<template>
  <div class="message-box">
    <el-form
      ref="pushform"
      :model="pushform"
      :rules="pushroles"
      label-width="120px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="标签类型" prop="typeKey">
            <el-select
              v-model="pushform.typeKey"
              placeholder="请选择"
              style="width: 100%; margin-bottom: 10px"
              @change="selectChange"
            >
              <el-option
                v-for="dict in selectData"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="标签树" prop="tagName">
            <el-cascader-panel
              v-model="pushform.tagName"
              :options="selectTagsList"
              :props="tagProps"
              @change="tagChangeFn()"
              ref="cascader"
            ></el-cascader-panel>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="新增/修改标签" prop="addTagName">
            <el-input
              style="margin-bottom: 20px"
              v-model="pushform.addTagName"
              size="mini"
              placeholder="请输入新增/修改客户标签"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="text-align: right">
      <el-button type="primary" size="mini" @click="handleAddTag('ADD')">
        新增
      </el-button>
      <el-button
        style="margin-left: 20px"
        type="primary"
        size="mini"
        @click="handleAddTag('UPDATE')"
      >
        修改
      </el-button>
    </div>
  </div>
</template>
<script>
import { getcustomTag } from "@/api/system/listByRetailKeywords.js";
import { editCustTag1 } from "@/api/system/listByRetailKeywords.js";
import { cloneDeep } from "lodash";
import _ from "lodash";
let _node = {};
export default {
  data() {
    return {
      pushroles: {
        typeKey: [
          { required: true, message: "标签类型不能为空", trigger: "change" },
        ],
        addTagName: [
          { required: true, message: "该输入框不能为空", trigger: "blur" },
        ],
      },
      pushform: {
        typeKey: "gs",
        tagName: [],
        addTagName: "",
      },
      selectData: [
        {
          label: "企业",
          value: "gs",
        },
        {
          label: "个人/商户",
          value: "ls",
        },
      ],
      tagProps: {
        label: "names",
        value: "id",
        children: "children",
        checkStrictly: true,
      },
      selectTagsList: [],
      newCustTag: [],
      siblingsNodes: [],
      childrenNodes: [],
    };
  },
  methods: {
    selectChange(e) {
      this.initData();
    },
    filterNodes(nodes) {
      return nodes.map((node) => {
        if (node.children) {
          if (node.children.length === 0) {
            delete node.children;
          } else {
            this.filterNodes(node.children);
          }
        }
        return node;
      });
    },
    handleAddTag(type) {
      this.$refs["pushform"].validate((valid) => {
        if (valid) {
          if (!this.pushform.addTagName) {
            this.$message.error("请输入客户标签");
            return;
          }
          const dataNodes =
            type === "ADD" ? this.childrenNodes : this.siblingsNodes;
          let existsFlag = dataNodes.findIndex(
            (tag) =>
              tag.names === this.pushform.addTagName ||
              tag.label === this.pushform.addTagName
          );
          if (existsFlag >= 0) {
            this.$message.error("客户标签已存在");
            return;
          }
          const chooseId = this.pushform.tagName.length
            ? this.pushform.tagName[this.pushform.tagName.length - 1]
            : "";
          this.newCustTag = [
            {
              parentId: chooseId,
              custTagName: this.pushform.addTagName,
              custTagType: this.pushform.typeKey, // 企业客户传gs，商户和个人传ls
            },
          ];
          const params =
            type === "ADD"
              ? // 新增
                {
                  custTagLight: [], // 点亮的标签列表
                  custId: '',
                  newManualTag: this.newCustTag, // 新增的标签列表
                  updateManualTags: [], // 修改的标签列表
                }
              : // 修改
                {
                  custTagLight: [], // 点亮的标签列表
                  custId: '',
                  newManualTag: [], // 新增的标签列表
                  updateManualTags: [
                    {
                      id: chooseId,
                      custTagName: this.pushform.addTagName,
                    },
                  ], // 修改的标签列表
                };
          this.pushform.addTagName = "";
          editCustTag1(params).then((res) => {
            if (res.code === 200) {
              this.$message.success(type === "ADD" ? "新增成功" : "修改成功");
              this.initData();
            }
          });
        } else {
          console.error("新增失败", error);
        }
      });
    },
    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];
      });
    },
    tagChangeFn() {
      if (this.pushform.tagName.length > 0) {
        const currentNode = this.$refs.cascader.getCheckedNodes()[0];
        this.siblingsNodes = currentNode?.parent
          ? currentNode?.parent?.children ?? []
          : this.selectTagsList; // 同级数据
        this.childrenNodes = currentNode?.children ?? []; // 子级数据
      }
    },
    initData() {
      getcustomTag(this.pushform.typeKey).then((res) => {
        this.selectTagsList = this.filterNodes(res.data);
      });
    },
  },
  created() {
    this.initData();
  },
};
</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;
  flex-direction: column;
  width: 60%;
}
</style>
