<template>
  <el-collapse-item :name="nameKey">
    <template slot="title">
      <p class="common-title">自定义标签</p>
    </template>
    <div class="message-box">
      <div class="message-box-right">
        <div style="margin-bottom: 20px">
          <el-cascader-panel
            v-model="tagName"
            :options="selectTagsList"
            :props="tagProps"
            @change="tagChangeFn()"
            ref="cascader"
          ></el-cascader-panel>
        </div>
        <el-tag
          v-for="(item, index) in showTagsList"
          :key="index"
          :type="item.enableFlag == true ? '' : 'info'"
          :style="{
            'margin-right': '15px',
            'margin-bottom': '12px',
            cursor: editTag ? 'pointer' : 'default',
          }"
          :closable="editTag && item.enableFlag == true"
          @click="handleClickTag(item)"
          @close="handleCloseTag(item)"
          >{{ editTag ? item.pathLabels : item.names }}</el-tag
        >
        <div>
          <el-button
            v-if="!editTag"
            size="mini"
            type="primary"
            :disabled="selectTagsList.length === 0"
            @click="handleEditTag()"
          >
            编辑标签状态
          </el-button>
          <el-button
            v-if="!editTag"
            size="mini"
            type="primary"
            :disabled="tagName.length === 0"
            @click="resetTag()"
          >
            重置标签
          </el-button>
          <el-button v-if="editTag" size="mini" @click="handleCancelEditTag()"
            >取消</el-button
          >
          <el-button
            v-if="editTag"
            type="success"
            size="mini"
            @click="handleSaveTag()"
            >点亮标签</el-button
          >
          <!-- <el-input
            style="margin-left: 20px"
            v-if="editTag"
            v-model="addTagName"
            size="mini"
            placeholder="请输入新增客户标签"
          />
          <el-button
            style="margin-left: 20px"
            v-if="editTag"
            type="success"
            size="mini"
            @click="handleAddTag('ADD')"
          >
                新增
            </el-button>
          <el-button
            style="margin-left: 20px"
            v-if="editTag"
            type="success"
            size="mini"
            @click="handleAddTag('UPDATE')"
          >
                修改
            </el-button> -->
        </div>
      </div>
    </div>
  </el-collapse-item>
</template>
<script>
import { editCustTag1 } from "@/api/system/listByRetailKeywords.js";
import { cloneDeep } from "lodash";
import _ from "lodash";
let _node = {};
export default {
  props: {
    tagManualList: {
      type: Array,
      default: () => [],
    },
    nameKey: {
      type: String,
      default: 0,
    },
    typeKey: {
      type: String,
      default: 'ls',
    },
  },
  watch: {
    tagManualList: {
      handler(newVal) {
        const val = cloneDeep(newVal)
        this.getInitTags(val)
      },
      deep: true,
      immediate: true
    },
  },
  data() {
    return {
      editTag: false,
      tagName: [],
      tagProps: {
        label: "names",
        value: "id",
        children: "children",
        checkStrictly: true,
      },
      selectTagsList: [],
      showTagsList: [],
      addTagName: "",
      newCustTag: [],
      siblingsNodes: [],
      childrenNodes: []
    };
  },
  methods: {
    getInitTags(val) {
        this.selectTagsList = this.filterNodes(val);
        if (this.tagName.length) {
            const currentNode = this.$refs.cascader.getCheckedNodes()[0]
            this.siblingsNodes = currentNode?.parent ? currentNode?.parent?.children??[] : this.selectTagsList // 同级数据
            // this.childrenNodes = currentNode?.children??[] // 子级数据
            
            const pathLabels = currentNode?.pathLabels?.join('-')
            this.childrenNodes = this.findChildNodes(this.tagManualList)
            this.showTagsList = this.childrenNodes.filter(v => v.children.length === 0).map(v => ({ ...v, pathLabels: `${pathLabels}-${v.names}` })) // 要点亮的标签
        } else {
          this.showTagsList = this.collectNamesWithFlagALL(this.tagManualList, '');
        }
    },
    filterNodes(nodes) {
      // return nodes.map((node) => {
      //   if (node.children) {
      //       if (node.children.length === 0) {
      //           node.disabled = true
      //           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;
      });
    },
    handleAddTag(type) {
      if (!this.addTagName) {
        this.$message.error("请输入客户标签");
        return;
      }
      const dataNodes = type === 'ADD' ? this.childrenNodes : this.siblingsNodes
      let existsFlag = dataNodes.findIndex(tag => tag.names === this.addTagName || tag.label === this.addTagName)
      if (existsFlag >= 0) {
        this.$message.error("客户标签已存在");
        return;
      }
      const chooseId = this.tagName.length
          ? this.tagName[this.tagName.length - 1]
          : '';
      this.newCustTag = [{
        parentId: chooseId,
        custTagName: this.addTagName,
        custTagType: this.typeKey, // 企业客户传gs，商户和个人传ls
      }];
      const params = type === 'ADD' ?
      // 新增
      {
        custTagLight: [], // 点亮的标签列表
        custId: this.$route.query.custId,
        newManualTag: this.newCustTag, // 新增的标签列表
        updateManualTags: [], // 修改的标签列表
      } : 
      // 修改
      {
        custTagLight: [], // 点亮的标签列表
        custId: this.$route.query.custId,
        newManualTag: [], // 新增的标签列表
        updateManualTags: [{
            id: chooseId,
            custTagName: this.addTagName,
        }], // 修改的标签列表
      }
      this.addTagName = "";
      editCustTag1(params).then((res) => {
        if (res.code === 200) {
          this.$message.success(type === 'ADD' ? "新增成功" : "修改成功");
          this.$emit('getDetailData')
        }
      });
    },
    handleEditTag() {
      this.editTag = true;
    },
    handleCancelEditTag(type) {
      this.handleSaveTag()
      this.editTag = false;
      this.tagName = []
    },
    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 = this.collectNamesWithFlagTrue(this.tagManualList);
      this.showTagsList.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)
            }
        }
      })
      editCustTag1({
        custTagLight: custTagList, // 点亮的标签列表
        custId: this.$route.query.custId,
        newManualTag: [], // 新增的标签列表
        updateManualTags: [], // 修改的标签列表
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success("标签修改成功");
          this.$emit('getDetailData')
        }
      });
    },
    tagChangeFn() {
      this.showTagsList = [];
      if (this.tagName.length > 0) {
        const currentNode = this.$refs.cascader.getCheckedNodes()[0]
        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,
        //             pathLabels: item?.pathLabels?.join('-')
        //         }) // 要点亮的标签
        //     }
        // })
        const pathLabels = currentNode?.pathLabels?.join('-')
        this.childrenNodes = this.findChildNodes(this.tagManualList)
        this.showTagsList = this.childrenNodes.filter(v => v.children.length === 0).map(v => ({ ...v, pathLabels: `${pathLabels}-${v.names}` })) // 要点亮的标签
      }
    },
    resetTag() {
      this.tagName = []
      this.showTagsList = this.collectNamesWithFlagALL(this.tagManualList, '');
    },
    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
          }
        }
      }
    },
    handleClickTag(val) {
      if (!this.editTag || val.enableFlag == true) return
      this.showTagsList.filter(
        (item) => item.id === val.id
      )[0].enableFlag = true
    },
    handleCloseTag(val) {
      this.showTagsList.filter(
        (item) => item.id === val.id
      )[0].enableFlag = false
    },
  },
};
</script>
<style lang="scss" scoped>
.common-wrap-cnt {
  background-color: #ffffff;
  overflow: hidden;
  box-shadow: 0 3px 8px 0 #00000017;
  border-radius: 16px 16px 0 0;
  height: calc(100vh - 135px);
  overflow-y: auto;
}

.tree-border {
  max-height: 300px;
  width: 100%;
  overflow-y: auto;
}
.create-form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebebeb;
  padding: 0 30px;
  .form-title {
    font-weight: 600;
    font-size: 18px;
    color: #222222;
    letter-spacing: 0.5px;
    line-height: 25px;
  }
  .form-operate {
  }
}
.common-title {
  position: relative;
  color: #222222;
  line-height: 16px;
  font-weight: 600;
  font-size: 16px;
  padding-left: 10px;
  margin: 0;
  &::before {
    position: absolute;
    top: 50%;
    transform: translatey(-50%);
    left: 0;
    content: '';
    width: 3px;
    background-color: #4886f8;
    height: 16px;
    border-radius: 2px;
  }
}
.common-create-main {
  padding: 24px 30px;
  ::v-deep .el-form {
    width: 70%;
    margin: 24px auto 0 auto;
    .el-form-item {
      margin-bottom: 16px;
      .el-input__inner {
        border: 1px solid #ebebeb;
        color: #3d3d3d;
      }
    }
    .el-form-item__label {
      font-weight: 400;
      line-height: 38px;
      font-size: 14px;
      color: #3d3d3d;
      padding-right: 24px;
    }
    .is-required .el-form-item__label {
      &::after {
        content: '*';
        left: 5px;
        color: #ff4d42;
        position: relative;
        top: 2px;
      }
      &::before {
        content: '';
      }
    }
  }
}

.message-box {
  display: flex;
  margin: 20px;
}

::v-deep .el-input {
  width: 600px;
}
</style>
