<template>
  <section class="list-header">
    <p class="common-title">{{ ruleTitle }}</p>
    <section class="main-wrap">
      <span class="rule-name-label">分配规则</span>
      <div>
        <div v-for="(item, ind) in listData" :key="item.key">
          <div class="formObj-form-item">
            <section class="form-vl">
              <span>第{{ ind + 1 }}优先级</span>
              <!-- <el-select
                v-model="item.ruleKey"
                placeholder="请选择"
                size="small"
                clearable
                class="input-box"
                @change="(val) => ruleChange(val, ind)"
              >
                <el-option
                  v-for="(ot, oInd) in ruleArr"
                  :disabled="isChose(ot, oInd)"
                  :key="ot.value"
                  :label="ot.label"
                  :value="ot.value"
                ></el-option>
              </el-select> -->
              <treeselect class="input-box" :multiple="false" v-model="item.ruleKey" :options="ruleData" placeholder="请选择"
                :show-count="false" noOptionsText="暂无数据" noResultsText="暂无数据" :limit="2"
                :limit-text="(count) => `+${count}`" :disable-branch-nodes="true" :alwaysOpen="false" :disabled="isEdit"
                :load-options="loadOptions" @select="(node) => onTreeSelect(node, ind)">
              </treeselect>
            </section>
            <section class="operate-areas">
              <el-button :disabled="listData.length === 1 || isEdit" type="text" icon="el-icon-remove-outline"
                class="gray-color" @click.prevent="onDel(ind)"></el-button>
              <el-button :disabled="isEdit"
                v-if="ind == listData.length - 1 && item.ruleKey != '3' && item.ruleKey != '8'" type="text"
                icon="el-icon-circle-plus-outline" class="gray-color" @click.prevent="onAdd(ind)"></el-button>
            </section>
          </div>
          <template v-if="item.ruleKey && ruleId.includes(item.ruleKey)">
            <section class="user-info">
              <span>归属机构</span>
              <treeselect ref="orgTree" size="small" :multiple="true" v-model="item.userDeptList" :options="deptOptions"
                placeholder="请选择" :show-count="true" noOptionsText="暂无数据" noResultsText="暂无数据"
                @select="(node) => onDeptTreeSelect(node, ind)" @deselect="(node) => clearTreeSelect(node, ind)"
                @open="onOrgTreeFocus" :flat="true" :disabled="isEdit" />
            </section>
            <section class="user-info">
              <span>客户经理</span>
              <el-select @focus="onClientManagerFocus" ref="clientManager" v-model="item.userName" multiple
                :multiple-limit="0" size="small" filterable placeholder="请选择" class="input-box" :disabled="isEdit">
                <el-option v-for="option in managerOptions" :key="option.userId"
                  :label="`${option.deptName}-${option.userName}-${option.nickName}`"
                  :value="option.userName"></el-option>
              </el-select>
            </section>
          </template>
        </div>
      </div>
    </section>
  </section>
</template>

<script>
import { getRuleShape } from "@/api/grid/draw-area.js";
import { uid } from "@/utils";
import { isEmpty, cloneDeep, omit } from "lodash";
import { getUserListByDeptIds } from "@/api/grid/region.js";
import { getUserProfile } from '@/api/grid/anchor.js'
import { mapGetters } from "vuex";

const relateTypeMap = {
  personal: "个人",
  company: "企业",
  merchant: "商户",
};

export default {
  props: {
    ruleTitle: {
      type: String,
      default: "",
    },
    ruleArr: {
      type: Array,
      default: () => [],
    },
    ruleId: {
      type: String,
      default: "8",
    },
    ruleName: {
      type: String,
      default: "",
    },
    defaultListData: {
      type: Array,
      default: () => [],
    },
    deptOptions: {
      type: Array,
      default: () => [],
    },
    userChecked: {
      type: Array,
      default: () => [],
    },
    clientType: {
      type: Object,
      default: () => { },
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    opsDept1: {
      type: String,
      default: undefined,
    },
  },
  computed: {
    ...mapGetters(["roles"]),
  },
  watch: {
    listData: {
      handler(arr) {
        this.$emit("getRuleArr", {
          arr: arr?.map((ot, oInd) =>
            omit(
              cloneDeep({
                ...ot,
                ruleOrder: oInd + 1,
              }),
              "key"
            )
          ),
          ruleName: this.ruleName,
        });

        let listArr = [];
        this.listData?.map((ot) => {
          ot.ruleKey && listArr.push(ot.ruleKey);
        });
        this.ruleData = this.setDisable(this.ruleData, listArr);
      },
      deep: true,
    },
    defaultListData: {
      handler(arr) {
        if (!isEmpty(arr)) {
          this.listData = arr?.map((it) => {
            if (it.userDeptList && it.userDeptList.length > 0) {
              this.fetchSelectOptions(it.userDeptList);
            }
            if (it.layerId && it.ruleKey) {
              let newKey =
                it.ruleKey == '90' ? '0' :
                  it.ruleKey == '91' ? '1' :
                    it.ruleKey == '92' ? '2' : ''
              if (!this.hasLoad[newKey]) {
                this.hasLoad[newKey] = true;
                this.getSpecialRule(newKey)
              }
              return {
                ...it,
                ruleKey: it.layerId,
                key: uid(),
              };
            }
            return {
              ...it,
              ruleKey: `${it.ruleKey}`,
              key: uid(),
            };
          });
        }
      },
      deep: true,
      immediate: true,
    },
    clientType: {
      handler(arr) {
        this.ruleData = this.setDisable(this.ruleData, []);
      },
      deep: true,
      immediate: true,
    },
    roles: {
      handler(val) {
        if (val) {
          if (val.includes("headPrivate")) {
            // 零售部
            this.opsDept = "0";
          } else if (val.includes("headPublic")) {
            // 公司部
            this.opsDept = "1";
          } else if (val.includes("headOps")) {
            // 运管部
            this.opsDept = "2";
          } else {
            this.opsDept = undefined;
          }
          this.ruleData = this.setDisable(this.ruleData, []);
        }
      },
      immediate: true,
    },
    opsDept1: {
      handler(val) {
        if (val) {
          this.opsDept = val || undefined;
          this.ruleData = this.setDisable(this.ruleData, []);
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      listData: [
        {
          ruleKey: null,
          key: uid(),
          relateType: relateTypeMap[this.ruleName],
        },
      ],
      checkedArr: [], // 选择的机构ID
      managerOptions: [], // 客户经理
      ruleData: [],
      opsDept: undefined,
      hasLoad: ["", "", ""],
    };
  },
  created() {
    this.getUser()
  },
  methods: {
    getUser() {
      getUserProfile().then(res => {
        this.deptId = res.data.dept.deptId
        let deptIdChars = String(this.deptId).substring(0, 3)
        if (deptIdChars == '931') {
          this.ruleData = [
           
            {
              label: "按行政网格归属",
              id: "2",
              children: [
                {
                  label: "按零售部行政网格归属",
                  id: "20",
                  key: "0",
                },
                {
                  label: "按公司部行政网格归属",
                  id: "21",
                  key: "1",
                },
                {
                  label: "按运管部行政网格归属",
                  id: "22",
                  key: "2",
                },
              ],
            },
            {
              label: "按自绘地图网格归属",
              id: "9",
              children: [
                {
                  label: "按零售部自绘地图网格归属",
                  id: "90",
                  key: "0",
                  children: null,
                },
                {
                  label: "按公司部自绘地图网格归属",
                  id: "91",
                  key: "1",
                  children: null,
                },
                {
                  label: "按运管部自绘地图网格归属",
                  id: "92",
                  key: "2",
                  children: null,
                },
              ],
            },
            {
              label: "随机平均分配",
              id: "8",
            },
            {
              label: "手动指定",
              id: "3",
            },
          ]
        } else {
          this.ruleData = [
            {
              label: "按贷款归属",
              id: "4",
            },
            {
              label: "按存款归属",
              id: "5",
            },
            {
              label: "按全员营销归属",
              id: "6",
              children: [
                {
                  label: "信用卡营销",
                  id: "203205",
                },
                {
                  label: "信用卡责任",
                  id: "203207",
                },
                {
                  label: "代发工资有效户",
                  id: "204202",
                },
                {
                  label: "国际业务结算",
                  id: "207201",
                },
                {
                  label: "国际业务贸易融资",
                  id: "207202",
                },
              ],
            },
            // {
            //   label: '按代发薪归属',
            //   id: '7'
            // },
           
            {
              label: "按行政网格归属",
              id: "2",
              children: [
                {
                  label: "按零售部行政网格归属",
                  id: "20",
                  key: "0",
                },
                {
                  label: "按公司部行政网格归属",
                  id: "21",
                  key: "1",
                },
                {
                  label: "按运管部行政网格归属",
                  id: "22",
                  key: "2",
                },
              ],
            },
            {
              label: "按自绘地图网格归属",
              id: "9",
              children: [
                {
                  label: "按零售部自绘地图网格归属",
                  id: "90",
                  key: "0",
                  children: null,
                },
                {
                  label: "按公司部自绘地图网格归属",
                  id: "91",
                  key: "1",
                  children: null,
                },
                {
                  label: "按运管部自绘地图网格归属",
                  id: "92",
                  key: "2",
                  children: null,
                },
              ],
            },
            {
              label: "随机平均分配",
              id: "8",
            },
            {
              label: "手动指定",
              id: "3",
            },
          ]
        }
      })
    },
    // 查询特色规则
    getSpecialRule(key) {
      getRuleShape({ opsDept: key }).then((res) => {
        if (res.code === 200) {
          const newData = res.data.map((item) => {
            return {
              label: item.layerName,
              id: item.layerId,
              layerId: item.layerId,
              parentKey: key,
              // isExpanded:true
            };
          });
          this.ruleData = this.ruleData.map(item => {
            if (item.id === '9') {
              let children = item.children;
              children[key].children = newData;
              return {
                ...item,
                children
              }
            }
            return item;
          })
        }
      });
    },
    //分配规则
    onTreeSelect(node, ind) {
      console.log(node);
      if (node.layerId) {
        let obj = this.listData[ind];
        obj.layerId = node.layerId;
        obj.parentKey = node.parentKey;
        this.listData.splice(ind, 1, obj);
      } else {
        let obj = this.listData[ind];
        delete obj.layerId;
        delete obj.parentKey;
        this.listData.splice(ind, 1, obj);
      }
    },
    onAdd(tag) {
      const newItems = {
        ruleKey: null,
        key: uid(),
        relateType: relateTypeMap[this.ruleName],
      };
      this.listData.splice(tag + 1, 0, newItems);
    },
    onDel(index) {
      this.listData.splice(index, 1);
    },
    isChose(row, tag) {
      const listArr = this.listData?.filter((ot) => ot.ruleKey === row.value);
      return !isEmpty(listArr);
    },
    setDisable(data, ids) {
      return data.map((v) => {
        v.isDisabled = ids.includes(v.id);
        if (v.key && this.opsDept >= 0) {
          v.isDisabled = v.key !== this.opsDept;
        }
        if (v.children && v.children.length > 0) {
          this.setDisable(v.children, ids);
        }
        return v;
      });
    },
    loadOptions({ action, parentNode, callback }) {
      if (action === "LOAD_CHILDREN_OPTIONS") {
        if (!parentNode.key) {
          parentNode.children = [
            {
              label: "暂无数据",
              id: "8888",
              isDisabled: true,
            },
          ];
          callback();
          return;
        }
        if (this.hasLoad[parentNode.key]) {
          callback();
          return;
        }
        getRuleShape({ opsDept: parentNode.key }).then((res) => {
          if (res.code === 200) {
            const newData = res.data.map((item) => {
              return {
                label: item.layerName,
                id: item.layerId,
                layerId: item.layerId,
                parentKey: parentNode.key,
              };
            });
            parentNode.children =
              newData.length > 0
                ? newData
                : [
                  {
                    label: "暂无数据",
                    id: "8888",
                    isDisabled: true,
                  },
                ];
            callback();
          }
        });
      }
    },
    // 选择归属机构
    onDeptTreeSelect(node, index) {
      // console.log('勾选');
      const { children = [] } = node;
      const childrenArr = children.map((child) => child.id);
      this.checkedArr = [
        ...new Set([
          ...this.checkedArr,
          ...this.userChecked,
          node.id,
          ...childrenArr,
        ]),
      ];
      this.fetchSelectOptions(this.checkedArr);
    },
    // 取消勾选归属机构
    clearTreeSelect(node, ind) {
      // console.log('取消', node);
      const index = this.checkedArr.findIndex((id) => id === node.id);
      if (index > -1) {
        this.checkedArr.splice(index, 1);
      }
      const { children = [] } = node;
      if (children.length > 0) {
        children.map((child) => {
          const index = this.checkedArr.findIndex((id) => id === child.id);
          if (index > -1) {
            this.checkedArr.splice(index, 1);
          }
        });
      }
      this.fetchSelectOptions(this.checkedArr, ind);
    },
    fetchSelectOptions(deptIds, ind = undefined) {
      if (isEmpty(deptIds)) {
        if (
          ind !== undefined &&
          this.ruleId.includes(this.listData[ind].ruleKey)
        ) {
          this.listData[ind].userName = [];
        }
        return (this.managerOptions = []);
      }
      getUserListByDeptIds({ deptIds: deptIds }).then((response) => {
        this.managerOptions = response.data;
        this.setListData(ind);
      });
    },
    setListData(ind) {
      if (
        ind !== undefined &&
        this.ruleId.includes(this.listData[ind].ruleKey)
      ) {
        const userName = this.listData[ind].userName;
        const newuserName = userName.filter((id) => {
          const _ind = this.managerOptions.findIndex(
            (item) => item.userName === id
          );
          if (_ind > -1) {
            return id;
          }
        });
        this.listData[ind].userName = newuserName;
      }
    },
    onOrgTreeFocus() {
      // this.$refs.clientManager.blur()
    },
    onClientManagerFocus() {
      // this.$refs.orgTree.blurInput()
    },
    ruleChange(val, index) {
      if (!this.ruleId.includes(val)) {
        delete this.listData[index].userName;
        delete this.listData[index].userDeptList;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.common-title {
  position: relative;
  color: #222222;
  line-height: 16px;
  font-weight: 600;
  font-size: 16px;
  padding-left: 10px;
  margin: 0 20% 20px 34px;

  &::before {
    position: absolute;
    top: 50%;
    transform: translatey(-50%);
    left: 0;
    content: "";
    width: 3px;
    background-color: #4886f8;
    height: 16px;
    border-radius: 2px;
  }
}

.formObj-form-item {
  display: flex;
  align-items: center;

  .operate-areas {
    margin-left: 16px;

    ::v-deep .el-icon-circle-plus-outline {
      color: #4886f8;
      font-size: 20px;
    }

    ::v-deep .el-icon-remove-outline {
      font-size: 20px;
    }

    ::v-deep .gray-color {
      color: #999999;
    }
  }

  .form-vl {
    display: flex;
    align-items: center;

    span {
      margin-right: 10px;
      font-size: 14px;
      color: #606266;
    }

    .input-box {
      width: 440px;

      .option-label {
        color: #4d4d4d;
        line-height: 26px;
      }

      ::v-deep .vue-treeselect__label {
        color: #4d4d4d;
        line-height: 26px;
      }

      ::v-deep .vue-treeselect__option--disabled .vue-treeselect__label {
        color: #aaa;
        line-height: 26px;
      }
    }
  }
}

.user-info {
  margin-bottom: 5px;
  margin-left: 26px;
  display: flex;
  align-items: center;

  ::v-deep .vue-treeselect__control {
    width: 415px;
    height: 32px;
  }

  span {
    margin-right: 10px;
    font-size: 14px;
    color: #606266;

    &::before {
      content: "*";
      left: -3px;
      color: #ff4d42;
      position: relative;
      top: 2px;
    }
  }

  .input-box {
    width: 415px;
  }
}

.main-wrap {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;

  .rule-name-label {
    width: 140px;
    text-align: right;
    padding-right: 24px;
    line-height: 36px;
    font-size: 14px;
    font-weight: 400;
    color: #3d3d3d;

    &::after {
      content: "*";
      left: 5px;
      color: #ff4d42;
      position: relative;
      top: 2px;
    }
  }

  ul {
    li {
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>