<template>
  <div class="main">
    <div class="main_top">
      <div class="maintop_left">商户建档</div>
      <div class="maintop_right">
        <el-button @click="handleCommercialClose">取消</el-button>
        <el-button type="primary" @click="handleCommercialCommit" class="commit_btn">确定</el-button>
      </div>
    </div>
    <el-form ref="addCommercialForm" :model="addCommercialForm" label-width="140px" :rules="commercialRules"
      class="addCommercialForm">
      <div class="title_box">
        <div class="title_blue"></div>
        <span>法人信息</span>
      </div>
      <div class="infoBox">
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="lpName" label="经营者姓名">
              <el-input v-model="addCommercialForm.lpName" maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="custIdc" label="身份证号">
              <el-input v-model="addCommercialForm.custIdc" @blur="initInfoByCustIdc(addCommercialForm.custIdc)"
                maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="custGender" label="性别">
              <el-select v-model="addCommercialForm.custGender">
                <el-option v-for="(item, index) in genderList" :key="index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="birthday" label="出生日期">
              <el-date-picker v-model="addCommercialForm.birthday" type="date" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="custAge" label="年龄">
              <el-input v-model="addCommercialForm.custAge" maxlength="3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="custPhone" label="经营手机号">
              <el-input v-model="addCommercialForm.custPhone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="title_box">
        <div class="title_blue"></div>
        <span>商户信息</span>
      </div>
      <div class="infoBox">
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="custName" label="商户名称">
              <el-input v-model="addCommercialForm.custName" maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="socialCreditCode" label="统信码">
              <el-input v-model="addCommercialForm.socialCreditCode" maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="status" label="经营状态">
              <el-select v-model="addCommercialForm.status">
                <el-option v-for="(item, index) in statusList" :key="index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="businessScope" label="经营范围">
              <el-input v-model="addCommercialForm.businessScope" maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="dz_row">
          <el-col :span="10">
            <el-form-item prop="custLocation" label="经营地址">
              <el-cascader v-model='addCommercialForm.custLocation' :props="regAddress">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="5" class="mphdz">
            <el-form-item prop="custLocationNum" label-width="0">
              <el-input v-model="addCommercialForm.custLocationNum" maxlength="18" placeholder="请输入门牌号,非必填"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="dz_row">
          <el-col :span="10">
            <el-form-item prop="registerLocation" label="注册地址">
              <el-cascader v-model='addCommercialForm.registerLocation' :props="regAddress">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="5" class="mphdz">
            <el-form-item prop="registerLocationNum" label-width="0">
              <el-input v-model="addCommercialForm.registerLocationNum" maxlength="18"
                placeholder="请输入门牌号,非必填"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="industry" label="行业名称">
              <el-cascader v-model='addCommercialForm.industry' :options="industryOptions"
                :props="{ expandTrigger: 'hover', label: 'label', value: 'value', checkStrictly: true }">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="title_box">
        <div class="title_blue"></div>
        <span>关联人信息</span>
      </div>
      <div class="infoBox">
        <div class="glrxx">
          <el-row :gutter="24">
            <el-col :span="15">
              <el-table :data="addCommercialForm.tableData" style="width: 100%;">
                <el-table-column prop="relatePerson" label="关联人">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input v-model="scope.row.relatePerson" maxlength="18" v-if="scope.row.isEdit"></el-input>
                      <div v-if="!scope.row.isEdit">{{ scope.row.relatePerson }}</div>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="relateCustIdc" label="关联人身份证号" >
                  <template slot-scope="scope">
                    <el-form-item label-width="0" :prop="`tableData.${scope.$index}.relateCustIdc`" :rules="commercialRules.relateCustIdc">
                      <el-input v-model="scope.row.relateCustIdc" maxlength="18" v-if="scope.row.isEdit"></el-input>
                      <div v-if="!scope.row.isEdit">{{ scope.row.relateCustIdc }}</div>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" v-if="!scope.row.isEdit" @click="handleClickEdit(scope.row)">编辑</el-button>
                    <el-button type="text" v-if="scope.row.isEdit" @click="handleClickSave(scope.row)">保存</el-button>
                    <el-button type="text" v-if="!scope.row.isEdit"
                      @click="handleClickDelete(scope.row, scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="15">
              <div class="addGlr" @click="handleAddGlr"><i class="el-icon-circle-plus-outline addIcon"></i>添加关联人</div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="title_box">
        <div class="title_blue"></div>
        <span>其他信息</span>
      </div>
      <div class="infoBox">
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="belongBranchId" label="客户经理归属机构">
              <el-cascader v-model='addCommercialForm.belongBranchId' :options="departOptions"
                :props="{ expandTrigger: 'hover', label: 'label', value: 'id', checkStrictly: true }"
                @change="changeBranchName(addCommercialForm.belongBranchId)">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="comUserSelect" label="客户经理">
              <el-select v-model="addCommercialForm.comUserSelect" @focus="selectUser">
                <el-option v-for="(item, index) in userList" :key="index" :label="item.label" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>
<script>
import { getUserProfile } from '@/api/grid/anchor.js'
import { Message } from 'element-ui'
import { getDeptTree, getDeptUserTree, getAddressTreeAdd, deptTreeByManager } from "@/api/grid/address/tree.js";
import { getIndustryTree, addRecord, getRegStatus } from '@/api/system/listByRetailKeywords.js'
export default {
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!value?.trim()) {
        return callback(new Error('请输入手机号'))
      }
      const regExp = /^1(3|4|5|6|7|8|9)[0-9]{9}$/
      if (!regExp.test(value)) {
        this.showCode = false
        this.canClick = false
        callback(new Error('请输入正确的手机号'))
      } else {
        this.canClick = true
        callback()
      }
    }
    var validateCustIdc = (rule, value, callback) => {
      if (!value?.trim()) {
        return callback(new Error('请输入身份证号码'))
      }
      const regex = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      if (!regex.test(value)) {
        callback(new Error('请输入正确的身份证号码'))
      } else {
        callback()
      }
    }
    return {
      addCommercialForm: {
        custIdc: '',
        lpName: '',
        custGender: '',
        birthday: '',
        custAge: '',
        custPhone: '',
        registerLocation: '',
        registerLocationNum: '',
        custLocation: '',
        custLocationNum: '',
        socialCreditCode: '',
        custName: '',
        businessScope: '',
        status: '',
        industry: '',
        belongUserId: '',
        belongBranchId: '',
        belongBranchName: '',
        comUserSelect: '',
        tableData: []
      },
      commercialRules: {
        custIdc: [{ required: true, validator: validateCustIdc, trigger: 'blur' }],
        custPhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        custName: [{ required: true, message: '请输入', trigger: 'blur' }],
        socialCreditCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        relateCustIdc: [{ required: true, validator: validateCustIdc, trigger: 'blur' }],
        belongBranchId:[{ required: true, message: '请选择', trigger: 'change' }],
      },
      regAddress: {
        lazy: true,
        lazyLoad(node, resolve) {
          setTimeout(() => {
            const nodes = []
            let query = {
              level: node.level + 1,
              code: node.level == 0 ? '33' : node.value.value,
            }

            getAddressTreeAdd(query).then(res => {
              res.data.map(item => {
                let obj = {
                  value: item,
                  label: item.label,
                  leaf: item.level >= 5
                }
                nodes.push(obj)
              })

              resolve(nodes)
            })
          }, 500)
        }
      },
      adressOptions: [],
      isMarriedList: [
        {
          label: '未婚',
          value: '未婚'
        },
        {
          label: '已婚',
          value: '已婚'
        },
        {
          label: '离异',
          value: '离异'
        }
      ],
      genderList: [
        { label: '男', value: '男' },
        { label: '女', value: '女' },
      ],
      industryOptions: [],
      userList: [],
      departOptions: [],
      statusList: [

      ],
    }
  },
  created() {
    // this.initAddressTree()
    this.initRegStatus()
    this.initIndustryTree()
    this.getUser()
  },
   mounted() {
    this.userId = this.addCommercialForm.belongBranchId
  },
  methods: {
    initRegStatus() {
      getRegStatus().then(res => {
        if (res.code == 200) {
          this.statusList = res.data.map(item => {
            return {
              label: item.dictLabel,
              value: item.dictValue
            }
          })
        }
      })
    },
    initInfoByCustIdc(data) {
      //性别
      let sexCode = data.charAt(16)
      let gender = parseInt(sexCode, 10) % 2 === 0 ? '女' : '男'
      //年龄
      let today = new Date()
      let birthDate = new Date(data.substring(6, 10))
      let age = today.getFullYear() - birthDate.getFullYear()
      //出生日期
      let year = data.substring(6, 10)
      let mounth = data.substring(10, 12)
      let day = data.substring(12, 14)
      let csDate = `${year}-${mounth}-${day}`
      this.addCommercialForm.custGender = gender
      this.addCommercialForm.birthday = csDate
      this.addCommercialForm.custAge = age

    },
    initIndustryTree() {
      getIndustryTree().then(res => {
        this.industryOptions = res.data.map(item => {
          return {
            value: item.code,
            label: item.name,
            children: item.industryTrees
          }
        })
        this.industryOptions.forEach(item => {
          item.children.forEach(el => {
            el.value = el.code
            el.label = el.name
          })
        })
      })
    },
    // initAddressTree() {
    //   getAddressTree({ code: '33' }).then(res => {
    //     this.adressOptions = res.data
    //   })
    // },
    getUser() {
      getUserProfile().then(res => {
        this.deptId = res.data.dept.deptId
        this.deptName = res.data.dept.deptName
        let roleName = res.data.roleName
        if (roleName == '普通客户经理') {
          this.initdeptTreeByManager()
        } else {
          this.initDeptTree()
        }
      })
    },
    initDeptTree() {
      getDeptTree(this.deptId).then(res => {

        this.departOptions = res.data
      })
    },
    initdeptTreeByManager() {
      deptTreeByManager(this.deptId).then(res => {
        this.departOptions = res.data
      })
    },
    changeBranchName(value) {
      this.addCommercialForm.comUserSelect = ''
      this.userList = []
      this.userId = value ? value[value.length - 1] : ''
    },
    selectUser(value) {

      this.initGetDeptTree()
    },
    initGetDeptTree() {

      const params = {
        deptid: this.userId
      }
      getDeptUserTree(params).then(res => {
        if (res.length > 0) {
          this.userList = res.map(item => {
            return {
              value: item.userName,
              label: `${item.nickName}-${item.userName}`,
            }
          })
        } else {
          Message.warning('该机构下无客户经理')
        }

      })
    },
    handleAddGlr() {
      this.addCommercialForm.tableData.push({
        relatePerson: '',
        relateCustIdc: '',
        isEdit: true
      })
    },
    handleClickSave(item) {
      item.isEdit = false
    },
    handleClickEdit(item) {
      item.isEdit = true
    },
    handleClickDelete(item, index) {
      this.addCommercialForm.tableData.splice(index, 1)
    },
    formDataPamars(json) {
      const params = []
      for (const key in json) {
        const value = json[key]
        if (value && typeof value === 'object' && !Array.isArray(value)) {
          params.push(...Object.keys(value).map((k) => `${key}[${k}]=${encodeURIComponent(value[k])}`))
        } else if (Array.isArray(value)) {
          value.forEach((item) => {
            params.push(`${key}[]=${encodeURIComponent(item)}`)
          })
        } else {
          params.push(`${key}=${encodeURIComponent(value)}`)
        }
      }
      return params.join('&')
    },
    handleCommercialClose() {
      this.$refs.addCommercialForm.resetFields()
      this.$router.push({ path: '/customer/filingHome', query: { selectType: '1' } })
    },
    handleCommercialCommit() {
      if (this.addCommercialForm.relatePerson == this.addCommercialForm.lpName) {
        Message.warning('关联人不能为本人')
        return
      }
      //户籍地址
      let registerLocationArr = this.addCommercialForm.registerLocation ? this.addCommercialForm.registerLocation.map(item => { return item.label }) : []
      let registerLocationStr = registerLocationArr.join(' ').replace(/\s/g, '')
      //住宅地址
      let custLocationArr = this.addCommercialForm.custLocation ? this.addCommercialForm.custLocation.map(item => { return item.label }) : []
      let custLocationStr = custLocationArr.join(' ').replace(/\s/g, '')
      this.$refs.addCommercialForm.validate((valid) => {
        if (valid) {
          const infoParams = {
            custType: '1',
            custIdc: this.addCommercialForm.custIdc,
            lpName: this.addCommercialForm.lpName,
            custGender: this.addCommercialForm.custGender,
            birthday: this.addCommercialForm.birthday,
            custAge: this.addCommercialForm.custAge,
            custPhone: this.addCommercialForm.custPhone,
            registerLocation: `${registerLocationStr} ${this.addCommercialForm.registerLocationNum}`,
            custLocation: `${custLocationStr} ${this.addCommercialForm.custLocationNum}`,
            socialCreditCode: this.addCommercialForm.socialCreditCode,
            custName: this.addCommercialForm.custName,
            businessScope: this.addCommercialForm.businessScope,
            status: this.addCommercialForm.status,
            industry: this.addCommercialForm.industry ? this.addCommercialForm.industry[this.addCommercialForm.industry.length - 1] : '',
            belongBranchId: this.addCommercialForm.belongBranchId[this.addCommercialForm.belongBranchId.length - 1],
            belongBranchName: this.addCommercialForm.belongBranchName,
            belongUserId: this.addCommercialForm.comUserSelect.value,
            belongUserName: this.addCommercialForm.comUserSelect.label
          }
          const params = {
            custInfoRecord: infoParams,
            familyMembersRecords: [],
            recordRelates: this.addCommercialForm.tableData.map(item => {
              return {
                relateCustIdc: item.relateCustIdc,
                relatePerson: item.relatePerson
              }
            })

          }
          addRecord(params).then(res => {
            if (res.code == 200) {
              Message.success(res.msg)
              this.$router.push({ path: '/filing/filingHome', query: { selectType: '1' } })

            }
          })
        } else {
          return false
        }
      })

    },
  },
}
</script>
<style lang="scss" scoped>
.main {
  background-color: #ffffff;
}

::v-deep .el-select {
  width: 100%
}

::v-deep .el-input {
  width: 100%
}

::v-deep .el-cascader {
  width: 100%
}

.footer {
  margin: 30px 0;
  text-align: center;
}

.commit_btn {
  margin-left: 30px;
}

.addCommercialForm {
  padding: 20px 30px 10px 20px;
}

.main_top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-radius: 4px 4px 0px 0px;
  box-shadow: 0px 1px 0px 0px rgba(0, 0, 0, 0.09);
}

.maintop_left {
  font-size: 20px;
}

.title_box {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.title_blue {
  display: inline-block;
  width: 3px;
  height: 20px;
  background-color: rgb(22, 132, 252);
  margin-right: 10px;
}

.infoBox {
  margin-top: 30px;
  margin-left: 10%;
}

.dz_row {
  ::v-deep .el-col {
    padding-right: 0 !important;
  }
}

.mphdz {
  ::v-deep .el-input {
    width: 95% !important;
  }
}


.addGlr {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px 0;
  background-color: rgba(70, 130, 255, 0.1);
  color: rgba(70, 130, 255, 1);
  border: 1px solid rgba(70, 130, 255, 1);
  cursor: pointer;
}

.addIcon {
  font-size: 25px;
  margin-right: 10px;
}
</style>