<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"
            label-width="130px"
            size="medium"
            label-position="top"
          >
            <el-form-item label="网格名称" prop="currentPageName">
              <el-input
                v-model="formData.currentPageName"
                minlength="2"
                placeholder="请输入"
                clearable
                maxlength="20"
                size="small"
                @blur="onInputBlur"
              />
            </el-form-item>
            <el-form-item
              label="请选择总行行政网格名称"
              prop="firGrid"
              class="myGrid"
            >
              <el-select
                v-model="formData.firGrid"
                :disabled="Number(edit) === 1 || isEdit"
                placeholder="请选择总行行政网格"
                clearable
                style="width: 100%"
                @change="handleSelectTop"
              >
                <el-option
                  v-for="item in firGridOptions"
                  :key="item.gridId"
                  :label="item.gridName"
                  :value="item.gridId"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="formData.firGrid"
              label="业务部门归属"
              prop="opsDept"
            >
              <el-radio-group
                v-model="formData.opsDept"
                size="medium"
                :disabled="true"
              >
                <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.firGrid"
              label="网格类型"
              prop="gridType"
            >
              <el-select
                v-model="formData.gridType"
                placeholder="请选择网格类型"
                :disabled="isEdit"
                clearable
                style="width: 100%"
                @click="handleSelect"
              >
                <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
              v-if="formData.firGrid"
              label="选择行政区划"
              class="tree-select"
              prop="addressTree"
            >
              <el-tree
                ref="addressTree"
                class="tree-border"
                :data="menuOptions"
                show-checkbox
                node-key="value"
                :check-strictly="!formData.menuCheckStrictly"
                :default-checked-keys="areaChecked"
                :default-expanded-keys="areaChecked"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                @check="onChecked"
              />
            </el-form-item>
            <el-form-item
              v-if="formData.firGrid"
              label="预计客户数"
              prop="clientNumber"
            >
              <span>{{ estimatedNumberOfClirnt }}</span>
            </el-form-item>
            <el-form-item
              v-if="formData.firGrid"
              label="网格责任类型"
              prop="gridResponsibilityType"
            >
              <el-radio-group
                v-model="formData.gridResponsibilityType"
                size="medium"
                @change="onGridResponsibilityTypeChange"
              >
                <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>
            <div v-if="formData.firGrid">
              <el-form-item label="客户经理" prop="clientManager">
                <el-select
                  v-model="formData.clientManager"
                  size="small"
                  filterable
                  multiple
                  :multiple-limit="
                    formData.gridResponsibilityType === '2' ? 0 : 1
                  "
                  placeholder="请选择"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="option in managerOptions"
                    :key="option.Id"
                    :label="`${option.deptName}-${option.userName}-${option.nickName}`"
                    :value="option.userName"
                  />
                </el-select>
              </el-form-item>
            </div>
          </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>
          </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 { getSecAddressTree as treeselect } from '@/api/grid/address/tree.js'
import {
  getTopList,
  createSecGrid,
  getUserListByGridId,
  getCustCount
} from '@/api/grid/region.js'
import {
  getRegionDes,
  secRegionUpdate,
  saveSecRedis,
  getSecRedis,
  checkName
} from '@/api/grid/list/gridlist.js'
import { isEqual, cloneDeep, isEmpty, debounce } from 'lodash'
import { getRegionCoordQuery } from '@/api/grid/draw-area.js'
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,
      isEditing: false,
      menuOptions: [],
      gridId: [],
      gridName: null,
      estimatedNumberOfClirnt: 0,
      formData: {
        firGrid: '',
        gridType: undefined,
        associatedMap: undefined,
        clientNumber: undefined,
        gridResponsibilityType: '1',
        homeOrganization: undefined,
        menuCheckStrictly: true,
        clientManager: [],
        currentPageName: '',
        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'
          }
        ],
        firGrid: [
          {
            required: true,
            message: '请选择总行行政网格',
            trigger: 'change'
          }
        ],
        opsDept: [
          {
            required: true,
            message: '请选择业务部门归属',
            trigger: 'change'
          }
        ],
        gridType: [
          {
            required: true,
            message: '请选择网格类型',
            trigger: 'change'
          }
        ],
        gridResponsibilityType: [
          {
            required: true,
            message: '网格责任类型不能为空',
            trigger: 'change'
          }
        ],
        addressTree: [
          {
            validator: this.validateTree,
            required: true,
            trigger: 'change'
          }
        ],
        homeOrganization: [
          {
            required: true,
            message: '请输入归属机构',
            trigger: 'blur'
          }
        ],
        clientManager: [
          {
            required: true,
            message: '请输入客户经理',
            trigger: 'blur'
          }
        ]
      },
      firGridOptions: [],
      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'
        }
      ],
      managerOptions: [],
      value: [],
      selectedOptions: [{ selected: null }],
      ManagerOptions: [{ value: '' }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      areaChecked: [],
      orgChecked: [],
      operateName: '创建成功',
      btnLoading: false,
      pageLoading: false
    }
  },
  computed: {
    edit() {
      return this.$route.query.edit
    },
    isEdit() {
      return Number(this.$route.query?.edit) === 2
    },
    routeGridId() {
      return this.$route.query.gridId
    },
    topGridId() {
      return this.$route.query.topGridId
    },
    gridType() {
      return this.$route.query.gridType
    },
    pageName() {
      return this.isEdit ? '支行行政网格修改' : '支行行政网格创建'
    },
    isStash() {
      return this.$route.query?.isStash
    },
    isTour() {
      return sessionStorage.getItem('isTour')
    }
  },
  watch: {
    'formData.firGrid'(newValue) {
      if (!this.isEdit && !this.isStash) {
        this.getMenuTreeselect()
      }
      this.getMenuManagerSelect()
    },
    edit: {
      handler(val) {
        if (Number(val) === 2) {
          this.gridId = this.routeGridId
          this.getDetailData()
        } else if (Number(val) === 1) {
          this.gridId = this.routeGridId
          this.formData.gridType = this.gridType
          this.formData.firGrid = Number(this.routeGridId)
          this.formData.opsDept = this.$route.query.opsDept
          this.parentGridId = Number(this.routeGridId)
        }
      },
      immediate: true
    },
    isStash: {
      handler(val) {
        if (Number(val) === 1) {
          this.getDetailData()
        }
      },
      immediate: true
    }
  },
  created() {
    this.getTopSelect()
    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() {
      console.log(this.steps, 'steps')
      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: 'second'
      }).toString()
      return `${baseUrl}?${queryString}`
    },
    onGridResponsibilityTypeChange() {
      this.formData.clientManager = []
    },
    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('网格名称不能重复，请重新填写')
      }
    },
    async getDetailData() {
      try {
        this.pageLoading = true
        const { code, data } =
          this.isStash === '1'
            ? await getSecRedis()
            : await getRegionDes(this.routeGridId)

        if (code === 200) {
          this.formData = {
            firGrid: data.parentGridId,
            gridType: data.gridType,
            gridResponsibilityType: data.gridDutyType,
            clientManager: this.isStash
              ? data?.gridUserRelateDTOList?.map((ot) => ot.userName)
              : data?.userRelateList?.map((ot) => ot.userName),
            currentPageName: data.gridName,
            opsDept: data.opsDept
          }
          if (this.isStash) {
            this.gridId = data.parentGridId
          }
          this.parentGridId = data.parentGridId
          this.menuOptions = data.addressTree
          this.estimatedNumberOfClirnt = data.custCount
          this.areaChecked = data?.divisionRelateList || []
          this.areaChecked = this.isStash
            ? data?.adminDivisionCodeList
            : data?.divisionRelateList
          this.orgChecked = cloneDeep(this.formData.clientManager)
          this.getCountData(this.areaChecked)
          if (data.divisionRelateList) {
            const regionKeys = this.regionCodeFilter(data.divisionRelateList)
            const output = await getRegionCoordQuery(regionKeys)
            const polygonData = output['data'].map(
              (item) => item['polygonList']
            )
            window.frames['bdmap'].addPolygon(polygonData)
          }
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.pageLoading = false
      }
    },
    editName() {
      this.isEditing = true
    },
    saveName() {
      this.isEditing = false
    },
    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 = checkedObj.checkedKeys
      if (isEmpty(collectedArr)) {
        window.frames['bdmap'].cleanPolygon()
        return (this.estimatedNumberOfClirnt = 0)
      }
      const collect = collectedArr.filter((code) => code.length === 12)
      this.getCountData(collect)

      const output = await getRegionCoordQuery(collect)
      const polygonData = output['data'].map((item) => item['polygonList'])
      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]
    },
    handleSelectTop(value) {
      this.estimatedNumberOfClirnt = 0
      this.formData.clientManager = []
      this.gridId = value
      this.parentGridId = value
      const option = this.firGridOptions.find(
        (item) => item.gridId === this.gridId
      )
      this.gridName = option ? option.gridName : null
      this.formData.gridType = option ? option.gridType : null
      this.formData.opsDept = option ? option.opsDept : null
      this.getTopSelect()
    },
    getTopSelect() {
      getTopList()
        .then((response) => {
          this.firGridOptions = response.data
        })
        .catch((error) => console.log('error', error))
    },
    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()
      }
    },
    getMenuTreeselect() {
      treeselect({ gridId: this.gridId })
        .then((response) => {
          this.menuOptions = response.data
        })
        .catch((error) => {
          console.log('error', error)
        })
    },
    getMenuManagerSelect() {
      getUserListByGridId({ gridId: this.gridId })
        .then((response) => {
          this.managerOptions = response.data
        })
        .catch((error) => console.log('error', error))
    },
    handleSelect(value) {
      if (value === '0') {
        this.getMenuTreeselect()
        this.getMenuManagerSelect()
      }
    },
    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
    },
    getSubmitForm: debounce(function(isStash = false) {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          const adminDivisionCodeList = []
          const gridUserRelateDTOList = []
          if (this.formData.currentPageName?.trim()?.length < 2) {
            return this.$message.error(
              '网格名称最少两个字符，请修改后重新提交'
            )
          }
          const { clientManager = [], gridResponsibilityType } = this.formData
          if (gridResponsibilityType === '2' && clientManager.length <= 1) {
            this.$message({
              type: 'warning',
              message: '竞争网格时，客户经理必须选择2个及以上'
            })
            return
          }
          this.$refs.addressTree.getCheckedNodes().forEach((element) => {
            adminDivisionCodeList.push(element.value)
          })
          clientManager?.map((item) => {
            const obj = this.managerOptions.find((ot) => ot.userName === item)
            gridUserRelateDTOList.push({
              relateDeptId: obj.deptId,
              relateDeptName: obj.deptName,
              relateDeptType: obj.deptType,
              optFlag: '0',
              relateType: '1',
              userId: obj.userId,
              userName: obj.userName,
              nickName: obj.nickName
            })
          })
          const data = {
            adminDivisionCodeList: adminDivisionCodeList,
            gridDutyType: this.formData.gridResponsibilityType,
            gridLevel: '2',
            gridName: this.formData.currentPageName,
            gridType: this.formData.gridType,
            gridUserRelateDTOList: gridUserRelateDTOList,
            parentGridId: this.parentGridId,
            opsDept: this.formData.opsDept
          }
          if (this.isEdit) {
            data.gridId = this.gridId
            const deleteUserRelate = this.findUniqueEle(
              this.orgChecked,
              gridUserRelateDTOList?.map((ob) => ob.userName)
            )
            const newArr = gridUserRelateDTOList
              ?.map((ot) => {
                if (!this.orgChecked.includes(ot.userName)) {
                  return ot
                }
                return null
              })
              ?.filter((on) => on)
            if (!isEmpty(deleteUserRelate)) {
              const resultArr = this.findObjById(
                this.managerOptions,
                deleteUserRelate
              )

              data.gridUserRelateDTOList = [
                ...newArr,
                ...resultArr?.map((oi) => ({
                  relateDeptId: oi.deptId,
                  relateDeptName: oi.deptName,
                  relateDeptType: oi.deptType,
                  optFlag: '1',
                  relateType: 1,
                  userId: oi.userId,
                  userName: oi.userName
                }))
              ]
            } else {
              data.gridUserRelateDTOList = [...newArr]
            }
          }
          this.btnLoading = true

          let apiUrl
          if (isStash) {
            apiUrl = saveSecRedis
          } else {
            apiUrl = this.isEdit ? secRegionUpdate : createSecGrid
          }
          console.log(data, '------------------>>')
          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: '确定',
                    callback: (action) => {
                      this.cancelForm()
                    }
                  }
                )
              }
            })
            .catch((err) => console.error(err))
            .finally(() => {
              setTimeout(() => {
                this.btnLoading = false
              }, 100)
            })
        } else {
          return false
        }
      })
    }, 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)
    }
  }
}
</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;
      }
    }
  }
}

::v-deep .el-checkbox.is-disabled {
  display: none;
}

.question_icon {
  color: #b9b9b9;
}

::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: -40%;
  left: -75%;
}
</style>
<style>
@import "../../tour.css";
</style>
