<template>
  <div class="common-wrap-cnt">
    <v-tour name="importTour" :steps="steps" :options="tourOptions" />
    <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
            id="commonMain"
            ref="elForm"
            v-loading="pageLoading"
            class="elForm"
            :model="formData"
            :rules="rules"
            size="medium"
            label-width="30%"
            label-position="top"
          >
            <el-form-item label="总行行政网格名称" prop="currentPageName">
              <el-input
                v-model="formData.currentPageName"
                placeholder="请输入"
                minlength="2"
                clearable
                maxlength="20"
                size="small"
                @blur="onInputBlur"
              />
            </el-form-item>
            <el-form-item label="网格类型" prop="gridType">
              <el-select
                v-model="formData.gridType"
                :disabled="Number(edit) === 2"
                placeholder="请选择网格类型"
                clearable
                style="width: 100%"
                @click="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="opsDept">
              <el-radio-group
                v-model="formData.opsDept"
                size="medium"
                :disabled="opsDeptDisable || Number(edit) === 2"
              >
                <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
              v-if="formData.gridType === '0'"
              label="选择行政区划"
              class="tree-select"
              prop="addressTree"
            >
              <el-tree
                ref="addressTree"
                class="tree-border"
                :data="menuOptions"
                show-checkbox
                node-key="value"
                empty-text="加载中，请稍候"
                :default-checked-keys="areaChecked"
                :default-expanded-keys="areaChecked"
                :props="defaultGridProps"
                @check="onChecked"
              />
            </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"
              >
                <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
                v-if="formData.gridResponsibilityType === '1'"
                ref="testingTree"
                v-model="formData.deptTree"
                :options="deptOptions"
                placeholder="请选择"
                no-options-text="暂无数据"
                no-results-text="暂无数据"
                @select="onDeptTreeSelect"
              />
              <div
                v-if="formData.gridResponsibilityType === '2'"
                class="tree-select-border"
              >
                <el-input
                  v-model="filterText"
                  size="mini"
                  clearable
                  placeholder="请输入关键字进行过滤"
                />
                <el-tree
                  ref="deptTree"
                  :data="deptOptions"
                  :filter-node-method="filterNode"
                  show-checkbox
                  :check-strictly="true"
                  node-key="id"
                  empty-text="暂无数据"
                  :default-checked-keys="orgChecked"
                  :default-expanded-keys="orgChecked"
                  :props="defaultDeptProps"
                />
              </div>
            </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
            v-if="formData.gridType === '0'"
            v-loading="mapLoading"
            style="marginleft: 10px"
          >
            <iframe
              name="bdmap"
              :src="getIframeSrc()"
              style="width: 100%; height: 650px"
            />
          </div>
        </el-col>
      </el-row>
    </section>
  </div>
</template>
<script>
import {
  getAddressTree as treeselect,
  getTopDeptTree,
  getRegionCodeByDept
} from '@/api/grid/address/tree.js'
import { createTopGrid, getCustCount } from '@/api/grid/region.js'
import { getRegionCoordQuery } from '@/api/grid/draw-area.js'
import {
  getRegionDes,
  regionUpdate,
  saveTopRedis,
  getTopRedis,
  checkName
} from '@/api/grid/list/gridlist.js'
import { isEqual, debounce, isEmpty } from 'lodash'
import { businessBelongList } from '../utils'
import { mapGetters } from 'vuex'

export default {
  components: {},
  props: [],
  data() {
    return {
      steps: [
        {
          target: '#commonMain',
          content:
            '<div style="font-size:20px;line-height:25px">总行行政网格创建</div><br><span>填写信息,星号为必填,选择行政区划(可多选)、网格责任类型,归属机构,点击提交即可在网格查询查看</span>',
          overlay: true,
          params: {
            placement: 'right',
            highlight: true,
            mask: true
          }
        },
        {
          target: '#commonMain',
          content:
            '<div style="font-size:20px;line-height:25px">总行行政网格创建</div><br><span>填写信息,星号为必填,选择行政区划(可多选)、网格责任类型,归属机构,点击提交即可在网格查询查看</span>',
          overlay: true,
          params: {
            placement: 'right',
            highlight: true,
            mask: true
          }
        },
        {
          target: '#commonMain',
          content: '',
          overlay: true,
          before: () => {
            return this.$router.push({ path: '/grid/list' }).then(() => {
              return new Promise((resolve) => {
                const checkElement = () => {
                  if (document.querySelector('#uoloadWapper')) {
                    resolve()
                  } else {
                    setTimeout(checkElement, 100)
                  }
                }
                checkElement()
              })
            })
          }
        }
      ],
      tourOptions: {
        highlight: true,
        labels: {
          buttonSkip: '跳过',
          buttonPrevious: '上一步',
          buttonNext: '下一步',
          buttonStop: '完成'
        },
        enabledButtons: {
          buttonSkip: true,
          buttonPrevious: true,
          buttonNext: true,
          buttonStop: true
        },
        useKeyboardNavigation: true,
        startTime: 0,
        stopOnTargetNotFound: true,
        debug: false
      },
      businessBelongList: businessBelongList,
      mapLoading: false,
      currentPageName: '',
      operateName: '创建成功',
      isEditing: false,
      menuOptions: [],
      filterText: '',
      areaChecked: [],
      orgChecked: [],
      deptOptions: [],
      estimatedNumberOfClirnt: 0,
      formData: {
        gridType: '0',
        associatedMap: undefined,
        clientNumber: undefined,
        gridResponsibilityType: '1',
        homeOrganization: undefined,
        agencyUpperLimit: undefined,
        durationOnce: undefined,
        menuCheckStrictly: true,
        currentPageName: '',
        deptTree: undefined,
        opsDept: undefined
      },
      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'
          }
        ],
        addressTree: [
          {
            validator: this.validateTree,
            required: true,
            trigger: 'change'
          }
        ],
        gridResponsibilityType: [
          {
            required: true,
            message: '网格责任类型不能为空',
            trigger: 'change'
          }
        ],
        deptTree: [
          {
            validator: (rule, value, callback) => {
              if (this.formData.gridResponsibilityType === '1') {
                if (!value) {
                  callback(new Error('机构不能为空'))
                } else {
                  callback()
                }
              } else {
                const checkedKeys = this.$refs.deptTree.getCheckedKeys()

                if (checkedKeys.length === 0) {
                  callback(new Error('机构不能为空'))
                } else {
                  callback()
                }
              }
            },
            required: true,
            trigger: 'change'
          }
        ],
        homeOrganization: [
          {
            required: true,
            message: '请输入归属机构',
            trigger: 'blur'
          }
        ],
        agencyUpperLimit: [
          {
            required: true,
            message: '认领机构上限',
            trigger: 'blur'
          }
        ],
        durationOnce: [
          {
            required: true,
            message: '单次认领时长',
            trigger: 'blur'
          }
        ]
      },
      gridTypeOptions: [
        { label: '行政区划', value: '0' },
        { label: '菜场', value: '1', disabled: true },
        { label: '政府单位', value: '2', disabled: true },
        { label: '事业单位', value: '3', disabled: true },
        { label: '社区', value: '4', disabled: true },
        { label: '商圈', value: '5', disabled: true },
        { label: '企业', value: '6', disabled: true },
        { label: '市场园区', value: '7', disabled: true },
        { label: '教育', value: '8', disabled: true },
        { label: '其他', value: '9', disabled: true }
      ],
      homeOptions: [
        {
          label: '括苍支行',
          value: 'kuocang'
        },
        {
          label: 'xx支行',
          value: 'xx'
        }
      ],
      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: [],
      opsDeptDisable: false
    }
  },
  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
    },
    isTour() {
      return sessionStorage.getItem('isTour')
    }
  },
  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.deptTree.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() {
    if (!this.edit) {
      this.getMenuTreeselect()
    }
    this.getDeptTreeSelect()
    window['mapProps'] = (params) => {
      if (params === 'map loading') {
        this.mapLoading = true
      } else if (params === 'map loading finish') {
        this.mapLoading = false
      }
    }
  },
  mounted() {
    if (this.isTour == '3') {
      setTimeout(() => {
        this.startTour()
      }, 1000)
    }
  },
  methods: {
    startTour() {
      this.$tours['importTour'].start(1)
      const tour = this.$tours['importTour']
      tour.previousStep = function() {
        sessionStorage.setItem('isTour', '2')
        this.$router.push({ path: '/grid/create/create' })
      }
    },
    getIframeSrc() {
      const baseUrl = '/baidu/regionSelect.html'
      const queryString = new URLSearchParams({
        NODE_ENV: process.env.NODE_ENV,
        type: 'first'
      }).toString()
      return `${baseUrl}?${queryString}`
    },
    async onInputBlur() {
      if (this.formData.currentPageName?.trim().length < 2) {
        return
      }
      const res = await checkName({
        gridName: this.formData.currentPageName
      })
      if (res.code === 200 && res.data) {
        this.formData.currentPageName = ''
        this.$message.error('网格名称不能重复，请重新填写')
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    async getDetailData() {
      try {
        this.pageLoading = true
        const { code, data } =
          this.isStash === '1'
            ? await getTopRedis()
            : await getRegionDes(this.gridId)
        if (code === 200) {
          this.formData = {
            gridType: data.gridType,
            gridResponsibilityType: data.gridDutyType,
            currentPageName: data.gridName,
            opsDept: data.opsDept
          }
          this.estimatedNumberOfClirnt = data.custCount
          this.areaChecked = this.isStash
            ? data?.adminDivisionDTOList?.map((it) => it.code)
            : data?.divisionRelateList
          this.getCountData(this.regionCodeFilter(this.areaChecked))

          if (this.isStash === '1') {
            if (data.gridDutyType === '1') {
              this.formData.deptTree =
                data?.gridUserRelateDTOList?.[0]?.relateDeptId
              this.orgCheckedOnlyOneArr = data?.gridUserRelateDTOList?.map(
                (it) => ({
                  id: it.relateDeptId,
                  level: it.relateDeptType,
                  label: it.relateDeptName
                })
              )
            } else {
              this.orgChecked = data?.gridUserRelateDTOList?.map(
                (ot) => ot.relateDeptId
              )
            }
          } else {
            if (data.gridDutyType === '1') {
              this.formData.deptTree = data?.userRelateList?.[0]?.relateDeptId
              this.nowDeptTree = data.userRelateList
            } else {
              this.orgChecked = data?.userRelateList?.map(
                (ot) => ot.relateDeptId
              )
              this.nowDeptTree = data.userRelateList
            }
          }
          this.menuOptions = data?.addressTree || []
        }
      } catch (error) {
        console.error(error)
      } finally {
        setTimeout(async() => {
          const collectedArr = this.$refs.addressTree.getCheckedKeys()
          if (isEmpty(collectedArr)) return
          const regionKeys = this.regionCodeFilter(collectedArr)
          const output = await getRegionCoordQuery(regionKeys)
          const polygonData = output['data'].map((item) => item['polygonList'])
          if (!isEmpty(polygonData)) {
            window.frames['bdmap'].addPolygon(polygonData)
          }
        }, 1000)
        this.pageLoading = false
      }
    },
    onDeptTreeSelect(node) {
      if (node.id) {
        this.orgCheckedOnlyOneArr = [node]
        this.$refs.elForm.clearValidate('deptTree')
      }
    },
    editName() {
      this.isEditing = true
    },
    saveName() {
      this.isEditing = false
    },
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
      })
    },
    validateTree(rule, value, callback) {
      const checkedKeys = this.$refs.addressTree.getCheckedKeys()
      const collected = []
      var temp = 12
      setTimeout(() => {
        for (let i = 0; i < checkedKeys.length; i++) {
          if (checkedKeys[i].length < temp) {
            collected.push(checkedKeys[i])
          }
          temp = checkedKeys[i].length
        }
      }, 100)
      if (checkedKeys.length === 0) {
        callback(new Error('请至少选择一个选项'))
      } else {
        callback()
      }
    },
    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(collectedArr) {
      if (isEmpty(collectedArr)) {
        return (this.estimatedNumberOfClirnt = 0)
      }
      getCustCount({ collect: collectedArr }).then((res) => {
        this.estimatedNumberOfClirnt = res.data
      })
    },
    async onChecked(data, checkedObj) {
      const collectedArr = this.regionCodeFilter(checkedObj.checkedKeys)
      if (isEmpty(collectedArr)) {
        window.frames['bdmap'].cleanPolygon()
        return (this.estimatedNumberOfClirnt = 0)
      }

      this.getCountData(collectedArr)

      const regionKeys = this.regionCodeFilter(collectedArr)
      const output = await getRegionCoordQuery(regionKeys)
      const polygonData = output['data'].map((item) => item['polygonList'])
      if (!isEmpty(polygonData)) {
        window.frames['bdmap'].addPolygon(polygonData)
      }
    },
    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]
    },
    handleconnect() {},
    handledisconnect() {},
    async getMenuTreeselect() {
      treeselect({ code: '33' })
        .then((response) => {
          this.menuOptions = response.data
          this.menuOptions.forEach((item) => {
            if (item.level === 2) {
              item.disabled = true
            }
          })
        })
        .catch((error) => {
          console.log('error', error)
        })
    },
    getDeptTreeSelect() {
      getTopDeptTree().then((response) => {
        this.deptOptions = response.data
      })
    },
    handleSelect(value) {
      if (value === '0') {
        this.getMenuTreeselect()
      }
    },
    onStash() {},
    getSubmitForm: debounce(function(isStash = false) {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          const adminDivisionDTOList = []
          if (this.formData.currentPageName?.trim()?.length < 2) {
            return this.$message.error(
              '网格名称最少两个字符，请修改后重新提交'
            )
          }
          this.$refs.addressTree.getCheckedNodes().forEach((element) => {
            adminDivisionDTOList.push({
              code: element.value,
              label: element.label
            })
          })
          this.$refs.addressTree.getHalfCheckedNodes().forEach((element) => {
            adminDivisionDTOList.push({
              code: element.value,
              label: element.label
            })
          })
          // 机构树
          const gridUserRelateDTOList = []
          const deptTreeCheckedArr =
            this.formData.gridResponsibilityType === '1'
              ? this.orgCheckedOnlyOneArr
              : this.$refs.deptTree.getCheckedNodes()
          if (
            this.formData.gridResponsibilityType === '2' &&
            deptTreeCheckedArr.length <= 1
          ) {
            this.$message({
              type: 'warning',
              message: '竞争网格时，归属机构必须选择2个及以上'
            })
            return
          }
          deptTreeCheckedArr?.forEach((element) => {
            gridUserRelateDTOList.push({
              relateDeptId: element.id,
              relateDeptName: element.label,
              relateDeptType: element.level,
              optFlag: '0',
              relateType: '2'
            })
          })
          const data = {
            adminDivisionDTOList: adminDivisionDTOList,
            gridDutyType: this.formData.gridResponsibilityType,
            gridLevel: '1',
            gridName: this.formData.currentPageName,
            gridType: this.formData.gridType,
            gridUserRelateDTOList: gridUserRelateDTOList,
            opsDept: this.formData.opsDept
          }
          if (Number(this.edit) === 2) {
            // 编辑页
            data.gridId = this.gridId
            if (
              !isEqual(
                this.areaChecked,
                this.$refs.addressTree.getCheckedKeys()
              )
            ) {
              data.deleteAdminDivisionList = this.findUniqueEle(
                this.areaChecked,
                this.$refs.addressTree.getCheckedKeys()
              )
            }
            const deleteUserRelate = this.findUniqueEle(
              this.orgChecked,
              gridUserRelateDTOList?.map((ob) => ob.relateDeptId)
            )
            const newArr = gridUserRelateDTOList
              ?.map((ot) => {
                if (!this.orgChecked.includes(ot.relateDeptId)) {
                  return ot
                }
                return null
              })
              ?.filter((on) => on)
            if (!isEmpty(deleteUserRelate)) {
              const resultArr = this.findObjById(
                this.deptOptions,
                deleteUserRelate
              )
              data.gridUserRelateDTOList = [
                ...newArr,
                ...resultArr?.map((oi) => ({
                  relateDeptId: oi.id,
                  relateDeptName: oi.label,
                  relateDeptType: oi.level,
                  optFlag: '1',
                  relateType: 2
                }))
              ]
            } else {
              const arr = this.nowDeptTree.map((item) => {
                return {
                  optFlag: '1',
                  relateDeptId: item.relateDeptId,
                  relateDeptName: item.relateDeptName,
                  relateDeptType: item.relateDeptType,
                  relateType: 2
                }
              })
              if (newArr.length == 0) {
                data.gridUserRelateDTOList = [...newArr]
              } else {
                data.gridUserRelateDTOList = [...newArr, ...arr]
              }
            }
          }
          this.btnLoading = true
          let apiUrl
          if (isStash) {
            apiUrl = saveTopRedis
          } else {
            apiUrl = Number(this.edit) === 2 ? regionUpdate : createTopGrid
          }
          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),
    findObjById(data, ids) {
      const result = []
      function search(node) {
        if (ids.includes(node.id)) {
          result.push(node)
        }
        if (node.children) {
          node.children.forEach((child) => search(child))
        }
      }

      data.forEach((ot) => search(ot))
      return result
    },
    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)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "./../created/component/create-style.scss";

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

    .myGrid {
      ::v-deep .el-form-item__label {
        // text-align: left;
        line-height: 19px;
        // padding-right: 10px;
      }
    }
  }
}

.question_icon {
  color: #b9b9b9;
}

::v-deep .el-checkbox.is-disabled {
  display: none;
}
::v-deep .v-step::after {
  content: "";
  position: absolute;
  width: 100px;
  height: 100px;
  background-image: url("../../../../assets/images/arrow.gif");
  background-repeat: no-repeat;
  background-size: contain;
  top: 0;
  left: 50%;
  z-index: 9999999;
}

::v-deep .v-step[data-popper-placement^="right"]::after {
  top: -80%;
  left: -75%;
}
</style>
<style>
@import "../../tour.css";
</style>
