<template>
  <div class="common-wrap-cnt">
    <section class="create-form-header">
      <p class="form-title">{{ pageName }}</p>
    </section>
    <section class="common-create-main">
      <p class="common-title">信息填写</p>
      <el-form
        ref="elForm"
        v-loading="pageLoading"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="140px"
        class="el-form-vir"
      >
        <el-form-item label="网格名称" prop="currentPageName">
          <el-input
            ref="nameInput"
            v-model="formData.currentPageName"
            minlength="2"
            placeholder="请输入网格名称"
            maxlength="20"
            size="small"
            @blur="onInputBlur"
          />
        </el-form-item>
        <el-form-item label="网格类型" prop="gridType">
          <el-select
            v-model="formData.gridType"
            placeholder="请选择网格类型"
            clearable
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option
              v-for="item in gridTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务部门归属" prop="opsDept">
          <el-radio-group
            v-model="formData.opsDept"
            size="medium"
            :disabled="opsDeptDisable || isEdit"
            @change="businessbelongChange"
          >
            <el-radio
              v-for="item in businessBelongList"
              :key="item.key"
              :label="item.key"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客户类型" prop="clientType">
          <el-checkbox
            v-model="allSelected"
            :disabled="isEdit || disabledclientType[0]"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
          <el-checkbox
            v-model="formData.clientType.personal"
            :disabled="isEdit || disabledclientType[1]"
            @change="hangleCheckedTypeChange"
          >个人</el-checkbox>
          <el-checkbox
            v-model="formData.clientType.merchant"
            :disabled="isEdit || disabledclientType[2]"
            @change="hangleCheckedTypeChange"
          >商户</el-checkbox>
          <el-checkbox
            v-model="formData.clientType.company"
            :disabled="isEdit || disabledclientType[3]"
            @change="hangleCheckedTypeChange"
          >企业</el-checkbox>
        </el-form-item>
        <el-form-item label="预计客户数" prop="clientNumber">
          <span>{{ tableList.length }}</span>
        </el-form-item>
        <el-form-item label="网格创建类型" prop="createMode">
          <el-radio-group
            v-model="formData.createMode"
            size="medium"
            :disabled="isEdit"
            @change="createModeChange"
          >
            <el-radio label="1">导入客户</el-radio>
            <el-radio label="2">导入管户</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="formData.createMode === '1'">
          <!-- 导入客户 -->
          <el-form-item label="导入客户" prop="importClient">
            <el-button
              type="primary"
              size="small"
              @click="handleImport"
            >上传文件</el-button>
            <input
              ref="fileInput"
              type="file"
              style="display: none"
              @change="handleFileUpload"
            >
            <el-button
              type="text"
              icon="el-icon-download"
              style="color: #4886f8; margin-left: 25px"
              @click="downloadFlie"
            >下载模板</el-button>
          </el-form-item>
          <el-form-item label="选择客户" prop="selectClient" class="chose-cnt">
            <el-select
              v-model="formData.selectClient"
              size="small"
              placeholder="选择分群"
              :disabled="isEdit"
              clearable
            >
              <el-option
                v-for="item in selectClientOptions"
                :key="item.groupId"
                :label="item.groupName"
                :value="item.groupId"
                :disabled="item.disabled"
              />
            </el-select>
            <el-button
              type="primary"
              :disabled="!formData.selectClient || isEdit"
              size="small"
              @click="uploadClient"
            >导入</el-button>
          </el-form-item>
          <el-form-item label="网格分配方式" prop="gridDistributionMode">
            <el-radio-group
              v-model="formData.gridDistributionMode"
              size="medium"
              :disabled="isEdit"
              @change="onGridDistributionModeChange"
            >
              <el-radio label="1">指定</el-radio>
              <el-radio
                v-if="
                  isHeadAdmin ||
                    isPublic ||
                    isPrivate ||
                    isHeadOps ||
                    isBranchAdmin ||
                    isOutletAdmin
                "
                :disabled="!isShowGridDistributionMode()"
                label="2"
              >自定义配置</el-radio>
              <el-radio
                v-if="isCommonManager"
                disabled
                label="2"
              >自定义配置</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="formData.gridDistributionMode === '1'"
            label="网格责任类型"
            prop="gridResponsibilityType"
          >
            <el-radio-group
              v-model="formData.gridResponsibilityType"
              size="medium"
              @change="onDutyTypeChange"
            >
              <el-radio label="1">
                责任网格
                <el-tooltip
                  placement="top"
                  trigger="hover"
                  content="一对一分配。一个网格只分配给一个支行"
                >
                  <span
                    class="quesiton"
                  ><i
                    class="el-icon-question question_icon"
                  /></span>
                </el-tooltip>
              </el-radio>
              <el-radio label="2">
                竞争网格
                <el-tooltip
                  placement="top"
                  trigger="hover"
                  content="一对多分配。同一个网格可以分配给多个支行"
                >
                  <span
                    class="quesiton"
                  ><i
                    class="el-icon-question question_icon"
                  /></span>
                </el-tooltip>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <section v-if="formData.gridDistributionMode === '2'">
            <template v-for="rule in configRules">
              <custom-rule
                :key="rule.key"
                :rule-title="rule.ruleTitle"
                :default-list-data="rule.defaultListData"
                :dept-options="deptOptions"
                :rule-id="ruleId"
                :rule-name="rule.ruleName"
                :client-type="formData.clientType"
                :is-edit="isEdit"
                :ops-dept1="opsDept"
                @getRuleArr="getRuleArr"
              />
            </template>
          </section>
          <template v-if="formData.gridDistributionMode === '1'">
            <!-- :multiple="true" -->
            <el-form-item label="归属机构" class="select-group" prop="deptTree">
              <treeselect
                ref="orgTree"
                v-model="formData.deptTree"
                :multiple="true"
                :options="belongDeptOptions"
                placeholder="请选择"
                :show-count="true"
                no-options-text="暂无数据"
                no-results-text="暂无数据"
                :flat="true"
                @select="onDeptTreeSelect"
                @deselect="clearTreeSelect"
                @input="handleInput"
                @open="onOrgTreeFocus"
              />
            </el-form-item>
            <!-- v-if="isShowGridDistributionMode()" -->
            <el-form-item
              label="客户经理"
              prop="clientManager"
              class="select-group"
            >
              <el-select
                ref="clientManager"
                v-model="formData.clientManager"
                multiple
                :multiple-limit="
                  formData.gridResponsibilityType === '2' ? 0 : 1
                "
                size="small"
                style="width: 100%"
                filterable
                placeholder="请选择"
                @focus="onClientManagerFocus"
              >
                <el-option
                  v-for="option in managerOptions"
                  :key="option.userId"
                  :label="`${option.deptName}-${option.userName}-${option.nickName}`"
                  :value="option.userName"
                />
              </el-select>
            </el-form-item>
          </template>
        </template>
        <template v-else>
          <!-- 导入管户关系 -->
          <el-form-item label="导入管户关系" prop="importClient">
            <el-button
              type="primary"
              size="small"
              @click="handleImport"
            >上传文件</el-button>
            <input
              ref="fileInput"
              type="file"
              style="display: none"
              @change="handleFileUpload"
            >
            <el-button
              type="text"
              icon="el-icon-download"
              style="color: #4886f8; margin-left: 25px"
              @click="downloadFlie"
            >下载模板</el-button>
          </el-form-item>
        </template>
      </el-form>
      <section class="preview-cnt">
        <p class="common-title">预览</p>
        <section class="table-wrap preview-table">
          <el-table :data="tableList" class="common-table-cnt">
            <el-table-column prop="custIsn" label="客户内码" />
            <el-table-column prop="custType" label="客户类型" />
            <el-table-column label="客户证件类型" prop="custIdType">
              <!-- <template slot-scope="scope">
                <span v-if="scope.row.custType == '个人'">
                  {{ scope.row.custIdType }}
                </span>
                <span v-if="scope.row.custType == '商户' || scope.row.custType == '企业'">
                  {{ scope.row.socialCreditCodeType }}
                </span>
              </template> -->
            </el-table-column>
            <el-table-column label="客户证件号" prop="custIdn">
              <!-- <template slot-scope="scope">
                <span v-if="scope.row.custType == '个人'">
                  {{ scope.row.custId }}
                </span>
                <span v-if="scope.row.custType == '商户' || scope.row.custType == '企业'">
                  {{ scope.row.socialCreditCode }}
                </span>
              </template> -->
            </el-table-column>
            <el-table-column prop="custName" label="客户姓名" />
            <el-table-column
              v-if="formData.createMode === '2'"
              prop="userName"
              label="柜员号"
            />
            <el-table-column prop="operate" label="操作">
              <template slot-scope="scope">
                <a
                  href="#"
                  style="color: blue"
                  @click.prevent="deleteClient(scope.$index, scope.row)"
                >移除</a>
              </template>
            </el-table-column>
          </el-table>
          <section class="form-operate" style="margin: 16px">
            <el-button
              type="plain"
              size="small"
              @click="cancelForm"
            >取消</el-button>
            <el-button
              v-if="!isEdit"
              type="plain"
              size="small"
              :loading="btnLoading"
              @click="getSubmitForm(true)"
            >暂存</el-button>
            <el-button
              type="primary"
              size="small"
              :loading="btnLoadingSub"
              @click="getSubmitForm(false)"
            >提交</el-button>
          </section>
        </section>
      </section>
    </section>
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :before-upload="beforeUpload"
        :file-list="fileList"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="downloadFlie"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="自建名单网格"
      :visible.sync="createdSuccess"
      style="text-align: center; width: 50%; margin-left: 25%"
    >
      <h3 v-html="operateTip" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancelForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  createVirGrid,
  uploadFileUpdate,
  uploadFile,
  uploadFileGuan,
  uploadFileGuanUpdate,
  getUserListByDeptIds,
  getGroupList,
  listByGroupId
} from '@/api/grid/region.js'
import { getDeptTree, getCommerList } from '@/api/grid/address/tree.js'
import {
  getVirtualgridDetail,
  updateVirtual,
  saveVirtualRedis,
  getVirtualRedis,
  checkVirtualName
} from '@/api/grid/list/gridlist.js'
import { isEqual, cloneDeep, isEmpty, debounce, throttle } from 'lodash'
import CustomRule from './components/custom-rule'
import { uid } from '@/utils'
import { businessBelongList } from '../utils'
import { mapGetters } from 'vuex'

const clientTypeOptions = [
  { key: 1, label: '个人', value: '1' },
  { key: 2, label: '商户', value: '2' },
  { key: 3, label: '企业', value: '3' }
]
export default {
  components: { CustomRule },
  props: [],
  data() {
    return {
      businessBelongList: businessBelongList,
      ruleArr: [
        // {
        //   label: '按管户归属',
        //   id: '1'
        // },
        {
          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'
        }
      ],
      ruleId: '8',
      operateTip: '自建名单网格创建成功！',
      isEditing: false,
      selectClient: [],
      createdSuccess: false,
      fileName: '',
      allSelected: false,
      formData: {
        gridType: undefined,
        associatedMap: undefined,
        clientNumber: undefined,
        gridDistributionMode: '1',
        gridResponsibilityType: '1',
        agencyUpperLimit: undefined,
        clientManager: [],
        durationOnce: undefined,
        clientType: { personal: false, merchant: false, company: false },
        currentPageName: '', // 自建名单网格AAA
        deptTree: [],
        createMode: '1', // 导入类型,
        opsDept: undefined
      },
      opsDeptDisable: false,
      responseResult: [],
      preTable: [],
      fileList: [],
      clientType: [],
      deptOptions: [],
      belongDeptOptions: [],
      deptTree: [],
      clientTypes: clientTypeOptions,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头
        // headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: '/grid/virtual/import'
      },
      rules: {
        currentPageName: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value.trim()) {
                callback(new Error('请输入网格名称'))
              } else if (value.trim().length < 2) {
                callback(new Error('网格名称最小为两位'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        gridType: [
          {
            required: true,
            message: '网格类型不能为空',
            trigger: 'change'
          }
        ],
        opsDept: [
          {
            required: true,
            message: '请选择业务部门归属',
            trigger: 'change'
          }
        ],
        clientType: [
          {
            required: true,
            message: '客户类型不能为空',
            trigger: 'change'
          }
        ],
        gridResponsibilityType: [
          {
            required: true,
            message: '网格责任类型不能为空',
            trigger: 'change'
          }
        ],
        gridDistributionMode: [
          {
            required: true,
            message: '网格分配方式不能为空',
            trigger: 'change'
          }
        ],
        deptTree: [
          {
            validator: (rule, value, callback) => {
              if (isEmpty(value)) {
                callback(new Error('机构不能为空'))
              } else {
                callback()
              }
            },
            required: true,
            trigger: 'change'
          }
        ],
        clientManager: [
          {
            required: true,
            message: '客户经理不能为空',
            trigger: 'change'
          }
        ],
        agencyUpperLimit: [
          {
            required: true,
            message: '认领机构上限',
            trigger: 'blur'
          }
        ],
        durationOnce: [
          {
            required: true,
            message: '单次认领时长',
            trigger: 'blur'
          }
        ]
      },
      gridTypeOptions: [
        { label: '菜场', value: '1' },
        { label: '政府单位', value: '2' },
        { label: '事业单位', value: '3' },
        { label: '社区', value: '4' },
        { label: '商圈', value: '5' },
        { label: '企业', value: '6' },
        { label: '市场园区', value: '7' },
        { label: '教育', value: '8' },
        { label: '其他', value: '9' }
      ],
      selectClientOptions: [],
      managerOptions: [],
      value: [],
      userChecked: [],
      btnLoading: false,
      btnLoadingSub: false,
      pageLoading: false,
      userSelectedArr: [],
      tableList: [],
      configRuleArr: {
        personal: {
          ruleTitle: '个人客户分配规则配置'
        },
        merchant: {
          ruleTitle: ''
        },
        company: {
          ruleTitle: ''
        }
      },
      ruleMap: {},
      orgCheckedOnlyOneArr: [],
      checkedArr: [],
      detailInfo: {},
      disabledclientType: [false, false, false, false],
      opsDept: undefined
    }
  },
  computed: {
    ...mapGetters(['roles']),
    edit() {
      return this.$route.query.edit
    },
    isEdit() {
      return Number(this.$route.query?.edit) === 2
    },
    routeGridId() {
      return this.$route.query.gridId
    },
    pageName() {
      return this.isEdit ? '自建名单网格修改' : '自建名单网格创建'
    },
    isStash() {
      return this.$route.query?.isStash
    },
    configRules() {
      const newArr = []
      this.ruleMap = {}
      if (this.formData.clientType.personal) {
        const resultObj = {
          ruleTitle: '个人客户分配规则配置',
          ruleName: 'personal',
          key: uid()
        }
        const newdata = this.detailInfo[
          this.isEdit ? 'gridVirtualRulesDTOList' : 'virtualGridRuleDTOList'
        ]?.filter((it) => it.relateType === '个人')
        resultObj.defaultListData = this.formatList(newdata)
        newArr.push(resultObj)
        this.ruleMap.personal = [
          {
            relateType: '个人',
            ruleKey: null,
            ruleOrder: 1
          }
        ]
      }

      if (this.formData.clientType.merchant) {
        const resultObj = {
          ruleTitle: '商户客户分配规则配置',
          ruleName: 'merchant',
          key: uid()
        }
        const newdata = this.detailInfo[
          this.isEdit ? 'gridVirtualRulesDTOList' : 'virtualGridRuleDTOList'
        ]?.filter((it) => it.relateType === '商户')
        resultObj.defaultListData = this.formatList(newdata)
        newArr.push(resultObj)
        this.ruleMap.merchant = [
          {
            relateType: '商户',
            ruleKey: null,
            ruleOrder: 1
          }
        ]
      }

      if (this.formData.clientType.company) {
        const resultObj = {
          ruleTitle: '企业客户分配规则配置',
          ruleName: 'company',
          key: uid()
        }
        const newdata = this.detailInfo[
          this.isEdit ? 'gridVirtualRulesDTOList' : 'virtualGridRuleDTOList'
        ]?.filter((it) => it.relateType === '企业')
        resultObj.defaultListData = this.formatList(newdata)
        newArr.push(resultObj)
        this.ruleMap.company = [
          {
            relateType: '企业',
            ruleKey: null,
            ruleOrder: 1
          }
        ]
      }
      return newArr
    },
    // 总行
    isHeadAdmin() {
      return this.roles.includes('headAdmin')
    },
    // 对公
    isPublic() {
      return this.roles.includes('headPublic')
    },
    // 对私
    isPrivate() {
      return this.roles.includes('headPrivate')
    },
    // 运管部
    isHeadOps() {
      return this.roles.includes('headOps')
    },
    // 支行
    isBranchAdmin() {
      return this.roles.includes('branchAdmin')
    },
    // 客户经理
    isCommonManager() {
      return this.roles.includes('commonManager')
    },
    // 网点主任
    isOutletAdmin() {
      return this.roles.includes('outletAdmin')
    }
  },
  watch: {
    edit: {
      handler(val) {
        if (Number(val) === 2) {
          this.gridId = this.routeGridId
          this.getDetailData()
        }
      },
      immediate: true
    },
    'formData.clientType': {
      handler(val) {
        const mapping = {
          company: '2',
          merchant: '1',
          personal: '0'
        }
        const result = Object.keys(val)
          .filter((key) => val[key])
          .map((key) => mapping[key])
        this.getList(result)
      },
      deep: true
    },
    preTable: {
      handler(val) {
        if (val.length === 0) return
        this.tableList = this.getNoRepeatArr(val)
      },
      deep: true
    },
    isStash: {
      handler(val) {
        if (Number(val) === 1) {
          this.getDetailData()
        }
      },
      immediate: true
    },
    roles: {
      handler(val) {
        if (val) {
          if (val.includes('headPrivate')) {
            // 零售部
            this.formData.opsDept = '0'
            this.opsDeptDisable = true
            this.businessbelongChange('0')
          } else if (val.includes('headPublic')) {
            // 公司部
            this.formData.opsDept = '1'
            this.opsDeptDisable = true
            this.businessbelongChange('1')
          } else if (val.includes('headOps')) {
            // 运管部
            this.formData.opsDept = '2'
            this.opsDeptDisable = true
            this.businessbelongChange('2')
          } else {
            // 总行管理员或者支行管理员
            this.formData.opsDept = undefined
            this.opsDeptDisable = false
          }
        }
      },
      immediate: true
    }
  },
  created() {
    this.getDeptTreeSelect()
  },
  mounted() {},
  methods: {
    onDeptTreeSelect(node, obj) {
      this.orgCheckedOnlyOneArr = [node]
      if (node.children && this.formData.gridResponsibilityType === '2') {
        const childrenArr = node.children.map((child) => child.id)
        this.checkedArr = [
          ...new Set([
            ...this.checkedArr,
            ...this.userChecked,
            node.id,
            ...childrenArr
          ])
        ]
      } else {
        if (this.formData.gridResponsibilityType === '2') {
          this.checkedArr = [
            ...new Set([...this.checkedArr, ...this.userChecked, node.id])
          ]
        } else {
          this.checkedArr = [node.id]
        }
      }
      this.fetchSelectOptions(this.checkedArr)
      this.$refs.elForm.clearValidate('deptTree')
    },
    handleInput(selected) {
      if (this.formData.gridResponsibilityType === '2') {
        return
      } else {
        if (selected.length > 1) {
          this.formData.deptTree = [selected[selected.length - 1]]
        } else {
          this.formData.deptTree = 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)
    },
    onOrgTreeFocus() {
      this.$refs.clientManager.blur()
    },
    onClientManagerFocus() {
      this.$refs.orgTree.blurInput()
    },
    async onInputBlur() {
      if (this.formData.currentPageName?.trim().length < 2) {
        return
      }
      const res = await checkVirtualName({
        gridName: this.formData.currentPageName
      })
      if (res.code === 200 && res.data) {
        this.formData.currentPageName = ''
        this.$message.error('网格名称不能重复，请重新填写')
      }
    },
    getRuleArr(obj) {
      console.log(obj)
      this.ruleMap[obj.ruleName] = obj.arr?.map((item) => ({
        ...item,
        ruleKey: item.layerId
          ? item.parentKey == '0'
            ? '90'
            : item.parentKey == '1'
              ? '91'
              : item.parentKey == '2'
                ? '92'
                : ''
          : item.ruleKey
      }))
    },
    getList(arr) {
      if (isEmpty(arr)) return (this.selectClientOptions = [])
      getGroupList({
        custTypes: arr?.join(',')
      }).then((res) => {
        this.selectClientOptions = res.rows
      })
    },
    isShowGridDistributionMode() {
      return Object.values(this.formData.clientType).includes(true)
    },
    async getDetailData() {
      try {
        this.pageLoading = true
        const { code, data } =
          this.isStash === '1'
            ? await getVirtualRedis()
            : await getVirtualgridDetail(this.routeGridId)
        if (code === 200) {
          this.detailInfo = data
          this.formData = {
            ...this.formData,
            currentPageName: data.gridName,
            gridType: data.gridType,
            gridResponsibilityType: data.gridDutyType,
            gridDistributionMode: data.gridAssignType,
            clientType: {
              personal: data.hasRetail,
              merchant: data.hasRetailBusiness,
              company: data.hasBusiness
            },
            createMode: data.createMode,
            opsDept: data.opsDept
          }
          if (this.isStash) {
            this.gridId = data.gridType
          }
          this.preTable = this.isStash
            ? this.formData.createMode === '1'
              ? data.custDTOList
              : data.virtualCustUserDTOList
            : []
          this.allSelected =
            data.hasRetail && data.hasRetailBusiness && data.hasBusiness
          this.estimatedNumberOfClirnt = data.custCount
          const userStr = this.isStash
            ? 'gridUserRelateDTOList'
            : 'virtualUserList'
          this.userChecked = [
            ...new Set(data?.[userStr]?.map((ot) => ot.relateDeptId) || [])
          ]
          this.formData.clientManager =
            data?.[userStr]
              ?.filter((og) => og.relateType === '1')
              ?.map((ot) => ot.userName) || []
          this.fetchSelectOptions(this.userChecked)
          this.userSelectedArr = isEmpty(this.formData.clientManager)
            ? []
            : cloneDeep(this.formData.clientManager)
          this.formData.deptTree = this.userChecked

          this.tableList = data.virtualCustUserList
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.pageLoading = false
      }
    },
    submitUpload() {
      this.$refs.upload.submit()
      this.upload.open = false
    },
    beforeUpload(file) {
      const data = new FormData()
      data.append('file', file)
      this.isEdit && data.append('gridId', this.gridId)
      const API =
        this.formData.createMode === '1'
          ? this.isEdit
            ? uploadFileUpdate
            : uploadFile
          : this.isEdit
            ? uploadFileGuanUpdate
            : uploadFileGuan
      API(data).then((res) => {
        let flag = false
        const custArr = []
        res.data?.forEach((item) => {
          if (this.formData.clientType.personal) {
            custArr.push('个人')
          }
          if (this.formData.clientType.merchant) {
            custArr.push('商户')
          }
          if (this.formData.clientType.company) {
            custArr.push('企业')
          }
          const index = custArr.findIndex(
            (custType) => custType === item.custType
          )
          if (index < 0) flag = true
          // if (item.custType === '个人') {
          //   this.formData.clientType.personal = true;
          // }
          // if (item.custType === '商户') {
          //   this.formData.clientType.merchant = true;
          // }
          // if (item.custType === '企业') {
          //   this.formData.clientType.company = true;
          // }
          // this.allSelected = this.formData.clientType.personal && this.formData.clientType.merchant && this.formData.clientType.company
        })
        if (flag) {
          this.$message.warning('只允许导入已选的客户类型')
          return
        }
        this.preTable = res.data
      })
      return false
    },
    fetchSelectOptions(deptIds) {
      if (isEmpty(deptIds)) {
        this.formData.clientManager = []
        return (this.managerOptions = [])
      }
      getUserListByDeptIds({ deptIds: deptIds }).then((response) => {
        if (
          this.isHeadAdmin ||
          this.isPublic ||
          this.isPrivate ||
          this.isHeadOps ||
          this.isBranchAdmin
        ) {
          this.managerOptions = response.data
          this.setclientManager()
        } else if (this.isCommonManager) {
          this.managerOptions = response.data.filter(
            (item) => item.userName == this.nowId
          )
        }
      })
    },
    setclientManager() {
      const userName = this.formData.clientManager
      const newuserName = userName.filter((id) => {
        const _ind = this.managerOptions.findIndex(
          (item) => item.userName === id
        )
        if (_ind > -1) {
          return id
        }
      })
      this.formData.clientManager = newuserName
    },
    getDeptTreeSelect() {
      if (
        this.isHeadAdmin ||
        this.isPublic ||
        this.isPrivate ||
        this.isHeadOps ||
        this.isBranchAdmin
      ) {
        getDeptTree().then((response) => {
          const newData = this.formatData(response.data)
          this.deptOptions = newData
          this.belongDeptOptions = response.data || []
        })
      } else if (this.isCommonManager) {
        getCommerList().then((res) => {
          this.nowId = res.data.userName
          const obj = {
            id: res.data.deptId,
            label: res.data.deptName
          }
          this.deptOptions.push(obj)
        })
      }
    },
    formatData(data) {
      return data.map((item) => {
        if (item.children && item.children.length > 0) {
          this.formatData(item.children)
        }
        if (item.level === 'head') {
          item.isDisabled = true
        } else {
          item.isDisabled = false
        }
        return item
      })
    },
    // 业务部门归属点击
    businessbelongChange(val) {
      if (val === '0') {
        // 零售部 禁用客户类型 企业 全部
        this.disabledclientType = [true, false, false, true]
        this.formData.clientType.company = false
        this.allSelected = false
      } else if (val === '1') {
        // 公司部 禁用客户类型 商户 个人 全部
        this.disabledclientType = [true, true, true, false]
        this.formData.clientType.personal = false
        this.formData.clientType.merchant = false
        this.allSelected = false
      } else if (val === '2') {
        // 运管部 不禁用客户类型
        this.disabledclientType = [false, false, false, false]
      }
      this.opsDept = val
    },
    handleCheckAllChange(val) {
      this.formData.clientType.personal = val
      this.formData.clientType.merchant = val
      this.formData.clientType.company = val
    },
    hangleCheckedTypeChange(value) {
      this.allSelected =
        this.formData.clientType.personal &&
        this.formData.clientType.merchant &&
        this.formData.clientType.company
    },
    editName() {
      this.isEditing = true
      this.$nextTick(() => {
        this.$refs.nameInput.focus()
      })
    },
    saveName() {
      this.isEditing = false
    },
    findObjById(data, ids) {
      const result = []
      function search(node) {
        if (ids.includes(node.userName)) {
          result.push(node)
        }
        if (node.children) {
          node.children?.forEach((child) => search(child))
        }
      }

      data?.forEach((ot) => search(ot))
      return result
    },
    getDTOList() {
      const resultArr = this.managerOptions?.filter((option) =>
        this.formData?.clientManager?.includes(option.userName)
      )
      resultArr?.forEach((item) => {
        item.optFlag = '0'
        item.relateType = '1'
        item.relateDeptId = item.deptId
        item.relateDeptName = item.deptName
        item.relateDeptType = item.deptType
        item.userId = item.userId
        item.userName = item.userName
      })
      return resultArr
    },
    getUserEditData(arr) {
      const deleteUserRelate = this.findUniqueEle(
        this.userSelectedArr,
        arr?.map((ob) => ob.userName)
      )
      const newArr = arr
        ?.map((ot) => {
          if (!this.userSelectedArr.includes(ot.userName)) {
            return ot
          }
          return null
        })
        ?.filter((on) => on)
      let editGridUserRelateDTOList = []
      if (!isEmpty(deleteUserRelate)) {
        const resultArr = this.findObjById(
          this.managerOptions,
          deleteUserRelate
        )

        editGridUserRelateDTOList = [
          ...newArr,
          ...resultArr?.map((oi) => ({
            relateDeptId: oi.deptId,
            relateDeptName: oi.deptName,
            relateDeptType: oi.deptType,
            optFlag: '1',
            relateType: '1',
            userId: oi.userId,
            userName: oi.userName
          }))
        ]
      } else {
        editGridUserRelateDTOList = [...newArr]
      }
      return editGridUserRelateDTOList
    },
    hasEmptyRuleName() {
      return Object.values(this.ruleMap)?.some((arr) =>
        arr.some((item) => !item.ruleKey)
      )
    },
    getSubmitForm: debounce(function(isStash = false) {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          if (this.formData.currentPageName?.trim()?.length < 2) {
            return this.$message.error(
              '网格名称最少两个字符，请修改后重新提交'
            )
          }
          const gridUserRelateDTOList = this.getDTOList()

          if (
            this.formData.gridDistributionMode === '1' &&
            this.formData.gridResponsibilityType === '2' &&
            gridUserRelateDTOList.length <= 1
          ) {
            this.$message({
              type: 'warning',
              message: '竞争网格时，客户经理必须选择2个及以上'
            })
            return []
          }
          this.tableList.forEach((item) => (item.optFlag = '0'))
          if (this.tableList.length > 3000) {
            return this.$message.error('导入的列表不能超过3000条')
          }
          let data
          if (this.formData.createMode === '1') {
            data = {
              custDTOList: this.tableList,
              gridAssignType: this.formData.gridDistributionMode,
              gridDutyType: this.formData.gridResponsibilityType,
              gridName: this.formData.currentPageName,
              gridType: this.formData.gridType,
              gridUserRelateDTOList: gridUserRelateDTOList,
              hasBusiness: this.formData.clientType.company,
              hasRetail: this.formData.clientType.personal,
              hasRetailBusiness: this.formData.clientType.merchant,
              createMode: this.formData.createMode,
              opsDept: this.formData.opsDept
            }
            if (
              this.hasEmptyRuleName() &&
              this.formData.gridDistributionMode === '2'
            ) {
              return this.$message.error(
                '自定义配置不能存在空值，请修改后重新提交'
              )
            }
            if (this.formData.gridDistributionMode === '2') {
              const list = Object.values(this.ruleMap)?.reduce(
                (acc, val) => acc.concat(val),
                []
              )
              const hasUserNameList = list.filter((v) => v.userName)
              let flag = false
              hasUserNameList.map((item) => {
                if (item.userName.length === 0) {
                  flag = true
                }
              })
              if (flag) {
                return this.$message.error(
                  '自定义配置客户经理不能为空，请修改后重新提交'
                )
              }
              const noUserNameList = list.filter((v) => !v.userName)
              hasUserNameList.map((v) => {
                const { userDeptList, userName = [], ...other } = v
                userName.map((id) => {
                  noUserNameList.push({
                    ...other,
                    userName: id,
                    userDeptList: userDeptList.join(',')
                  })
                })
              })
              data.virtualGridRuleDTOList = noUserNameList
            }
            if (this.isEdit) {
              data.gridId = this.gridId
              data.gridUserRelateDTOList = this.getUserEditData(
                gridUserRelateDTOList
              )
            }
          } else {
            data = {
              virtualCustUserDTOList: this.tableList,
              gridName: this.formData.currentPageName,
              gridType: this.formData.gridType,
              hasBusiness: this.formData.clientType.company,
              hasRetail: this.formData.clientType.personal,
              hasRetailBusiness: this.formData.clientType.merchant,
              createMode: this.formData.createMode,
              opsDept: this.formData.opsDept
            }
            if (this.isEdit) {
              data.gridId = this.gridId
            }
          }
          let apiUrl
          if (isStash) {
            this.btnLoading = true
            apiUrl = saveVirtualRedis
          } else {
            this.btnLoadingSub = true
            apiUrl = this.isEdit ? updateVirtual : createVirGrid
          }
          apiUrl(data)
            .then((response) => {
              if (response.code === 200) {
                if (isStash) {
                  return this.$message.success(response.data)
                }
                this.operateName = this.isEdit ? '修改成功' : '创建成功'
                this.$alert(
                  `${this.formData.currentPageName} ${this.operateName}！`,
                  '自建名单网格',
                  {
                    confirmButtonText: '确定',
                    dangerouslyUseHTMLString: true,
                    callback: (action) => {
                      this.cancelForm()
                    }
                  }
                )
              } else {
                this.$message.error(
                  response.msg || this.isEdit ? '修改失败' : '新建失败'
                )
              }
            })
            .catch((err) => console.error(err))
            .finally(() => {
              setTimeout(() => {
                if (isStash) this.btnLoading = false
                else this.btnLoadingSub = false
              }, 100)
            })
        } else {
          this.$message.error('请填必填项')
        }
      })
    }, 200),
    findUniqueEle(arr1, arr2) {
      const set1 = new Set(arr1)
      const set2 = new Set(arr2)

      const diff = new Set([...set1].filter((x) => !set2.has(x)))
      return Array.from(diff)
    },
    cancelForm() {
      const { query } = this.$route
      if (query.backUrl) {
        this.$router.replace({
          path: query.backUrl,
          query
        })
      } else {
        this.$router.go(-1)
      }
    },
    downloadFlie() {
      const API =
        this.formData.createMode === '1'
          ? 'grid/virtual/export'
          : '/grid/virtual/export/relate'
      const TEXT = this.formData.createMode === '1' ? '客户模板' : '管户模板'
      this.download(API, {}, `${TEXT}_${new Date().getTime()}.xlsx`)
    },
    // 导入类型选择
    createModeChange(val) {
      this.tableList = []
    },
    handleImport() {
      const custArr = []
      if (this.formData.clientType.personal) {
        custArr.push('个人')
      }
      if (this.formData.clientType.merchant) {
        custArr.push('商户')
      }
      if (this.formData.clientType.company) {
        custArr.push('企业')
      }
      if (custArr.length === 0) {
        this.$message.warning('请先选择客户类型')
        return
      }
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          '</div>',
        '导入结果',
        {
          dangerouslyUseHTMLString: true
        }
      )
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    handleFileUpload(event) {
      const file = event.target.flies[0]
      if (file) {
        this.fileName = file.name
        this.uploadFile(file)
      }
    },
    uploadFile(file) {
      const formData = new FormData()
      formData.append('file', file)
    },
    isObjectEqual(obj1, obj2) {
      const keys1 = Object.keys(obj1)
      const keys2 = Object.keys(obj2)
      if (keys1.length !== keys2.length) {
        return false
      }
      for (const key of keys1) {
        if (obj1[key] !== obj2[key]) {
          return false
        }
      }
      return true
    },
    onGridDistributionModeChange(val) {
      if (val === '2') {
        this.configRuleArr = []
      }
    },
    onDutyTypeChange(val) {
      this.formData.deptTree = []
      this.formData.clientManager = []
    },
    getNoRepeatArr(arr) {
      if (this.formData.createMode === '1') {
        // 按照客户号去重
        // return Array.from(new Set(arr?.map((item) => item.custIdn))).map((custIdn) => arr?.find((item) => item.custIdn === custIdn))
        return this.uniqueByFields(arr, 'one', 'custIdn')
      } else {
        // 按照客户号和柜员号去重
        return this.uniqueByFields(arr, 'two', 'custIdn', 'userName')
      }
    },
    uniqueByFields(arr, type, field1, field2) {
      const uniqueArray = this.tableList
      if (type === 'one') {
        arr.map((item) => {
          const index = uniqueArray.findIndex(
            (v) => v[field1] === item[field1]
          )
          if (index === -1) {
            uniqueArray.push(item)
          }
        })
      } else if (type === 'two') {
        arr.map((item) => {
          const index = uniqueArray.findIndex(
            (v) => v[field1] === item[field1] && v[field2] === item[field2]
          )
          if (index === -1) {
            uniqueArray.push(item)
          }
        })
      }
      return uniqueArray
    },
    uploadClient() {
      listByGroupId({ groupId: this.formData.selectClient }).then((res) => {
        const isContained = res.rows.every((item1) =>
          this.responseResult.some((item2) => this.isObjectEqual(item1, item2))
        )
        if (isContained) {
          this.$message.error('请勿重复导入')
        } else {
          res.rows?.forEach((item) => this.responseResult.push(item))
          const newArr = this.responseResult.map((item) => {
            if (item.custType == '0') {
              return {
                custIsn: item.custIsn,
                custIdType: item.idType,
                custIdn: item.custIdc,
                custId: item.custId,
                custName: item.custName,
                custType: '个人'
              }
            } else {
              return {
                custIsn: item.custIsn,
                custIdType: item.socialCreditCodeType,
                custIdn: item.socialCreditCode,
                custId: item.custId,
                custName: item.custName,
                custType: item.custType == '1' ? '商户' : '企业'
              }
            }
          })

          this.preTable = [...newArr, ...this.preTable]
          // const a = this.selectClientOptions.filter((item) => item.groupId === this.formData.selectClient)
          // console.log(a,'custTypecustType')
          // if (a[0].custType === '0') {
          //   a[0].custType = '个人'
          // } else if (a[0].custType === '1') {
          //   a[0].custType = '商户'
          // } else {
          //   a[0].custType = '企业'
          // }
          // this.preTable.forEach((item) => (item.custType = a[0].custType))
        }
      })
    },
    deleteClient(index, row) {
      this.tableList.splice(index, 1)
      this.responseResult.splice(index, 1)
      this.preTable.splice(index, 1)
      console.log(this.preTable, 'this.preTable')
    },
    formatList(list = []) {
      const listRule38 = []
      list.map((v) => {
        if (v.ruleKey && this.ruleId.includes(v.ruleKey)) {
          const index = listRule38.findIndex((a) => a.ruleKey === v.ruleKey)
          if (index > -1) {
            listRule38[index].userName.push(v.userName)
          } else {
            listRule38.push({
              ...v,
              userName: [v.userName],
              userDeptList: v.userDeptList?.split(',')
            })
          }
        }
      })
      const listRule = list.filter((v) => !this.ruleId.includes(v.ruleKey))
      return listRule.concat(listRule38)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "./../created/component/create-style.scss";

.preview-table {
  width: 100%;
  margin-top: 16px;
}

::v-deep .vue-treeselect__checkbox.vue-treeselect__checkbox--disabled {
  display: none;
}

.preview-cnt {
  margin-top: 40px;
}

.chose-cnt {
  ::v-deep .el-form-item__content {
    display: flex;
    justify-content: space-between;

    .el-button {
      width: 88px;
      margin-left: 24px;
    }

    .el-select {
      flex: 1;
    }
  }
}

.common-create-main {
  .el-form-vir {
    min-width: 740px;
  }
}

.question_icon {
  color: #b9b9b9;
}
</style>
