<template>
  <div class="main_box">
    <navbar title="省行客户标签" v-if="!flag"></navbar>
    <div :class="[!flag?'main_f':'','main']">
      <van-sticky lass="button-box" :offset-top="46" v-if="!flag">
        <van-button
          v-if="!editTag"
          type="info"
          style="width: 100%"
          @click="handleEditTag"
          >编辑标签</van-button
        >
        <van-button
          v-if="editTag"
          type="info"
          style="width: 50%; margin-right: 32px"
          @click="handleSaveTag"
          >保存</van-button
        >
        <van-button
          v-if="editTag"
          type="info"
          plain
          style="width: 50%"
          @click="handleCancelEditTag"
          >取消</van-button
        >
      </van-sticky>
      <div v-if="flag" style="display:flex">
        <van-button
          v-if="!editTag"
          type="info"
          style="width: 100%"
          @click="handleEditTag"
          >编辑标签</van-button
        >
        <van-button
          v-if="editTag"
          type="info"
          style="width: 50%; margin-right: 32px"
          @click="handleSaveTag"
          >保存</van-button
        >
        <van-button
          v-if="editTag"
          type="info"
          plain
          style="width: 50%"
          @click="handleCancelEditTag"
          >取消</van-button
        >
      </div>
      <!-- <van-form ref="form">
        <van-field
          v-model="tagName"
          label="标签类型"
          is-link
          readonly
          placeholder="请选择"
          @click="showPicker = true"
        ></van-field>
        <van-popup
          v-model="showPicker"
          position="bottom"
          :style="{ height: '40%' }"
        >
          <van-picker
            show-toolbar
            :columns="selectTagsList"
            @cancle="showPicker = false"
            @confirm="confirmTagFn"
            @cancel="cancelTagFn"
          ></van-picker>
        </van-popup>
      </van-form> -->
      <van-sticky lass="button-box1" :offset-top="122">
        <div style="padding: 10px; max-height: 200px; overflow: auto; background-color: white">
          <span>已选择的标签：</span>
          <van-tag
            v-for="(item, index) in labelList"
            :key="index"
            style="margin: 10px"
            size="large"
            type="primary"
            :closeable="editTag == true"
            @close="handleCloseNew(item)"
          >{{ item.names }} </van-tag>
        </div>
      </van-sticky>
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane
          v-for="(item,index) in tagsList"
          :key="index"
          :label="item.names"
          :name="item.names"
        >
          <div v-if="item.children.length !== 0">
            <RenderChildren :children="item.children" :prefix="item.names" :editTag="editTag" :delName="delName" ></RenderChildren>
          </div>
          <div v-else>
            {{ item.names }}
          </div>
        </el-tab-pane>
      </el-tabs>
      <!-- <div class="main_top">
        <van-tag
          v-for="(item, index) in showTagsList"
          :key="index"
          :style="{
            'margin-right': '16px',
            'margin-bottom': '16px',
            cursor: editTag ? 'pointer' : 'default',
          }"
          size="large"
          :type="item.enableFlag == true ? 'primary' : 'default'"
          :closeable="editTag && item.enableFlag == true"
          @click="handleClickTag(item)"
          @close="handleCloseTag(item)"
          >{{ item.names }}</van-tag
        >
      </div> -->
      <!-- <div class="special_ipt" v-if="editTag">
        <van-field v-model="addTagName" label="" placeholder="请输入新增客户标签"></van-field>
        <van-button
          type="info"
          @click="handleAddTag"
          style="width:120px"
          >新增</van-button
        >
      </div> -->
    </div>
  </div>
</template>

<script>
import navbar from "../../components/navbar/navbar.vue";
import { getTagList, editCustTag } from "@/service/api/custome";
import { Button, Field, Tag, Sticky, Toast, Form, Picker } from "vant";
import { cloneDeep } from "lodash";
import _ from "lodash";
import RenderChildren from './RenderChildren.vue'
export default {
  props:{
    flag: {
      type: Boolean,
      default: false,   
    },
    custType: {
      type: String,
      default: "",   
    },
  },
  data() {
    return {
      originTagList: [],
      tagsList: [],
      editTag: false,
      tagName:[],
      showPicker:false,
      selectTagsList:[],
      showTagsList:[],
      addTagName:"",
      newCustTag:[],
      activeTab: null,
      labelList: [],
      delName: ''
    };
  },
  components: {
    navbar: navbar,
    VanButton: Button,
    VanField: Field,
    VanTag: Tag,
    VanSticky: Sticky,
    VanToast: Toast,
    VanForm: Form,
    VanPicker: Picker,
    RenderChildren
  },
  created() {
    this.init();
    console.log(111, this.flag)
  },
  provide() {
    return {
      onNodeUpdate: this.handleLabelChange
    }
  },
  methods: {
    init() {
      this.getTagInfo();
    },

    getTagInfo() {
      const custId = sessionStorage.getItem("custId");
      let custType=""
      if(this.custType){
        custType=this.custType
      }else{
        if(sessionStorage.getItem("custType") == '2'){
          custType="gs"
        }else{
          custType="ls"
        }
      }
      getTagList(custId,custType).then((res) => {
        if (res.code === 200) {
          this.tagsList = cloneDeep(res.data) || [];
          this.originTagList = cloneDeep(res.data) || [];
          this.selectTagsList=this.getTwoLevels(this.tagsList);
          this.tagName=[this.selectTagsList[0].text,this.selectTagsList[0].children[0].text];
          this.showTagsList=this.tagsList[0].children[0].children||[];
          this.activeTab = this.tagsList[0].names
          this.labelList = this.flattenNodes(this.tagsList)
        }
      });
    },
    getTwoLevels(nodes){
      return _.map(nodes, parent => ({
        text: parent.names,
        children: _.map(parent.children, child => ({
          text: child.names // 清除子节点的 children 属性
          // 或：_.omit(child, ['children']) // 如果需要保留其他属性
        }))
      }));
    },

    handleClickTag(val) {
      if (!this.editTag || val.enableFlag == true) return;
      this.showTagsList.filter(
        (item) => item.names === val.names
      )[0].enableFlag = true;
      this.updateListFn(this.showTagsList);
    },
    handleCloseTag(val) {
      console.log(val)
      this.showTagsList.filter(
        (item) => item.names === val.names
      )[0].enableFlag = false;
      this.updateListFn(this.showTagsList);
    },
    updateListFn(showTagsList){
      for(let i=0;i<this.tagsList.length;i++){
        if(this.tagsList[i].names == this.tagName[0]){
          for(let j=0;j<this.tagsList[i].children.length;j++){
            if(this.tagsList[i].children[j].names == this.tagName[1]){
              this.tagsList[i].children[j].children=showTagsList;
            }
          }
        }
      }
    },
    handleEditTag() {
      this.editTag = true;
    },
    handleCancelEditTag() {
      this.editTag = false;
      this.tagsList = cloneDeep(this.originTagList);
      this.labelList = this.flattenNodes(this.tagsList)
    },
    tagChangeFn(){
      for(let i=0;i<this.tagsList.length;i++){
        if(this.tagsList[i].names == this.tagName[0]){
          for(let j=0;j<this.tagsList[i].children.length;j++){
            if(this.tagsList[i].children[j].names == this.tagName[1]){
              this.showTagsList=this.tagsList[i].children[j].children||[];
            }
          }
        }
      }
    },
    collectNamesWithFlagTrue(nodes){
      return _.flatMap(nodes, (node) => {
        // 1. 收集当前节点的name（若 flag 为 true）
        const current = node.enableFlag ? [node.names] : [];
        // 2. 递归处理 children（若存在）并获取子节点中符合的 name
        const children = _.get(node, 'children', []);
        const childNames = children.length 
          ? this.collectNamesWithFlagTrue(children) // 递归处理子节点
          : [];
        // 3. 合并当前节点和子节点的结果
        return [...current, ...childNames];
      });
    },
    handleSaveTag() {
      console.log(this.labelList)
      const custTagList = Object.values(this.labelList).map(item => ({
        custTagName: item.names,
        id: item.id
      }))
      let custType=""
      if(this.custType){
        custType=this.custType
      }else{
        if(sessionStorage.getItem("custType") == '2'){
          custType="gs"
        }else{
          custType="ls"
        }
      }
      editCustTag({
        custTagList: custTagList,
        custId: sessionStorage.getItem("custId"),
        newCustTags:this.newCustTag,
        custTagType:custType
      }).then((res) => {
        if (res.code === 200) {
          Toast.success("修改成功");
          this.originTagList = cloneDeep(this.tagsList);
          this.editTag = false;
          this.init();
          if(this.$route.query.from) {
            this.$router.go(-1)
          }
        }
      });
    },
    confirmTagFn(val,index){
      this.tagName=val;
      this.tagChangeFn();
      this.showPicker=false;
    },
    cancelTagFn(){
      this.showPicker=false;
    },
    handleAddTag(){
      if(!this.addTagName){
        Toast.fail('请输入客户标签')
        return;
      }
      let existsFlag=_.includes(_.map(this.showTagsList,'names'),this.addTagName)
      if(existsFlag){
        Toast.fail('客户标签已存在')
        return;
      }
      this.showTagsList.push({
        children: [],
        enableFlag: true,
        names: this.addTagName,
        type: "",
        useFlag: false,
      })
      this.updateListFn(this.showTagsList);
      this.newCustTag.push({
        custTagLevel1:this.tagName.split(",")[0],
        custTagLevel2:this.tagName.split(",")[1],
        custTagName:this.addTagName,
      })
      this.addTagName="";
    },
    handleLabelChange(type, val) {
      if (type === 'add') {
        this.labelList.push(val)
      } else {
        this.labelList = this.labelList.filter(item => item.id !== val.id)
      }
    },
    flattenNodes(tree, visibleKey = 'enableFlag') {
      const result = []
      const traverse = (nodes ) => {
        if(!Array.isArray(nodes)) return

        nodes.forEach(node => {
          if (node[visibleKey] === true) {
            result.push({...node})
          }
          if (Array.isArray(node.children)) {
            traverse(node.children)
          }
        })
      }
      traverse(tree)
      return result
    },
    handleCloseNew(val) {
      this.labelList = this.labelList.filter(item => item.id !== val.id)
      this.delName = val.id
    }
  },
};
</script>

<style lang="less" scoped>
.main_f{
  padding-top: 46px;
  min-height: 100vh;
  padding-bottom: 60px;
}
.main {
  font-size: 16px;

  &_top {
    padding: 16px;
  }

  ::v-deep .van-sticky {
    display: flex;
    align-items: center;
    padding: 16px;
    background: #ffffff;
  }
}
.special_ipt{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
</style>
