<template>
  <div class="main">
    <div class="main_top">
      <div class="maintop_left">个人建档</div>
      <div class="maintop_right">
        <el-button @click="handleAddPersonClose">取消</el-button>
        <el-button type="primary" @click="handleAddPersonCommit" class="commit_btn">确定</el-button>
      </div>
    </div>
    <el-form ref="addPersonForm" :model="addPersonForm" label-width="140px" :rules="personRules" class="addPersonForm">
      <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="addPersonForm.custName" 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="addPersonForm.custIdc" @blur="initInfoByCustIdc(addPersonForm.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="addPersonForm.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="addPersonForm.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="addPersonForm.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="addPersonForm.custPhone" maxlength="11"></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='addPersonForm.registerLocation' :props="regAddress">
                <template slot-scope="{node,data}">
                  <span>{{ data.label }}</span>
                </template>
              </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="addPersonForm.registerLocationNum" maxlength="10" 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="jobLocation" label="单位地址">
              <el-cascader v-model='addPersonForm.jobLocation' :props="regAddress">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="5" class="mphdz">
            <el-form-item prop="jobLocationNum" label-width="0">
              <el-input v-model="addPersonForm.jobLocationNum" maxlength="10" 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="custLocation" label="住宅地址">
              <el-cascader v-model='addPersonForm.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="addPersonForm.custLocationNum" maxlength="10" placeholder="请输入门牌号,非必填"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="isMarried" label="婚姻状况">
              <el-select v-model="addPersonForm.isMarried">
                <el-option v-for="(item, index) in isMarriedList" :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="custEdu" label="学历">
              <el-select v-model="addPersonForm.custEdu">
                <el-option v-for="(item, index) in custEduList" :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="custSalary" label="年收入">
              <el-input v-model.number="addPersonForm.custSalary" maxlength="18"></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='addPersonForm.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">
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="relateMerchant" label="关联商户">
              <el-input v-model="addPersonForm.relateMerchant" maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="relateMerchantCode" label="关联商户统信码">
              <el-input v-model="addPersonForm.relateMerchantCode" maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="relateBusiness" label="关联企业">
              <el-input v-model="addPersonForm.relateBusiness" maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="relateBusinessCode" label="关联企业统信码">
              <el-input v-model="addPersonForm.relateBusinessCode" maxlength="18"></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">
        <div class="glrxx">
          <el-row :gutter="24">
            <el-col :span="15">
              <el-table :data="addPersonForm.tableData" style="width: 100%;">
                <el-table-column prop="fmyName" label="家庭成员">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input v-model="scope.row.fmyName" maxlength="18" v-if="scope.row.isEdit"></el-input>
                      <div v-if="!scope.row.isEdit">{{ scope.row.fmyName }}</div>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="fmyRln" label="与本人关系">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-select v-model="scope.row.fmyRln" v-if="scope.row.isEdit">
                        <el-option v-for="(item, index) in FmyRlnList" :key="index" :label="item.label"
                          :value="item.value"></el-option>
                      </el-select>
                      <div v-if="!scope.row.isEdit">{{ scope.row.fmyRln }}</div>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="fmyCustIdc" label="身份证号" >
                  <template slot-scope="scope">
                    <el-form-item label-width="0" :prop="`tableData.${scope.$index}.fmyCustIdc`"
                      :rules="personRules.fmyCustIdc">
                      <el-input v-model="scope.row.fmyCustIdc" maxlength="18" v-if="scope.row.isEdit"></el-input>
                      <div v-if="!scope.row.isEdit">{{ scope.row.fmyCustIdc }}</div>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="tel" label="手机号">
                  <template slot-scope="scope">
                    <el-form-item label-width="0" :prop="`tableData.${scope.$index}.tel`" :rules="personRules.tel">
                      <el-input v-model="scope.row.tel" maxlength="18" v-if="scope.row.isEdit"></el-input>
                      <div v-if="!scope.row.isEdit">{{ scope.row.tel }}</div>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="belongBusi" label="成员行业">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-cascader v-model='scope.row.belongBusi' :options="industryOptions" v-if="scope.row.isEdit"
                        :props="{ expandTrigger: 'hover', label: 'label', value: 'value', checkStrictly: true }"
                        :show-all-levels="false">
                      </el-cascader>
                      <div v-if="!scope.row.isEdit">{{ initIndustryBusiStr(scope.row.belongBusi) }}</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='addPersonForm.belongBranchId' :options="departOptions"
                :props="{ expandTrigger: 'hover', label: 'label', value: 'id', checkStrictly: true }"
                @change="changeBranchName(addPersonForm.belongBranchId)">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="perUserSelect" label="客户经理">
              <el-select v-model="addPersonForm.perUserSelect" @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, getInfoByCustIdc } from '@/api/system/listByRetailKeywords.js'
import { custEduList } from '../../charts/360charts/custEdu'
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 fmyTelPhone = (rule, value, callback) => {
      if (!value?.trim()) {
        callback()
      }
      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 {
      custEduList,
      addPersonForm: {
        custIdc: '',
        custName: '',
        custGender: '',
        birthday: '',
        custAge: '',
        custPhone: '',
        registerLocation: '',
        registerLocationNum: '',
        jobLocation: '',
        jobLocationNum: '',
        custLocation: '',
        custLocationNum: '',
        isMarried: '',
        custEdu: '',
        custSalary: '',
        industry: '',
        relateMerchant: '',
        relateMerchantCode: '',
        relateBusiness: '',
        relateBusinessCode: '',
        belongUserId: '',
        belongBranchId: '',
        perUserSelect: '',
        tableData: []
      },
      adressOptions: [],
      isMarriedList: [
        {
          label: '未婚',
          value: '未婚'
        },
        {
          label: '已婚',
          value: '已婚'
        },
        {
          label: '离异',
          value: '离异'
        }
      ],
      genderList: [
        { label: '男', value: '男' },
        { label: '女', value: '女' },
      ],
      FmyRlnList: [
        { label: '父亲', value: '父亲' },
        { label: '母亲', value: '母亲' },
        { label: '祖父', value: '祖父' },
        { label: '祖母', value: '祖母' },
        { label: '儿子', value: '儿子' },
        { label: '女儿', value: '女儿' },
        { label: '孙子', value: '孙子' },
        { label: '孙女', value: '孙女' },
        { label: '兄弟', value: '兄弟' },
        { label: '表兄弟', value: '表兄弟' },
        { label: '堂兄弟', value: '堂兄弟' },
        { label: '姐妹', value: '姐妹' },
        { label: '表姐妹', value: '表姐妹' },
        { label: '堂姐妹', value: '堂姐妹' },
        { label: '妻子', value: '妻子' },
        { label: '丈夫', value: '丈夫' },
      ],
      industryOptions: [],
      userList: [],
      departOptions: [],
      personRules: {
        custName: [{ required: true, message: '请输入', trigger: 'blur' }],
        custIdc: [{ required: true, validator: validateCustIdc, trigger: 'blur' }],
        custPhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        fmyCustIdc: [{ required: true, validator: validateCustIdc, trigger: 'blur' }],
        tel: [{ required: true, validator: validatePhone, 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)
        }
      }
    }
  },
  created() {
    // this.initAddressTree()
    this.initIndustryTree()
    this.getUser()
  },
  mounted() {
    this.userId = this.addPersonForm.belongBranchId
  },
  methods: {
    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.addPersonForm.custGender = gender
      this.addPersonForm.birthday = csDate
      this.addPersonForm.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
    //   })
    // },
    initIndustryBusiStr(data) {
      for (let i = 0; i < this.industryOptions.length; i++) {
        if (this.industryOptions[i].value == data[data.length - 1]) {

          return this.industryOptions[i].label
        } else {
          for (let j = 0; j < this.industryOptions[i].children.length; j++) {

            if (this.industryOptions[i].children[j].value == data[data.length - 1]) {

              return this.industryOptions[i].children[j].label
            }
          }
        }
      }
    },
    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.addPersonForm.perUserSelect = ''
      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.addPersonForm.tableData.push({
        fmyName:'',
        fmyRln:'',
        fmyCustIdc:'',
        tel:'',
        belongBusi:'',
        isEdit: true
      })
    },
    handleClickSave(item) {
      item.isEdit = false
    },
    handleClickEdit(item) {
      item.isEdit = true
    },
    handleClickDelete(item, index) {
      this.addPersonForm.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('&')
    },
    handleAddPersonClose() {
      this.$refs.addPersonForm.resetFields()
      this.$router.push({ path: '/customer/filingHome', query: { selectType: '0' } })
    },
    handleAddPersonCommit() {

      //户籍地址
      let registerLocationArr = this.addPersonForm.registerLocation ? this.addPersonForm.registerLocation.map(item => { return item.label }) : []
      let registerLocationStr = registerLocationArr.join(' ').replace(/\s/g, '')
      //单位地址
      let jobLocationArr = this.addPersonForm.jobLocation ? this.addPersonForm.jobLocation.map(item => { return item.label }) : []
      let jobLocationStr = jobLocationArr.join(' ').replace(/\s/g, '')
      //住宅地址
      let custLocationArr = this.addPersonForm.custLocation ? this.addPersonForm.custLocation.map(item => { return item.label }) : []
      let custLocationStr = custLocationArr.join(' ').replace(/\s/g, '')

      this.$refs.addPersonForm.validate((valid) => {

        if (valid) {
          const infoParams = {
            custType: '0',
            custIdc: this.addPersonForm.custIdc,
            custName: this.addPersonForm.custName,
            custGender: this.addPersonForm.custGender,
            birthday: this.addPersonForm.birthday,
            custAge: this.addPersonForm.custAge,
            custPhone: this.addPersonForm.custPhone,
            registerLocation: `${registerLocationStr} ${this.addPersonForm.registerLocationNum}`,
            jobLocation: `${jobLocationStr} ${this.addPersonForm.jobLocationNum}`,
            custLocation: `${custLocationStr} ${this.addPersonForm.custLocationNum}`,
            isMarried: this.addPersonForm.isMarried,
            custEdu: this.addPersonForm.custEdu,
            custSalary: this.addPersonForm.custSalary,
            industry: this.addPersonForm.industry[this.addPersonForm.industry.length - 1],

            belongUserId: this.addPersonForm.perUserSelect.value,
            belongBranchId: this.addPersonForm.belongBranchId[this.addPersonForm.belongBranchId.length - 1],
            belongUserName: this.addPersonForm.perUserSelect.label
          }
          let arr = this.addPersonForm.tableData.map(item => {
            return {
              fmyCustIdc: item.fmyCustIdc,
              fmyName: item.fmyName,
              fmyRln: item.fmyRln,
              tel: item.tel,
              belongBusi: item.belongBusi
            }
          })
          arr.forEach(item => {
            item.belongBusi = item.belongBusi ? item.belongBusi[item.belongBusi.length - 1] : ''
          })
          let recordRelate = {
            relateMerchant: this.addPersonForm.relateMerchant,
            relateMerchantCode: this.addPersonForm.relateMerchantCode,
            relateBusiness: this.addPersonForm.relateBusiness,
            relateBusinessCode: this.addPersonForm.relateBusinessCode,
          }
          const params = {
            custInfoRecord: infoParams,
            familyMembersRecords: arr,
            recordRelates: [recordRelate]
          }
          addRecord(params).then(res => {
            if (res.code == 200) {
              Message.success(res.msg)
              this.$router.push({ path: '/filing/filingHome', query: { selectType: '0' } })

            }
          })
        } 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;
}

.addPersonForm {
  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>