<template>
  <el-dialog
    class="modal-wrap"
    append-to-body
    :title="titleName"
    :visible.sync="visible"
    width="700px"
    @close="resetForm('allocForm')"
  >
    <div class="modal-cnt">
      <el-form
        :model="allocForm"
        :rules="allocRules"
        ref="allocForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="选择客户" prop="custName" class="tree-select" v-if="perInfo.gridId">
          <el-input
            v-model="allocForm.custName"
            filterable
            placeholder="请选择"
            class="choose"
            disabled
          />
        </el-form-item>
        <el-form-item label="选择客户" prop="custId" class="tree-select" v-else>
          <el-select
            v-model="allocForm.custId"
            filterable
            placeholder="请选择"
            class="choose"
          >
            <el-option
              v-for="option in custOptions"
              :key="`${option.custId}-${option.custType}`"
              :label="option.custName"
              :value="`${option.custId}-${option.custType}`"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属机构" class="tree-select" prop="deptTree">
          <treeselect
            ref="orgTree"
            :multiple="true"
            v-model="allocForm.deptTree"
            :options="deptOptions"
            placeholder="请选择"
            :show-count="true"
            noOptionsText="暂无数据"
            noResultsText="暂无数据"
            :limit="2"
            :limit-text="(count) => `+${count}`"
            @select="onDeptTreeSelect"
            @deselect="clearTreeSelect"
            @input="handleInput"
            @open="onOrgTreeFocus"
            :flat="false"
          />
        </el-form-item>
        <el-form-item label="客户经理" prop="userName" class="tree-select">
          <el-select
            @focus="onClientManagerFocus"
            ref="userName"
            v-model="allocForm.userName"
            multiple
            :collapse-tags="false"
            :multiple-limit="0"
            size="small"
            style="width: 100%"
            filterable
            clearable
            placeholder="请选择"
            @change="$forceUpdate()"
          >
            <el-option
              v-for="option in managerOptions"
              :key="option.userId"
              :label="`${option.deptName}-${option.userName}-${option.nickName}`"
              :value="option.userName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="operate-btn">
      <el-button @click="resetForm('allocForm')">取消</el-button>
      <el-button type="primary" @click="onSubmit('allocForm')">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { virtualCustAdd, virtualCustSearch } from "@/api/grid/list/gridlist";
import { getUserListByDeptIds } from '@/api/grid/region.js'
import { getDeptTree } from "@/api/grid/address/tree.js";

export default {
  components: {},
  props: ['gridId', 'titleName', 'perInfo'],
  watch: {
    visible(val) {
      if (val) {
        this.getCustData();
      }
    },
    perInfo: {
      handler(val) {
        this.allocForm.custName = val.custName;
        this.allocForm.custId = val.custId;
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    checkList() {
      if (isEmpty(this.indicatorsGroupName.trim())) {
        return this.listIndicatorsGroup;
      }
      return this.listIndicatorsGroup.filter((item) =>
        item.indicatorsGroupName.includes(this.indicatorsGroupName.trim())
      );
    },
  },
  data() {
    return {
      custOptions: [],
      deptOptions: [],
      managerOptions: [],
      visible: false,
      allocForm: {
        custId: '',
        custName: '',
        deptTree: [],
        userName: [],
      },
      allocRules: {
         custId: [
          {
            required: true,
            message: "请选择客户",
            trigger: "change",
          },
        ],
        deptTree: [
          {
            validator: (rule, value, callback) => {
                const checkedKeys = this.allocForm.deptTree;
                if (checkedKeys.length === 0) {
                  callback(new Error("机构不能为空"));
                } else {
                  callback();
                }
            },
            required: true,
            trigger: "change",
          },
        ],
        userName: [
          {
            validator: (rule, value, callback) => {
                const checkedKeys = this.allocForm.userName;
                if (checkedKeys.length === 0) {
                  callback(new Error("客户经理不能为空"));
                } else {
                  callback();
                }
            },
            required: true,
            trigger: "blur",
          },
        ],
      },
      checkedArr: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10000
      },
    };
  },
  created() {
    this.getDeptTreeSelect();
  },
  methods: {
    getDeptTreeSelect() {
      getDeptTree().then((response) => {
        this.deptOptions = response.data;
      });
    },
    async getCustData(params) {
      const res = await virtualCustSearch({
        gridId: this.perInfo.gridId || this.gridId,
        ...params,
        ...this.queryParams
      });
      this.custOptions = res?.data || [];
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.visible = false;
      this.$emit('close-modal');
    },
    async onSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let data = [];
          this.allocForm.userName.map(userName => {
            data.push({
                gridId: this.perInfo.gridId || this.gridId,
                custId: this.allocForm.custId.split('-')[0],
                custType: this.allocForm.custId.split('-')[1],
                userName: userName,
            });
          });
            const res = await virtualCustAdd(data);
            if (res.code === 200) {
                this.resetForm('allocForm');
                this.$message.success('手动绑定成功');
                if (this.perInfo.gridId) {
                  this.$emit('update-list')
                }
            }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return (
        data.label.indexOf(value) !== -1 ||
        String(data.id).indexOf(value) !== -1
      );
    },
    onOpen() {
      this.visible = true;
    },
    // 勾选归属机构
    onDeptTreeSelect(node) {
      const { children = [] } = node;
      const childrenArr = children.map((child) => child.id);
      this.checkedArr = [
        ...new Set([
          ...this.checkedArr,
          node.id,
          ...childrenArr,
        ]),
      ];
      this.fetchSelectOptions(this.checkedArr)
      this.$refs.allocForm.clearValidate('deptTree')
    },
    handleInput(selected) {
    },
    // 取消勾选归属机构
    clearTreeSelect(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)
    },
    fetchSelectOptions(deptIds, data = []) {
      if (deptIds.length === 0) {
        this.allocForm.userName = [];
        return (this.managerOptions = [])
      }
      getUserListByDeptIds({ deptIds: deptIds }).then((response) => {
        this.managerOptions = response.data;
        if (data.length > 0) {
          this.allocForm.userName = data.map(v => v.userName)
          return;
        }
        this.setuserName();
      })
    },
    setuserName() {
      const userName =this.allocForm.userName;
      const newuserName = userName.filter(id => {
        const _ind = this.managerOptions.findIndex(item => item.userName === id)
        if (_ind > -1) {
          return id
        }
      })
     this.allocForm.userName = newuserName;
    },
    onOrgTreeFocus() {
      this.$refs.userName.blur()
    },
    onClientManagerFocus() {
      this.$refs.orgTree.blurInput()
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}
.modal-cnt {
  .choose {
    width: 100%;
  }
  .tree-select{
    margin-bottom: 16px;
  }
}
::v-deep .operate-btn {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.modal-wrap {
  v-deep .el-tree-node__expand-icon.is-leaf {
    color: transparent !important;
  }
}
</style>