<template>
  <a-modal
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <template slot="title">
      <div class="modalTitle">
        <div class="modalColor"></div>
        <div>{{ title }}</div>
      </div>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules" :hideRequiredMark="true">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="上级行政区划" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="parentAreaName">
              <a-input v-model="model.parentAreaName" placeholder="请输入上级行政区划" :disabled="true"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="等级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="areaLevel">
              <j-dict-select-tag
                v-model="model.areaLevel"
                placeholder="请选择等级"
                dictCode="area_level"
                :disabled="true"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="areaName">
              <a-input
                v-model="model.areaName"
                placeholder="请输入行政区划名称"
                :maxLength="256"
                :disabled="disableSubmit"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" class="areaCodeArea">
            <a-form-model-item label="代码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="areaCode">
              <a-input
                :maxLength="2"
                v-model="provinceCode"
                :disabled="disabledAreaLevel >= 1 || disableSubmit"
                class="noRightStyle"
                oninput="value=value.replace(/\D/g,'')"
              ></a-input>
              <span class="line">-</span>
              <a-input
                :maxLength="2"
                v-model="countryCode"
                :disabled="disabledAreaLevel < 3 || disabledAreaLevel > 3 || disableSubmit"
                class="noRightStyle"
                oninput="value=value.replace(/\D/g,'')"
              ></a-input>
              <span class="line">-</span>
              <a-input
                v-model="countyCode"
                :disabled="disabledAreaLevel < 4 || disabledAreaLevel > 4 || disableSubmit"
                class="noRightStyle"
                :maxLength="2"
                oninput="value=value.replace(/\D/g,'')"
              ></a-input>
              <span class="line">-</span>
              <a-input
                v-model="townCode"
                :disabled="disabledAreaLevel < 5 || disabledAreaLevel > 5 || disableSubmit"
                class="noRightStyle"
                :maxLength="3"
                oninput="value=value.replace(/\D/g,'')"
              ></a-input>
              <span class="line">-</span>
              <a-input
                v-model="villageCode"
                :disabled="disabledAreaLevel < 5 || disabledAreaLevel > 5 || disableSubmit"
                class="noRightStyle"
                :maxLength="3"
                oninput="value=value.replace(/\D/g,'')"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="简称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="areaShortName">
              <a-input
                v-model="model.areaShortName"
                placeholder="请输入行政区划简称"
                :max="128"
                :disabled="disableSubmit"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="areaType">
              <a-select
                v-model="model.areaType"
                placeholder="请选择行政区划类型"
                :disabled="disableSubmit"
                :getPopupContainer="(triggerNode) => triggerNode.parentNode"
              >
                <a-select-option v-for="item in areaTypeOptions" :key="item.value" :value="item.value">
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="是否为特殊区划" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isSpecial">
              <j-dict-select-tag
                type="radio"
                v-model="model.isSpecial"
                placeholder="请选择是否特殊区划"
                dictCode="is_special"
                :disabled="disableSubmit"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" class="aColUn">
            <a-form-model-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="description">
              <a-textarea
                v-model="model.description"
                :rows="4"
                :maxLength="500"
                resize="none"
                placeholder="请输入行政区划描述"
                :disabled="disableSubmit"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-show="isEditOrAdd == 'edit'">
            <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
              <!-- <j-dict-select-tag type="list" v-model="model.status"  placeholder="请选择行政区划状态" dictCode="area_status"/> -->
              <a-select
                v-model="model.status"
                placeholder="请选择行政区划状态"
                :disabled="disableSubmit"
                @change="statusChange"
                :getPopupContainer="(triggerNode) => triggerNode.parentNode"
              >
                <a-select-option v-for="item in statusOptions" :key="item.value" :value="item.value">
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="顺序" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="areaOrder">
                  <a-input-number :min="0" :max="99999" v-model="model.areaOrder" :disabled="disableSubmit">
                  </a-input-number>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="24">
            <a-col :span="12">
              <a-form-model-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createBy">
                <a-input v-model="model.createBy" :disabled="true"> </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                <a-input v-model="model.createTime" :disabled="true"> </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="最近更新人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="updateBy">
                <a-input v-model="model.updateBy" :disabled="true"> </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="最近更新时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="updateTime">
                <a-input v-model="model.updateTime" :disabled="true"> </a-input>
              </a-form-model-item>
            </a-col>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
export default {
  name: 'GtSysAreaModal',
  components: {},
  data() {
    return {
      title: '操作',
      width: 1200,
      visible: false,
      disableSubmit: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      confirmLoading: false,
      validatorRules: {
        performLevel: [
          {
            required: true,
            message: '区划等级为自动加载，如没有，请联系管理员 ',
          },
        ],
        areaName: [
          {
            required: true,
            message: '请输入行政区划名称',
          },
        ],
        status: [
          {
            required: true,
            message: '请选择状态',
          },
        ],
        areaShortName: [
          {
            required: true,
            message: '请输入行政区划简称',
          },
        ],
        areaType: [
          {
            required: true,
            message: '请选择行政区划类型',
            validator: this.areaTypeValidator,
          },
        ],
        isSpecial: [
          {
            required: true,
            message: '请选择特殊区划',
          },
        ],
        areaOrder: [
          {
            required: true,
            message: '请输入顺序',
          },
        ],
        areaCode: [
          {
            required: true,
            validator: this.areaCodeValidator,
          },
        ],
      },
      url: {
        add: '/gtSysArea/add',
        edit: '/gtSysArea/edit',
      },
      expandedRowKeys: [],
      pidField: 'parentId',
      provinceCode: '00',
      countryCode: '00',
      countyCode: '00',
      townCode: '000',
      villageCode: '000',
      areaTypeOption: 'is_special',
      // 根据层级禁止编辑区划编码
      disabledAreaLevel: 0,
      // 判断是新增还是编辑,add是新增，edit是编辑
      isEditOrAdd: 'add',
      // 行政区划类型
      areaTypeOptions: [],
      // 行政区划状态
      statusOptions: [],
      // 代码初次进入显示00-00-000-000这种格式
      firstCode: true,
      // 记录当前的数据level
      currentRecordLevel: {},
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    //  行政区划状态初始化
    this.initStatusOptionsDictConfig('area_status')
  },
  methods: {
    // 行政区划类型初始化
    initAreaTypeDictConfig(type) {
      let _this = this
      //初始化字典 - 行政区划类型
      initDictOptions(type).then((res) => {
        if (res.success) {
          _this.areaTypeOptions = res.result
        }
      })
    },
    // 行政区划状态初始化
    initStatusOptionsDictConfig(type) {
      let _this = this
      //初始化字典 - 行政区划类型
      initDictOptions(type).then((res) => {
        if (res.success) {
          // res.result.forEach(item => {
          //   item['value'] = Number(item['value']);
          // });
          _this.statusOptions = res.result
        }
      })
    },
    add(obj, record) {
      console.log(record)
      this.modelDefault.parentId = ''
      this.visible = true
      // this.edit(Object.assign(this.modelDefault , obj));
      this.modelUn = {}
      this.modelUn.parentId = obj.parentId
      this.modelUn.parentAreaName = record.areaName + '(' + record.areaCode + ')'
      this.modelUn.areaLevel = String(Number(record.areaLevel) + 1)
      this.disabledAreaLevel = Number(record.areaLevel) + 1
      this.currentRecordLevel = this.disabledAreaLevel
      // 加载areaType下拉框
      this.addAreaTypeOptionNew(record.areaLevel)
      // 加载区划编码被禁input的值
      this.loadAreaCodeInputAdd(record.areaLevel, record.areaCode)
      this.isEditOrAdd = 'add'
      this.modelUn.isSpecial = '0'
      this.model = this.modelUn
    },
    edit(record) {
      this.model = Object.assign({}, record)
      console.log(record)
      this.model.parentAreaName = record.parentAreaName
      this.visible = true
      this.disabledAreaLevel = record.areaLevel
      this.currentRecordLevel = this.disabledAreaLevel
      // 加载areaType下拉框
      this.addAreaTypeOptionEdit(record.areaLevel)
      // 加载区划编码被禁input的值
      this.loadAreaCodeInputEdit(record.areaLevel, record.areaCode)
      this.isEditOrAdd = 'edit'
      // this.model.areaType = record.areaType;
      this.$nextTick(() => {
        this.model.areaType = String(record.areaType)
      })
    },
    check(record) {
      this.model = Object.assign({}, record)
      if (!this.model.description) {
        this.model.description = ' '
      }
      console.log(this.model)
      this.model.parentAreaName = record.parentAreaName
      this.visible = true
      this.disabledAreaLevel = record.areaLevel
      // 加载areaType下拉框
      this.addAreaTypeOptionEdit(record.areaLevel)
      // 加载区划编码被禁input的值
      this.loadAreaCodeInputEdit(record.areaLevel, record.areaCode)
      this.isEditOrAdd = 'check'
      // this.model.areaType = record.areaType;
      this.$nextTick(() => {
        this.model.areaType = String(record.areaType)
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.$refs.form.clearValidate()
      this.provinceCode = '00'
      this.countryCode = '00'
      this.countyCode = '00'
      this.townCode = '000'
      this.villageCode = '000'
    },
    statusChange(value) {
      let _this = this
      if (value == '0') {
        console.log(value)
        this.$confirm({
          class: 'delete_qx',
          title: '警告',
          content: (
            <div>
              <div>
                <span style="color:red">您将区划状态修改为“无效”</span>
                ，系统会默认将下属区划、组织机构、用户都修改为“无效”状态，“无效”的用户无法登录。
              </div>
            </div>
          ),
          okText: '确定',
          icon: 'exclamation-circle',
          onOk() {
            _this.model.status = '0'
            // _this.handleOk();
          },
          onCancel() {
            _this.model.status = '1'
          },
        })
      }
    },
    handleOk() {
      const that = this
      if (that.isEditOrAdd == 'check') {
        that.handleCancel()
      } else {
        // 触发表单验证
        if (that.countryCode == null) {
          that.countryCode = '00'
        }
        if (that.countyCode == null) {
          that.countyCode = '00'
        }
        if (that.townCode == null || that.townCode == undefined) {
          that.townCode = '000'
        } else if (String(that.townCode).length == '0') {
          that.townCode = '000'
        } else if (String(that.townCode).length == '1') {
          that.townCode = '00' + that.townCode
        } else if (String(that.townCode).length == '2') {
          that.townCode = '0' + that.townCode
        }
        if (that.villageCode == null || that.villageCode == undefined) {
          that.villageCode = '000'
        } else if (String(that.villageCode).length == '0') {
          that.villageCode = '000'
        } else if (String(that.villageCode).length == '1') {
          that.villageCode = '00' + that.villageCode
        } else if (String(that.villageCode).length == '2') {
          that.villageCode = '0' + that.villageCode
        }
        that.model.areaCode =
          that.provinceCode +
          String(that.countryCode).padStart(2, '0') +
          String(that.countyCode).padStart(2, '0') +
          that.townCode +
          that.villageCode
        if (that.isEditOrAdd == 'add') {
          that.model.status = '1'
        }
        this.$refs.form.validate((valid) => {
          if (valid) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            if (this.model.id && this.model.id === this.model[this.pidField]) {
              that.$message.warning('父级节点不能选择自己')
              that.confirmLoading = false
              return
            }
            httpAction(httpurl, this.model, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  this.$emit('ok')
                  that.close()
                } else if (res.code == '18005') {
                  this.$confirm({
                    class: 'delete_qx',
                    title: '代码已被暂用',
                    content: (
                      <div>
                        <div>{res.message}</div>
                      </div>
                    ),
                    okText: '确定',
                    type: 'error',
                    icon: 'close-circle',
                  })
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          } else {
            return false
          }
        })
      }
    },
    handleCancel() {
      this.close()
    },
    areaCodeChange(e) {
      let _this = this
      console.log(e.target.value)
      console.log(e.target.value.replace(/[^1-9.]/g, ''))
      return e.target.value.replace(/[^1-9.]/g, '')
    },
    submitSuccess(formData, flag) {
      if (!formData.id) {
        let treeData = this.$refs.treeSelect.getCurrTreeData()
        this.expandedRowKeys = []
        this.getExpandKeysByPid(formData[this.pidField], treeData, treeData)
        this.$emit('ok', formData, this.expandedRowKeys.reverse())
      } else {
        this.$emit('ok', formData, flag)
      }
    },
    getExpandKeysByPid(pid, arr, all) {
      if (pid && arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].key == pid) {
            this.expandedRowKeys.push(arr[i].key)
            this.getExpandKeysByPid(arr[i]['parentId'], all, all)
          } else {
            this.getExpandKeysByPid(pid, arr[i].children, all)
          }
        }
      }
    },
    numberFormatterProvince(value) {
      let _this = this
      if (_this.currentRecordLevel == 2) {
        return value
      } else {
        if (value.length == '0') {
          return '00'
        } else if (value.length == '1') {
          return '0' + value
        } else {
          return value
        }
      }
    },
    numberFormatterCountry(value) {
      let _this = this
      if (_this.currentRecordLevel == 3) {
        return value
      } else {
        if (value.length == '0') {
          return '00'
        } else if (value.length == '1') {
          return '0' + value
        } else {
          return value
        }
      }
    },
    numberFormatterCounty(value) {
      let _this = this
      if (_this.currentRecordLevel == 4) {
        return value
      } else {
        if (value.length == '0') {
          return '00'
        } else if (value.length == '1') {
          return '0' + value
        } else {
          return value
        }
      }
    },
    numberFormatterTown(value) {
      let _this = this
      if (_this.currentRecordLevel == 5) {
        return value
      } else {
        if (value.length == '0') {
          return '000'
        } else if (value.length == '1') {
          return '00' + value
        } else if (value.length == '2') {
          return '0' + value
        } else {
          return value
        }
      }
    },
    numberFormatterVillage(value) {
      let _this = this
      console.log(_this.currentRecordLevel)
      if (_this.currentRecordLevel == 5) {
        return value
      } else {
        if (value.length == '0') {
          return '000'
        } else if (value.length == '1') {
          return '00' + value
        } else if (value.length == '2') {
          return '0' + value
        } else {
          return value
        }
      }
    },
    addAreaTypeOptionNew(level) {
      let _this = this
      let _level = level
      if (!_level) {
        return false
      } else if (_level == 2) {
        _this.initAreaTypeDictConfig('province_area_type')
      } else if (_level == 3) {
        _this.initAreaTypeDictConfig('country_area_type')
      } else if (_level == 4) {
        _this.initAreaTypeDictConfig('district_area_type')
      }
      _this.$forceUpdate()
    },
    addAreaTypeOptionEdit(level) {
      let _this = this
      let _level = level
      if (!_level) {
        return false
      } else if (_level == 2) {
        _this.initAreaTypeDictConfig('province_area_type')
      } else if (_level == 3) {
        _this.initAreaTypeDictConfig('province_area_type')
      } else if (_level == 4) {
        _this.initAreaTypeDictConfig('country_area_type')
      } else if (_level == 5) {
        _this.initAreaTypeDictConfig('district_area_type')
      }
      _this.$forceUpdate()
    },
    loadAreaCodeInputAdd(level, areaCode) {
      let _this = this
      let _level = level
      let _areaCode = areaCode
      if (!_level || !_areaCode) {
        return false
      } else if (_level == 1) {
        _this.provinceCode = _areaCode.slice(0, 2)
        _this.countryCode = '00'
        _this.countyCode = '00'
        _this.townCode = '000'
        _this.villageCode = '000'
      } else if (_level == 2) {
        _this.provinceCode = _areaCode.slice(0, 2)
        _this.countryCode = _areaCode.slice(2, 4)
        _this.countyCode = '00'
        _this.townCode = '000'
        _this.villageCode = '000'
      } else if (_level == 3) {
        _this.provinceCode = _areaCode.slice(0, 2)
        _this.countryCode = _areaCode.slice(2, 4)
        _this.countyCode = _areaCode.slice(4, 6)
        _this.townCode = '000'
        _this.villageCode = '000'
      } else if (_level == 4) {
        _this.provinceCode = _areaCode.slice(0, 2)
        _this.countryCode = _areaCode.slice(2, 4)
        _this.countyCode = _areaCode.slice(4, 6)
        _this.townCode = _areaCode.slice(6, 9)
      }
      _this.$forceUpdate()
    },
    loadAreaCodeInputEdit(level, areaCode) {
      let _this = this
      let _level = level
      let _areaCode = areaCode
      if (!_level || !_areaCode) {
        return false
      } else {
        _this.provinceCode = _areaCode.slice(0, 2)
        _this.countryCode = _areaCode.slice(2, 4)
        _this.countyCode = _areaCode.slice(4, 6)
        _this.townCode = _areaCode.slice(6, 9)
        _this.villageCode = _areaCode.slice(9, 12)
      }
      _this.$forceUpdate()
    },
    areaShortNameValidator(rule, value, callback) {
      let _this = this
      if (!value || value.trim() == '') {
        callback(new Error('请输入行政区划简称'))
      } else {
        callback()
      }
    },
    areaCodeValidator(rule, value, callback) {
      callback()
    },
  },
}
</script>
<style lang="less" scoped>
/deep/.action-button .ant-btn-primary {
  
  
  border-radius: 2px;
}

/deep/ .ant-modal-footer {
  padding: 10px 16px 45px;
  border-top: 0;

  > div {
    display: flex;
    justify-content: center;
  }

  .ant-btn {
    width: 76px;
    height: 35px;
    line-height: 34px;

    border-radius: 2px 2px 2px 2px;
    opacity: 1;
    
    padding: 0;

 
  }

  .ant-btn-primary {
    
    
    color: #ffffff;

    &:hover {
      color: #fff !important;
    }
  }
}

::v-deep .ant-input-number:focus {
  
  
}

::v-deep .ant-input-number:hover {
  
}

::v-deep .ant-input-number-focused {
  
  
}

::v-deep .ant-input-number-handler:hover .ant-input-number-handler-up-inner {
  
}

::v-deep .ant-input-number-handler:hover .ant-input-number-handler-down-inner {
  
}

// 输入框
/deep/.ant-input {
  height: 38px;
}

/deep/ textarea.ant-input {
  height: auto;
}

/deep/.input-table .tbody .td input {
  height: 38px;
}

// 下拉框
::v-deep.ant-select {
  .ant-select-selection--single {
    height: 38px;
  }

  .ant-select-selection__rendered {
    line-height: 38px;
  }

  .ant-select-dropdown-menu-item-active:not(.ant-select-dropdown-menu-item-disabled) {
    
  }
}

/deep/.ant-input-number {
  height: 38px;
  line-height: 38px;
}

::v-deep.ant-row {
  & > .ant-col:nth-child(3),
  & > .ant-col:nth-child(4),
  & > .ant-col:nth-child(5),
  & > .ant-col:nth-child(6),
  & > .ant-col:nth-child(9) {
    .ant-form-item {
      .ant-form-item-control-wrapper {
        position: relative;

        &::before {
          position: absolute;
          content: '*';
          color: #f10f0f;
          top: 0;
          right: -24px;
          font-size: 24px;
          line-height: 44px;
        }
      }
    }
  }

  & > .ant-col:nth-child(7),
  & > .ant-col:nth-child(10) {
    .ant-form-item {
      .ant-form-item-control-wrapper {
        position: relative;

        &::before {
          position: absolute;
          content: '*';
          color: #f10f0f;
          top: 0;
          right: 270px;
          font-size: 24px;
          line-height: 44px;
        }
      }
    }
  }
}

// 滚动条
/deep/::-webkit-scrollbar-thumb {
  
  border-radius: 9px 9px 9px 9px;
}
</style>
<style scoped>
@import '~@assets/less/modal.less';
@import '~@assets/less/input.less';

.modalColor {
  
}

.areaCodeArea .line {
  margin: 0 2px;
  display: inline-block;
  width: 6px;
  text-align: center;
}

.areaCodeArea >>> .noRightStyle {
  width: calc(20% - 8px);
}

.aColUn > div >>> .ant-col:first-child {
  width: 10.4%;
}

.aColUn > div >>> .ant-col:nth-child(2) {
  width: 89.6%;
}

.aColUn > div >>> .ant-col:nth-child(2) > .ant-form-item-control {
  width: 93%;
}

.ant-form-item label {
  font-size: 16px;
}
</style>