<template>
  <div class="main">
    <div class="main_top">
      <div class="maintop_left">企业建档</div>
      <div class="maintop_right">
        <el-button @click="handleFirmlClose">取消</el-button>
        <el-button type="primary" @click="handleFirmCommit" class="commit_btn">确定</el-button>
      </div>
    </div>
    <el-form ref="addFirmForm" :model="addFirmForm" label-width="140px" :rules="firmRules" class="addFirmForm">
      <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="addFirmForm.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="addFirmForm.custIdc" @blur="initInfoByCustIdc(addFirmForm.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="addFirmForm.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="addFirmForm.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="addFirmForm.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="addFirmForm.custPhone" maxlength="11"></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="addFirmForm.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="addFirmForm.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="addFirmForm.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="addFirmForm.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='addFirmForm.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="addFirmForm.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='addFirmForm.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="addFirmForm.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="custCapital" label="注册资本">
              <el-input v-model="addFirmForm.custCapital" 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='addFirmForm.industry' :options="industryOptions"
                :props="{ expandTrigger: 'hover', label: 'label', value: 'value', checkStrictly: true }">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="tel" label="企业电话">
              <el-input v-model="addFirmForm.tel" maxlength="11"></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="addFirmForm.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="firmRules.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='addFirmForm.belongBranchId' :options="departOptions"
                :props="{ expandTrigger: 'hover', label: 'label', value: 'id', checkStrictly: true }"
                @change="changeBranchName(addFirmForm.belongBranchId)">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item prop="firmUserSelect" label="客户经理">
              <el-select v-model="addFirmForm.firmUserSelect" @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 {

      addFirmForm: {
        custIdc: '',
        lpName: '',
        custGender: '',
        birthday: '',
        custAge: '',
        custPhone: '',
        registerLocation: '',
        registerLocationNum: '',
        custLocation: '',
        custLocationNum: '',
        socialCreditCode: '',
        custName: '',
        businessScope: '',
        status: '',
        custCapital: '',
        industry: '',
        tel: '',

        belongUserId: '',
        belongBranchId: '',
        belongBranchName: '',
        firmUserSelect: '',
        tableData: []
      },
      firmRules: {
        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.addFirmForm.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.addFirmForm.custGender = gender
      this.addFirmForm.birthday = csDate
      this.addFirmForm.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.addFirmForm.firmUserSelect = ''
      this.userList = []
      this.userId = value ? value[value.length - 1] : this.addFirmForm.belongBranchId
    },
    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.addFirmForm.tableData.push({
        relatePerson: '',
        relateCustIdc: '',
        isEdit: true
      })
    },
    handleClickSave(item) {
      item.isEdit = false
    },
    handleClickEdit(item) {
      item.isEdit = true
    },
    handleClickDelete(item, index) {
      this.addFirmForm.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('&')
    },
    handleFirmlClose() {
      this.$refs.addFirmForm.resetFields()
      this.$router.push({ path: '/customer/filingHome', query: { selectType: '2' } })
    },
    handleFirmCommit() {
      //户籍地址
      console.log(this.addFirmForm.tableData, 'addFirmForm.tableData')
      if (this.addFirmForm.relatePerson == this.addFirmForm.lpName) {
        Message.warning('关联人不能为本人')
        return
      }
      let registerLocationArr = this.addFirmForm.registerLocation ? this.addFirmForm.registerLocation.map(item => { return item.label }) : []
      let registerLocationStr = registerLocationArr.join(' ').replace(/\s/g, '')
      //住宅地址
      let custLocationArr = this.addFirmForm.custLocation ? this.addFirmForm.custLocation.map(item => { return item.label }) : []
      let custLocationStr = custLocationArr.join(' ').replace(/\s/g, '')
      this.$refs.addFirmForm.validate((valid) => {
        if (valid) {
          const infoParams = {
            custType: '2',
            custIdc: this.addFirmForm.custIdc,
            lpName: this.addFirmForm.lpName,
            custGender: this.addFirmForm.custGender,
            birthday: this.addFirmForm.birthday,
            custAge: this.addFirmForm.custAge,
            custPhone: this.addFirmForm.custPhone,
            registerLocation: `${registerLocationStr} ${this.addFirmForm.registerLocationNum}`,
            custLocation: `${custLocationStr} ${this.addFirmForm.custLocationNum}`,
            socialCreditCode: this.addFirmForm.socialCreditCode,
            custName: this.addFirmForm.custName,
            businessScope: this.addFirmForm.businessScope,
            status: this.addFirmForm.status,
            custCapital: this.addFirmForm.custCapital,
            industry: this.addFirmForm.industry ? this.addFirmForm.industry[this.addFirmForm.industry.length - 1] : '',
            tel: this.addFirmForm.tel,
            belongBranchId: this.addFirmForm.belongBranchId[this.addFirmForm.belongBranchId.length - 1],
            belongBranchName: this.addFirmForm.belongBranchName,
            belongUserId: this.addFirmForm.firmUserSelect.value,
            belongUserName: this.addFirmForm.firmUserSelect.label,

          }
          const params = {
              custInfoRecord: infoParams,
              familyMembersRecords: [],
              recordRelates: this.addFirmForm.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: '2' } })
            }
          })
        } 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%
}

.commit_btn {
  margin-left: 30px;
}

.addFirmForm {
  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;
  }
}

.glrxx {

}

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