<template>
  <el-dialog title="添加地址" class="add-modal-wrap" append-to-body :visible.sync="visible" width="95%"
    :before-close="onClose" :close-on-click-modal="false">
    <section class="header-operate">
      <el-button size="small" type="primary" plain icon="el-icon-circle-plus-outline" class="add-btn"
        @click="onAdd">添加地址</el-button>
      <div class="dialog-footer">
        <el-button type="plain" size="small" @click="onClose">取消</el-button>
        <el-button type="primary" size="small" @click="onSubmit" :loading="btnLoading"
          :disabled="idDisabled">去审核</el-button>
      </div>
    </section>
    <el-form :inline="true" autoComplete="on" :model="formObj" :rules="formObjRules" ref="formObj">
      <section class="list-header">
        <p>
          <span>客户类型</span>
          <span>客户名称</span>
          <span>证件类型</span>
          <span>证件号</span>
          <span>地址类型</span>
          <span>地址</span>
          <span>工作行业</span>
          <span>预览解析结果</span>
          <span>备注</span>
          <span>操作</span>
        </p>
        <ul>
          <li class="formObj-form-item" v-for="(item, ind) in formObj.infoList" :key="item.key">
            <section class="form-vl">
              <el-form-item class="form-item form-item-custType" :prop="'infoList.' + ind + '.custType'"
                :rules="{ required: true, message: '客户类型为空', trigger: 'change' }">
                <el-select clearable disabled v-model="item.custType" filterable placeholder="请选择" class="select-wrap"
                  @change="(e) => onCustTypeChange(e, ind)">
                  <el-option v-for="item in clientTypeOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="form-item form-item-anchorName" :prop="'infoList.' + ind + '.anchorName'"
                :rules="{ required: true, message: '客户名称为空', trigger: 'blur' }">
                <el-input clearable v-model="item.anchorName" placeholder="请输入" class="input-name"></el-input>
              </el-form-item>
              <el-form-item class="form-item form-item-custIdType">
                <el-select clearable disabled v-model="item.custIdType" filterable placeholder="请选择" class="select-wrap">
                  <el-option v-for="item in custIdTypeOptions" :key="item.value" :label="item.label" :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="form-item form-item-legalId" :prop="'infoList.' + ind + '.legalId'"
                :rules="{ required: true, message: '证件号为空', trigger: 'blur' }">
                <el-input clearable v-model="item.legalId" placeholder="请输入" class="input-name"></el-input>
              </el-form-item>
              <el-form-item class="form-item form-item-addressName" :prop="'infoList.' + ind + '.addressName'"
                :rules="{ required: true, message: '地址类型为空', trigger: 'change' }">
                <el-select :disabled="!item.custType" clearable v-model="item.addressName" filterable placeholder="请选择"
                  class="select-wrap">
                  <el-option v-for="ot in item.addressTypeOptions" :key="ot.value" :label="ot.label" :value="ot.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="form-item form-item-address" :prop="'infoList.' + ind + '.address'"
                :rules="{ required: true, message: '地址为空', trigger: 'blur' }">
                <el-input clearable v-model="item.address" placeholder="请输入" class="input-name"></el-input>
              </el-form-item>
              <el-form-item class="form-item form-item-belongBusiness">
                <!-- <el-input clearable v-model="item.belongBusiness" placeholder="请输入" class="input-name"></el-input> -->
                <el-cascader v-model='item.belongBusiness' :options="industryOptions" placeholder="请选择" class="input-name"
                  :props="{ expandTrigger: 'hover', label: 'label', value: 'value', checkStrictly: true }">
                </el-cascader>
              </el-form-item>

              <el-form-item class="form-item form-item-company">
                <span class="common-span">{{ item.analysisResults }}</span>
              </el-form-item>
              <el-form-item class="form-item form-item-anchorRemark">
                <el-input clearable v-model="item.anchorRemark" placeholder="请输入" class="input-name"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="text" :disabled="formObj.infoList.length <= 1" @click="removeDomain(ind)">删除</el-button>
                <el-button type="text" :disabled="item.address.trim().length === 0" @click="onAnalysis(item, ind)"
                  style="margin-left: 8px">解析</el-button>
              </el-form-item>
            </section>
          </li>
        </ul>
      </section>
    </el-form>
  </el-dialog>
</template>

<script>
import { uid } from '@/utils'
import { isEmpty, cloneDeep, omit } from 'lodash'
import { mapGetters } from 'vuex'
import { addressStandardize, addAnchor } from '@/api/grid/anchor.js'
import { clientTypeOptions, custIdTypeOptions, addressTypeOptions, personAddressType, otherAddressType } from './../constant-info'
import { getIndustryTree } from '@/api/system/listByRetailKeywords.js'
const initMap = {
  custType: '',
  anchorName: '',
  custIdType: '',
  legalId: '',
  addressName: '',
  belongBusiness: '',
  analysisResults: '',
  address: '',
  anchorRemark: '',
  addressTypeOptions: []
}

export default {
  components: {},
  props: {
    custType: {
      type: String,
      default: ''
    }
  },
  computed: {
    uniscid() {
      return this.$route?.params?.uniscid
    },
    idDisabled() {
      return this.formObj.infoList?.some((ot) => ot.isEdit)
    }
  },
  watch: {
    visible(val) {
      val && this.getInitData()
    }
  },
  mounted() {
    this.initIndustryTree()
  },
  data() {
    return {
      clientTypeOptions,
      custIdTypeOptions,
      addressTypeOptions,
      removeIconStatus: false,
      formObjRules: {},
      btnLoading: false,
      visible: false,
      loading: false,
      industryOptions: [],
      formObj: {
        infoList: [cloneDeep(initMap)]
      },
      listArr: [],
      relationArr: [],
      valueMap: {
        0: { custIdType: '二代身份证', addressTypeOptions: personAddressType },
        1: { custIdType: '营业执照', addressTypeOptions: otherAddressType },
        2: { custIdType: '营业执照', addressTypeOptions: otherAddressType }
      }
    }
  },
  methods: {
    initIndustryTree() {
      getIndustryTree().then(res => {

        this.industryOptions = res.data.map(item => {
          return {
            value: item.name,
            label: item.name,
            children: item.industryTrees
          }
        })
        this.industryOptions.forEach(item => {
          item.children.forEach(el => {
            el.value = el.name
            el.label = el.name
          })
        })
      })
    },
    onCustTypeChange(val, ind) {
      this.formObj.infoList[ind].custIdType = ''
      this.formObj.infoList[ind].addressName = ''
      this.formObj.infoList[ind].addressTypeOptions = []
      if (!val) {
        return
      }
      this.formObj.infoList[ind].custIdType = this.valueMap[val].custIdType
      this.formObj.infoList[ind].addressTypeOptions = this.valueMap[val].addressTypeOptions
    },
    async onAnalysis(row, ind) {
      const res = await addressStandardize({
        address: row.address
      })
      if (res.code === 200 && res.data.status === 0) {
        const obj = res.data
        this.formObj.infoList[ind].analysisResults = `${obj.province}${obj.city}${obj.county}${obj.town}/${obj.village}`
      } else {
        this.formObj.infoList[ind].analysisResults = ''
        this.$message.error(res.data.msg || '解析失败')
      }
    },
    async getInitData() {
      this.formObj.infoList = this.formObj.infoList.map((og) => ({
        ...og,
        custType: this.custType,
        addressTypeOptions: this.valueMap[this.custType].addressTypeOptions,
        custIdType: this.valueMap[this.custType].custIdType
      }))
    },
    getArr(obj) {
      return Object.entries(obj).map((item) => {
        return {
          label: item[1],
          value: item[0]
        }
      })
    },
    onClose() {
      this.visible = false
      this.resetForm()
      setTimeout(() => {
        this.clearValidate()
      }, 0)
    },
    onOpen() {
      this.visible = true
    },
    onSubmit() {
      this.$refs.formObj.validate((valid) => {
        if (valid) {
          this.doAddOperation()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async doAddOperation() {
      try {
        this.btnLoading = true

        let resultArr = this.formObj.infoList.map((ot) => ({
          ...omit(ot, ['addressTypeOptions', 'analysisResults'])
        }))
        resultArr.forEach(item => {
          item.belongBusiness = item.belongBusiness ? item.belongBusiness[item.belongBusiness.length - 1] : ''
        })

        console.log(resultArr)
        const res = await addAnchor(resultArr)
        console.log(res, '-----')
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.onClose()
          this.$emit('refreshPage')
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.btnLoading = false
      }
    },
    resetForm() {
      this.formObj.infoList = [cloneDeep(initMap)]
    },
    clearValidate() {
      this.$refs.formObj.clearValidate()
    },
    addDomain(tag) {
      const newItems = {
        currentDate: '',
        key: uid(),
        isEdit: false,
        entname: this.formObj.infoList[0].entname,
        uniscid: this.formObj.infoList[0].uniscid,
        relaname: '',
        relatype: '',
        relation: ''
      }
      this.formObj.infoList.splice(tag + 1, 0, newItems)
    },
    removeDomain(index) {
      console.log(index)
      this.formObj.infoList.splice(index, 1)
    },
    hasEmptyProperty(obj) {
      for (const key in obj) {
        if (obj[key] === '') {
          return true
        }
      }
      return false
    },
    findEmptyIndexes(arr) {
      const emptyIndexs = []
      for (let i = 0; i < arr.length; i++) {
        if (this.hasEmptyProperty(arr[i])) {
          emptyIndexs.push(i + 1)
        }
      }
      return emptyIndexs
    },
    onEdit(tag) {
      this.formObj.infoList[tag].isEdit = true
    },
    onSave(tag) {
      this.clearValidate()
      this.formObj.infoList[tag].isEdit = false
      console.log(this.formObj.infoList, 'this.formObj.infoListthis.formObj.infoListthis.formObj.infoList')
    },
    onAdd() {
      this.formObj.infoList.push(
        cloneDeep({
          ...initMap,
          custType: this.custType,
          addressTypeOptions: this.valueMap[this.custType].addressTypeOptions,
          custIdType: this.valueMap[this.custType].custIdType
        })
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item-company {
  width: 10% !important;
}

.add-btn {}

.form-item-currentDate {
  width: 15% !important;
}

.form-item-relaname {
  width: 40% !important;
}

.form-item-relatype {
  width: 15% !important;
}

.el-icon-edit,
.el-icon-check {
  font-size: 24px;
  margin-right: 4px;
  cursor: pointer;
}

.common-span {
  display: inline-block;
  width: 100%;
}

.title-main {
  position: relative;
  color: rgba(0, 0, 0, 0.9);
  line-height: 22px;
  font-weight: bold;
  font-size: 18px;
  padding-left: 12px;
  margin-bottom: 20px;

  &::before {
    position: absolute;
    top: 50%;
    transform: translatey(-50%);
    left: 0;
    content: '';
    width: 4px;
    background-color: #0052d9;
    height: 18px;
  }
}

::v-deep .el-table__body-wrapper {
  max-height: 60vh;
  overflow-y: auto;
}

::v-deep .el-table {
  min-height: 56vh;
}

.list-header {
  clear: both;

  >p {
    font-size: 0;
    margin-bottom: 8px;
    display: flex;
    align-items: center;

    >span {
      font-size: 14px;
      color: #212121;
      display: inline-block;
      letter-spacing: normal;
      word-spacing: normal;
      width: 10%;
      margin-right: 12px;
    }
  }

  ul {
    height: 50vh;
    overflow-y: auto;
    margin: 0;
    list-style: none;
    padding: 0;

    .form-vl {
      display: flex;
      align-items: center;

      ::v-deep .el-form-item {
        margin-right: 12px;
        width: 10%;

        &.is-error .el-form-item__content {
          width: 62%;
        }
      }
    }

    .el-icon-remove-outline,
    .el-icon-circle-plus-outline {
      font-size: 24px;
      cursor: pointer;
    }

    .disabeld-icon {
      color: #dcdfe6;
      cursor: not-allowed;
      pointer-events: none;
    }
  }
}

.dialog-footer {
  text-align: right;
}

.header-operate {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
}
</style>

<style lang="scss">
.add-modal-wrap {
  .el-dialog__body {
    max-height: 90vh;
    overflow-y: auto;
  }
}
</style>