<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-row>
        <el-col :span="7">
          <el-form
            ref="elForm"
            v-loading="pageLoading"
            :model="formData"
            :rules="rules"
            size="medium"
            label-width="140px"
            label-position="top"
            class="elForm"
          >
            <el-form-item label="自绘地图网格名称" prop="currentPageName">
              <el-input
                v-model="formData.currentPageName"
                placeholder="请输入"
                minlength="2"
                clearable
                maxlength="20"
                size="small"
              />
            </el-form-item>
            <el-form-item label="业务部门归属" prop="opsDept">
              <el-radio-group
                v-model="formData.opsDept"
                size="medium"
                :disabled="opsDeptDisable || Number(edit) === 2"
                @change="handleSelectDept"
              >
                <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="gridType">
              <el-select
                v-model="formData.gridType"
                :disabled="Number(edit) === 2"
                placeholder="请选择网格类型"
                clearable
                style="width: 100%"
                @change="handleSelect"
              >
                <el-option
                  v-for="(item, index) in gridTypeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="预计客户数"
              prop="clientNumber"
            >{{ estimatedNumberOfClirnt }}
            </el-form-item>
            <el-form-item 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>
            <el-form-item label="归属机构" class="tree-select" prop="deptTree">
              <treeselect
                ref="orgTree"
                v-model="formData.deptTree"
                :multiple="true"
                :options="deptOptions"
                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="tree-select"
            >
              <el-select
                ref="clientManager"
                v-model="formData.clientManager"
                multiple
                :collapse-tags="false"
                :multiple-limit="
                  formData.gridResponsibilityType === '2' ? 0 : 1
                "
                size="small"
                style="width: 100%"
                filterable
                placeholder="请选择"
                @focus="onClientManagerFocus"
                @change="$forceUpdate()"
              >
                <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>
          </el-form>
          <section class="form-operate">
            <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="btnLoading"
              @click="getSubmitForm(false)"
            >提交</el-button>
            <!-- <el-button type="danger" size="small" @click="onDelStash">清除暂存</el-button> -->
          </section>
        </el-col>
        <el-col :span="17">
          <div style="marginleft: 10px">
            <b-map-create-first-grid
              v-loading="menuLoading"
              :map-menu-data="mapMenuData"
              :shape-ids="shapeIds"
              :total="total"
              :page-num="pageNum"
              @set-checkedkey="setCheckedkey"
              @handleCurrentChange="handleCurrentChange"
            />
          </div>
        </el-col>
      </el-row>
    </section>
  </div>
</template>
<script>
import { getDeptTree } from '@/api/grid/address/tree.js'
import { getUserListByDeptIds } from '@/api/grid/region.js'
import {
  lookAreasMap,
  getAreaShapeAvailableApi
} from '@/api/grid/draw-area.js'
import {
  getDrawDes,
  getDrawTopRedis,
  featureGridUpdate,
  featureGridStash,
  featureGridAdd,
  shapeCustCount,
  drawSave
} from '@/api/grid/list/gridlist.js'
import { isEqual, debounce, isEmpty } from 'lodash'
import BMapCreateFirstGrid from '@/map/BMapCreateFirstGrid.vue'
import { businessBelongList } from '../utils'
import { mapGetters } from 'vuex'

export default {
  components: {
    BMapCreateFirstGrid
  },
  props: [],
  data() {
    return {
      businessBelongList: businessBelongList,
      currentPageName: '',
      operateName: '创建成功',
      filterText: '',
      deptOptions: [],
      managerOptions: [],
      checkedArr: [],
      userChecked: [],
      estimatedNumberOfClirnt: 0, // 预计客户数
      formData: {
        clientManager: undefined,
        gridType: undefined,
        opsDept: undefined,
        associatedMap: undefined,
        clientNumber: undefined,
        gridResponsibilityType: '1',
        menuCheckStrictly: true,
        currentPageName: '',
        deptTree: []
      },
      rules: {
        currentPageName: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value.trim()) {
                callback(new Error('请输入网格名称'))
              } else if (value.trim().length < 2) {
                callback(new Error('网格名称最小为两位'))
              } else if (value.trim().length > 20) {
                callback(new Error('网格名称最大为20位'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        gridType: [
          {
            required: true,
            message: '请选择网格类型',
            trigger: 'change'
          }
        ],
        opsDept: [
          {
            required: true,
            message: '请选择业务部门归属',
            trigger: 'change'
          }
        ],
        gridResponsibilityType: [
          {
            required: true,
            message: '网格责任类型不能为空',
            trigger: 'change'
          }
        ],
        deptTree: [
          {
            validator: (rule, value, callback) => {
              const checkedKeys = this.formData.deptTree
              if (checkedKeys.length === 0) {
                callback(new Error('机构不能为空'))
              } else {
                callback()
              }
            },
            required: true,
            trigger: 'change'
          }
        ],
        clientManager: [
          {
            validator: (rule, value, callback) => {
              const checkedKeys = this.formData.clientManager
              const optionsLength = this.managerOptions.length
              if (checkedKeys.length === 0 && optionsLength > 0) {
                callback(new Error('客户经理不能为空'))
              } else {
                callback()
              }
            },
            required: true,
            trigger: 'change'
          }
        ]
      },
      selectedOptions: [{ selected: null }],
      defaultGridProps: {
        children: 'children',
        label: 'label'
      },
      defaultDeptProps: {
        children: 'children',
        label: 'label',
        disabled: (data) => !['head', 'branch', 'outlet'].includes(data.level)
      },
      btnLoading: false,
      pageLoading: false,
      treeDataList: [],
      orgCheckedOnlyOneArr: [],
      mapMenuData: [],
      menuLoading: false,
      shapeCheckedKeys: [],
      shapeIds: [],
      addShapeIds: [],
      deleteShapeIds: [],
      opsDeptDisable: false,
      pageNum: 1,
      total: 0,
      pageSize: 10,
      params: {}
    }
  },
  computed: {
    ...mapGetters(['roles']),
    edit() {
      return this.$route.query?.edit
    },
    gridId() {
      return this.$route.query?.gridId
    },
    isStash() {
      return this.$route.query?.isStash
    },
    pageName() {
      return Number(this.edit) === 2
        ? '自绘地图网格修改'
        : '自绘地图网格创建'
    },
    isEdit() {
      return Number(this.$route.query?.edit) === 2
    },
    gridTypeOptions() {
      const { layerDataSpe } = this.$store.state.featuredAreas
      const newData = layerDataSpe.map((item) => {
        return {
          label: item.label,
          value: item.id,
          disabled: item.disabled
        }
      })
      return [...newData]
    }
  },
  watch: {
    edit: {
      handler(val) {
        if (Number(val) === 2) {
          this.getDetailData()
        }
      },
      immediate: true
    },
    isStash: {
      handler(val) {
        if (Number(val) === 1) {
          this.getDetailData()
        }
      },
      immediate: true
    },
    filterText(val) {
      this.$refs.orgTree.filter(val)
    },
    roles: {
      handler(val) {
        if (val) {
          if (val.includes('headPrivate')) {
            // 零售部
            this.formData.opsDept = '0'
            this.opsDeptDisable = true
          } else if (val.includes('headPublic')) {
            // 公司部
            this.formData.opsDept = '1'
            this.opsDeptDisable = true
          } else if (val.includes('headOps')) {
            // 运管部
            this.formData.opsDept = '2'
            this.opsDeptDisable = true
          } else {
            // 总行管理员或者支行管理员
            this.formData.opsDept = undefined
            this.opsDeptDisable = false
          }
        }
      },
      immediate: true
    }
  },
  created() {
    this.getGridTypeOptions(this.formData.opsDept)
    this.getDeptTreeSelect()
  },
  methods: {
    handleCurrentChange(num) {
      this.pageNum = num
      const { layerId, opsDept, canChooseArr } = this.params
      this.getAreaShapeAvailable(layerId, opsDept, canChooseArr)
    },
    async getDetailData() {
      try {
        this.pageLoading = true
        const { code, data } =
          this.isStash === '1'
            ? await getDrawTopRedis()
            : await getDrawDes(this.gridId)
        if (code === 200) {
          this.formData = {
            gridType: data.layerId,
            gridResponsibilityType: data.gridDutyType,
            currentPageName: data.gridName,
            opsDept: data.opsDept
          }
          this.getAreaShapeAvailable(data.layerId, data.opsDept, data.shapeIds)
          this.formData.deptTree = data.userRelateDTOList.map(
            (v) => v.relateDeptId
          )
          this.fetchSelectOptions(
            this.formData.deptTree,
            data.userRelateDTOList
          )
          this.shapeIds = data.shapeIds
          this.getCountData(this.shapeIds.join(','))
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.pageLoading = false
      }
    },
    onDutyTypeChange(val) {
      this.formData.deptTree = []
      this.formData.clientManager = []
      this.$forceUpdate()
    },
    // 勾选归属机构
    onDeptTreeSelect(node) {
      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)
    },
    fetchSelectOptions(deptIds, data = []) {
      if (isEmpty(deptIds)) {
        this.formData.clientManager = []
        return (this.managerOptions = [])
      }
      getUserListByDeptIds({ deptIds: deptIds }).then((response) => {
        this.managerOptions = response.data
        if (data.length > 0) {
          this.formData.clientManager = data.map((v) => v.userName)
          return
        }
        this.setclientManager()
      })
    },
    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
    },
    onOrgTreeFocus() {
      this.$refs.clientManager.blur()
    },
    onClientManagerFocus() {
      this.$refs.orgTree.blurInput()
    },
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
      })
    },
    cancelForm() {
      // this.$router.go(-1);
      const { query } = this.$route
      if (query.backUrl) {
        this.$router.replace({
          path: query.backUrl,
          query
        })
      } else {
        this.$router.go(-1)
      }
    },
    getCountData(shapeIds) {
      shapeCustCount({ shapeIds }).then((res) => {
        const total = Object.values(res.data).reduce(
          (pre, cur) => pre + cur,
          0
        )
        this.estimatedNumberOfClirnt = total
      })
    },
    regionCodeFilter(regionArr) {
      const sorted = regionArr?.sort((a, b) => a.length - b.length)
      const keyLen = sorted?.[0]?.length
      if (keyLen === 12) {
        return regionArr
      }
      const keys = regionArr?.filter((code) => code.length === keyLen)
      keys?.forEach((key) => {
        regionArr = regionArr?.filter((code) => !code?.startsWith(key))
      })
      return [...keys, ...regionArr]
    },
    getDeptTreeSelect() {
      getDeptTree().then((response) => {
        const newData = this.formatData(response.data)
        this.deptOptions = newData
      })
    },
    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
      })
    },
    handleSelectDept() {
      this.formData.gridType = undefined
      this.getGridTypeOptions(this.formData.opsDept)
    },
    handleSelect(value) {
      const { opsDept, gridType } = this.formData
      this.pageNum = 1
      if (opsDept && gridType) {
        this.getAreaShapeAvailable(gridType, opsDept)
      }
    },
    async getAreaShapeAvailable(layerId, opsDept, canChooseArr = []) {
      this.menuLoading = true
      this.params = {
        layerId,
        opsDept,
        canChooseArr
      }
      const res = await getAreaShapeAvailableApi({
        layerId,
        opsDept,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
      const { code, rows } = res
      if (code === 200) {
        const newdata = rows.map((item) => {
          const canChoose = canChooseArr.includes(item.shapeId)
          return {
            ...item,
            label: item.shapeName,
            id: item.shapeId,
            disabled: item.relateFlag && !canChoose
          }
        })
        this.mapMenuData = newdata
        this.total = res.total
      }
      this.menuLoading = false
    },
    getSubmitForm: debounce(function(isStash = false) {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          if (this.shapeCheckedKeys.length === 0) {
            this.$message({
              type: 'warning',
              message: '请选择地图上的特色区域'
            })
            return
          }
          const userRelateDTOList = []
          const { clientManager = [], gridResponsibilityType } = this.formData
          if (gridResponsibilityType === '2' && clientManager.length <= 1) {
            this.$message({
              type: 'warning',
              message: '竞争网格时，客户经理必须选择2个及以上'
            })
            return
          }
          clientManager.map((userName) => {
            const item = this.managerOptions.find(
              (v) => v.userName === userName
            )
            if (item) {
              userRelateDTOList.push({
                relateDeptId: item.deptId,
                relateDeptName: item.deptName,
                relateDeptType: item.deptType,
                userName: item.userName,
                nickName: item.nickName
              })
            }
          })
          const data = {
            gridDutyType: this.formData.gridResponsibilityType,
            gridName: this.formData.currentPageName,
            layerId: this.formData.gridType,
            shapeIds: this.shapeCheckedKeys,
            userRelateDTOList,
            opsDept: this.formData.opsDept
          }
          if (Number(this.edit) === 2) {
            // 编辑页
            data.gridId = this.gridId
            data.addShapeIds = this.addShapeIds
            data.deleteShapeIds = this.deleteShapeIds
            delete data.shapeIds
          }
          this.btnLoading = true
          let apiUrl
          if (isStash) {
            apiUrl = drawSave
          } else {
            apiUrl =
              Number(this.edit) === 2 ? featureGridUpdate : featureGridAdd
          }
          apiUrl(data)
            .then((response) => {
              if (response.code === 200) {
                if (isStash) {
                  // 暂存
                  return this.$message.success(response.data)
                }
                this.operateName =
                  Number(this.edit) === 2 ? '修改成功' : '创建成功'
                this.$alert(
                  `${this.formData.currentPageName} ${this.operateName}！`,
                  '自绘地图网格',
                  {
                    confirmButtonText: '确定',
                    callback: (action) => {
                      this.cancelForm()
                    }
                  }
                )
              }
            })
            .catch((err) => console.error(err))
            .finally(() => {
              setTimeout(() => {
                this.btnLoading = false
              }, 100)
            })
        } else {
          return false
        }
      })
    }, 200),
    // 获取网格类型
    getGridTypeOptions(opsDept) {
      if (opsDept) {
        this.$store.dispatch('queryMenuSpe', { opsDept })
      }
    },
    setCheckedkey(data) {
      this.shapeCheckedKeys = [...data]
      if (data.length === 0) {
        this.estimatedNumberOfClirnt = 0
      } else {
        this.getCountData(data.join(','))
      }
      if (this.shapeIds.length > 0) {
        this.addShapeIds = data.filter(
          (shapeId) => !this.shapeIds.includes(shapeId)
        )
        this.deleteShapeIds = this.shapeIds.filter(
          (shapeId) => !data.includes(shapeId)
        )
      } else {
        this.addShapeIds = data
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "./../created/component/create-style.scss";

::v-deep .el-checkbox.is-disabled {
  display: none;
}
.common-wrap-cnt {
  ::v-deep .el-select__input {
    height: 32px;
  }

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

  ::v-deep .el-form-item--medium .el-form-item__content {
    line-height: 32px;
  }
}

.common-create-main .elForm {
  width: 100%;
}

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