<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="tagName2"
          label="标签类型"
          is-link
          readonly
          placeholder="请选择"
          @click="showPicker = true"
        ></van-field>
        <van-popup
          v-model="showPicker"
          position="bottom"
        >
          <div class="btn-box">
            <van-button
              type="info"
              plain
              size="mini"
              @click="showPicker = false"
            >
              取消
            </van-button>
            <van-button
              type="info"
              size="mini"
              @click="tagOK"
            >
              确定
            </van-button>
          </div>
          <div class="cas-box">
            <el-cascader-panel
                v-model="tagName"
                :options="selectTagsList"
                :props="tagProps"
                @change="tagChangeFn"
                ref="cascader"
            ></el-cascader-panel>
          </div>
        </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 showTagsList1"
          :key="index"
          :style="{
            'margin-right': '16px',
            'margin-bottom': '8px',
            cursor: editTag ? 'pointer' : 'default',
          }"
          size="large"
          :type="item.enableFlag == true ? 'primary' : 'default'"
          :closeable="editTag && item.enableFlag == true"
          @click="handleClickTag(item)"
          @close="handleCloseTag(item)"
          >{{ editTag ? item.pathLabels : item.names }}</van-tag
        >
      </div> -->
    </div>
  </div>
</template>

<script>
import navbar from "../../components/navbar/navbar.vue";
import { getTagList1, editCustTag1 } from "@/service/api/custome";
import { Button, Field, Tag, Sticky, Toast, Form, Picker, TreeSelect } 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:[],
      tagName1: [],
      tagName2: [],
      showPicker:false,
      selectTagsList:[],
      showTagsList:[],
      showTagsList1:[],
      addTagName:"",
      newCustTag:[],
      activeIndex: 0, // 左侧选中项索引
      activeId: "", // 右侧选中的ID
      tagProps: {
        label: "names",
        value: "id",
        children: "children",
        checkStrictly: true,
      },
      siblingsNodes: [],
      childrenNodes: [],
      activeTab: null,
      labelList: [],
      delName: ''
    };
  },
  components: {
    navbar: navbar,
    VanButton: Button,
    VanField: Field,
    VanTag: Tag,
    VanSticky: Sticky,
    VanToast: Toast,
    VanForm: Form,
    VanPicker: Picker,
    VanTreeSelect: TreeSelect,
    RenderChildren
  },
  created() {
    this.init();
  },
  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"
        }
      }
      getTagList1(custId,custType).then((res) => {
        if (res.code === 200) {
          this.tagsList = cloneDeep(res.data) || [];
          this.originTagList = cloneDeep(res.data) || [];
          this.selectTagsList = this.filterNodes(res.data);
          this.showTagsList1 = this.collectNamesWithFlagALL(this.tagsList, '');
          this.activeTab = this.tagsList[0].names
          this.labelList = this.flattenNodes(this.tagsList)
        }
      });
    },
    filterNodes(nodes) {
      // return nodes.map((node) => {
      //   if (node.children) {
      //       if (node.children.length === 0) {
      //           delete node.children
      //       } else {
      //           this.filterNodes(node.children)
      //       }
      //   }
      //   return node;
      // });
      const newNodes = nodes.filter(child => child.children.length > 0)
      return newNodes.map((node) => {
        if (node.children) {
            if (node.children.length === 0) {
                delete node.children
            } else {
                node.children = node.children.filter(child => child.children.length > 0)
                if (node.children.length === 0) {
                    delete node.children
                } else {
                  this.filterNodes(node.children)
                }
            }
        }
        return node;
      });
    },

    handleClickTag(val) {
      if (!this.editTag || val.enableFlag == true) return;
      this.showTagsList1.filter(
        (item) => item.names === val.names
      )[0].enableFlag = true;
    },
    handleCloseTag(val) {
      this.showTagsList1.filter(
        (item) => item.names === val.names
      )[0].enableFlag = false;
    },
    handleEditTag() {
      this.editTag = true;
    },
    handleCancelEditTag() {
      this.editTag = false;
      this.tagsList = cloneDeep(this.originTagList);
      this.labelList = this.flattenNodes(this.tagsList)
    },
    tagChangeFn() {
      this.showTagsList = [];
      if (this.tagName.length > 0) {
        const currentNode = this.$refs.cascader.getCheckedNodes()[0]
        this.tagName1 = currentNode?.pathLabels?.join(',')
        this.siblingsNodes = currentNode?.parent ? currentNode?.parent?.children??[] : this.selectTagsList // 同级数据
        // this.childrenNodes = currentNode?.children??[] // 子级数据
        // this.childrenNodes.map(item => {
        //     if (item.children.length === 0) {
        //         this.showTagsList.push({
        //             ...item.data
        //         }) // 要点亮的标签
        //     }
        // })

        const pathLabels = currentNode?.pathLabels?.join('-')
        this.childrenNodes = this.findChildNodes(this.tagsList)
        this.showTagsList = this.childrenNodes.filter(v => v.children.length === 0).map(v => ({ ...v, pathLabels: `${pathLabels}-${v.names}` })) // 要点亮的标签
      }
    },
    tagOK() {
      this.tagName2 = this.tagName1
      this.showTagsList1 = this.showTagsList
      this.showPicker = false
    },
    findChildNodes(nodes) {
      for (let node of nodes) {
        if (node.id === this.tagName[this.tagName.length - 1]) {
          return node.children
        } else if (node.children) {
          const found = this.findChildNodes(node.children)
          if (found) {
            return found
          }
        }
      }
    },
    collectNamesWithFlagALL(nodes, parentName = '') {
      return _.flatMap(nodes, (node) => {
        // 1. 收集当前节点
        const pathLabels = parentName ? `${parentName}-${node.names}` : node.names
        const current = node.children.length === 0 ? [{ ...node, pathLabels }] : []
        // 2. 递归处理 children（若存在）并获取子节点中符合的 name
        const children = _.get(node, "children", []);
        const childNames = children.length
          ? this.collectNamesWithFlagALL(children, pathLabels) // 递归处理子节点
          : [];
        // 3. 合并当前节点和子节点的结果
        return [...current, ...childNames];
      });
    },
    collectNamesWithFlagTrue(nodes) {
      return _.flatMap(nodes, (node) => {
        // 1. 收集当前节点的name（若 flag 为 true）
        const current = node.enableFlag ? [{ custTagName: node.names, id: node.id }] : [];
        // 2. 递归处理 children（若存在）并获取子节点中符合的 name
        const children = _.get(node, "children", []);
        const childNames = children.length
          ? this.collectNamesWithFlagTrue(children) // 递归处理子节点
          : [];
        // 3. 合并当前节点和子节点的结果
        return [...current, ...childNames];
      });
    },
    handleSaveTag() {
      const custTagList = Object.values(this.labelList).map(item => ({
        custTagName: item.names,
        id: item.id
      }))
      // const custTagList = this.collectNamesWithFlagTrue(this.tagsList)
      // this.showTagsList1.map(item => {
      //   if (item.enableFlag) {
      //       const index = custTagList.findIndex(tag => tag.id === item.id)
      //       if (index < 0) {
      //           custTagList.push({
      //               custTagName: item.names, 
      //               id: item.id
      //           })
      //       }
      //   } else {
      //       const index = custTagList.findIndex(tag => tag.id === item.id)
      //       if (index > -1) {
      //           custTagList.splice(index, 1)
      //       }
      //   }
      // })
      let custType=""
      if(this.custType){
        custType=this.custType
      }else{
        if(sessionStorage.getItem("custType") == '2'){
          custType="gs"
        }else{
          custType="ls"
        }
      }
      editCustTag1({
        custTagLight: custTagList, // 点亮的标签列表
        custId: sessionStorage.getItem("custId"),
        newManualTag: [], // 新增的标签列表
        updateManualTags: [], // 修改的标签列表
      }).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)
          }
        }
      });
    },
    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
    },
    updateEnableFlag(tree, targetName) {
      if(!Array.isArray(tree)) return false
      for (const node of tree) {
        if (node.names === targerName) {
          node.enableFlag = false
          return true
        }
        if (Array.isArray(node.children)) {
          const found = updateEnableFlag(node.children, targetName)
          if (found) return true
        }
      }
      return false
    }
  },
};
</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;
}

.cas-box {
    margin: 10px 10px 20px; 
    border: 1px solid #E4E7ED; 
    border-radius: 4px; 
    overflow: scroll; 
    ::v-deep .el-cascader-panel {
      border: none;
    }
}

.btn-box {
  display: flex;
  padding: 10px 10px 0;
  justify-content: space-between;
}
</style>
