<template>
  <ai-detail class="functionaryCreate">
    <ai-title slot="title" :title="detailTitle" isShowBottomBorder isShowBack @onBackClick="$router.push({})"/>
    <template #content>
      <el-form :model="form" ref="cadresForm" :rules="rules" label-width="160px" size="small">
        <ai-card title="基本信息">
          <template #content>
            <el-row type="flex" class="wrap">
              <el-form-item layout label-width="0">
                <el-form-item row label="姓名：" prop="name">
                  <el-row type="flex" align="middle">
                    <el-input placeholder="请输入姓名" v-model="form.name" clearable/>
                    <ai-person-select :instance="instance" @selectPerson="getInfoFromResident"/>
                  </el-row>
                </el-form-item>
                <el-form-item row label="身份证号：" prop="idNumber">
                  <el-input placeholder="请输入身份证号" clearable v-model="form.idNumber" :maxlength="18"
                            @change="handleIdNumberInfo"/>
                </el-form-item>
                <el-form-item row label="性别：">
                  <ai-select v-model="form.gender" :selectList="dict.getDict('sex')" disabled/>
                </el-form-item>
              </el-form-item>
              <el-form-item label="个人照片：">
                <ai-avatar :instance="instance" v-model="form.avatarUrl"/>
              </el-form-item>
              <el-form-item label="出生日期：">
                <el-date-picker placeholder="请选择..." disabled
                                value-format="yyyy-MM-dd HH:mm:ss"
                                :value="form.birthday" type="date"/>
              </el-form-item>
              <el-form-item label="年龄：">
                <el-input placeholder="请输入年龄" :value="$calcAge(form.idNumber)||null" disabled/>
              </el-form-item>
              <el-form-item label="联系方式：" prop="phone">
                <el-input v-model.number="form.phone" placeholder="请输入联系方式" :maxlength="11"/>
              </el-form-item>
              <el-form-item label="民族：">
                <ai-select v-model="form.nation" :selectList="dict.getDict('nation')"/>
              </el-form-item>
              <el-form-item label="文化程度：">
                <ai-select v-model="form.educationLevel" :selectList="dict.getDict('education_village_rc')"/>
              </el-form-item>
              <el-form-item label="政治面貌：" prop="politicalStatus">
                <ai-select v-model="form.politicalStatus" :selectList="dict.getDict('politicsStatus')"/>
              </el-form-item>
              <el-form-item label="入党时间：">
                <el-date-picker placeholder="选择日期"
                                value-format="yyyy-MM-dd 00:00:00"
                                format="yyyy-MM-dd"
                                v-model="form.membershipTime"
                                clearable
                                type="date"/>
              </el-form-item>
              <el-form-item label="参加工作时间：">
                <el-date-picker placeholder="选择日期"
                                value-format="yyyy-MM-dd 00:00:00"
                                format="yyyy-MM-dd"
                                v-model="form.jobTime"
                                type="date"/>
              </el-form-item>
              <el-form-item label="健康状况：" prop="healthCondition">
                <ai-select v-model="form.healthCondition" :selectList="dict.getDict('healthCondition')"/>
              </el-form-item>
              <el-form-item label="职称：">
                <el-input v-model="form.jobTitle" placeholder="请输入职称" clearable/>
              </el-form-item>
              <el-form-item row label="籍贯：" prop="areaId">
                <ai-area-select
                    @fullname="v=>form.areaName=v"
                    clearable
                    always-show
                    :instance="instance"
                    v-model="form.areaId" :areaLevel="3"/>
              </el-form-item>
              <el-form-item row label="现住址：" prop="currentAreaId">
                <ai-area-select
                    @fullname="v=>form.currentAreaName=v"
                    clearable
                    always-show
                    :instance="instance"
                    v-model="form.currentAreaId"/>
                <el-input placeholder="请输入详细地址" clearable v-model="form.currentAddress"/>
              </el-form-item>
            </el-row>
          </template>
        </ai-card>
        <ai-card title="学历信息">
          <template #right>
            <el-button type="text" icon="iconfont iconAdd" @click="dialog=true">添加学历信息</el-button>
          </template>
          <template #content>
            <el-table :data="form.educations" stripe border header-cell-class-name="table-header" align="center">
              <el-table-column
                  align="center"
                  prop="educationType"
                  label="学历类型"
                  width="119"
                  clearable
              >
                <template slot-scope="scope">
                  <span>{{ dict.getLabel("appVillageCadresEducationType", scope.row.educationType) || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="educationLevel" label="学历" width="100">
                <template slot-scope="scope">
                  <span>{{ dict.getLabel("education_village_rc", scope.row.educationalLevel) || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="graduatedSchool" label="毕业院校" width="200">
                <template slot-scope="scope">
                  <div>{{ scope.row.graduatedSchool || '-' }}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="learnProfession" label="专业" width="160">
                <template slot-scope="scope">
                  <span>{{ scope.row.learnProfession || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="graduationTime" label="毕业时间" width="100">
                <template slot-scope="scope">
                  <span>{{ (scope.row.graduationTime) ? (scope.row.graduationTime).substring(0, 10) : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="{row,$index}" v-if="$permissions('app_appvillagecadresnew_edit')">
                  <el-button type="text" @click="handleEditEducation(row,$index)">编辑</el-button>
                  <el-button type="text" @click="handleDelEducation($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </ai-card>
        <ai-card title="职务信息">
          <template #content>
            <el-row type="flex" class="wrap">
              <el-form-item row label="任职地区" prop="workAreaId">
                <ai-area-select clearable @fullname="v=>form.workAreaName=v" always-show :instance="instance"
                                v-model="form.workAreaId" :disabled-level="disabledLevel"/>
              </el-form-item>
              <el-form-item label="任职时间" prop="workTime">
                <el-date-picker placeholder="选择日期"
                                value-format="yyyy-MM-dd 00:00:00"
                                format="yyyy-MM-dd"
                                v-model="form.workTime"
                                type="date"/>
              </el-form-item>
              <el-form-item label="职务类别" prop="positionType">
                <ai-select v-model="form.positionType" :selectList="dict.getDict('cadrePositionType')"/>
              </el-form-item>
              <el-form-item label="是否镇街下派" prop="isSubordinate">
                <ai-select v-model="form.isSubordinate" :selectList="dict.getDict('yesOrNo')"/>
              </el-form-item>
              <el-form-item label="是否大学生村官" prop="isCollegeOfficer">
                <ai-select v-model="form.isCollegeOfficer" :selectList="dict.getDict('yesOrNo')"/>
              </el-form-item>
              <el-form-item label="是否村(居)委会委员" prop="isVillageMember">
                <ai-select v-model="form.isVillageMember" :selectList="dict.getDict('yesOrNo')"
                           @change="form.villageMemberPosition1=''"/>
              </el-form-item>
              <el-form-item label="村(居)委会委员职务" prop="villageMemberPosition1"
                            v-if="form.isVillageMember==1">
                <ai-select v-model="form.villageMemberPosition1"
                           :selectList="dict.getDict('appVillageMemberPosition1')"/>
              </el-form-item>
              <el-form-item label="是否支委委员" prop="isBranchMember">
                <ai-select v-model="form.isBranchMember" :selectList="dict.getDict('yesOrNo')"
                           @change="form.branchMemberPosition1=''"/>
              </el-form-item>
              <el-form-item label="支委委员职务" v-if="form.isBranchMember==1"
                            prop="branchMemberPosition1"
                            :rules="[{ required: true, message: '请选择支委委员职务', trigger: 'change' }]">
                <ai-select v-model="form.branchMemberPosition1" :selectList="dict.getDict('appBranchMemberPosition1')"/>
              </el-form-item>
              <el-form-item label="是否村(居)务监督委员会成员" prop="isVillageSupervision">
                <ai-select v-model="form.isVillageSupervision" :selectList="dict.getDict('yesOrNo')"
                           @change="form.villageSupervisionPosition1=''"/>
              </el-form-item>
              <el-form-item label="村(居)务监督委员会职务" v-if="form.isVillageSupervision==1"
                            :rules="[{ required: true, message: '请选择村(居)务监督委员会职务', trigger: 'change' }]"
                            prop="villageSupervisionPosition1">
                <ai-select v-model="form.villageSupervisionPosition1"
                           :selectList="dict.getDict('appVillageSupervisionPosition1')"/>
              </el-form-item>
              <el-form-item label="是否专职干部" prop="isFulltimeCadres">
                <ai-select v-model="form.isFulltimeCadres" :selectList="dict.getDict('yesOrNo')"
                           @change="form.fulltimeCadresPosition1='',form.fulltimeCadresTime=''"/>
              </el-form-item>
              <el-form-item label="专职干部职务" v-if="form.isFulltimeCadres==1"
                            prop="fulltimeCadresPosition1"
                            :rules="[{ required: true, message: '请选择专职干部职务', trigger: 'change' }]">
                <ai-select v-model="form.fulltimeCadresPosition1"
                           :selectList="dict.getDict('appFulltimeCadresPosition1')"/>
              </el-form-item>
              <el-form-item label="担任专职干部时间" v-if="form.isFulltimeCadres==1" prop="fulltimeCadresTime"
                            :rules="[{ required: true, message: '请选择担任专职干部时间', trigger: 'change' }]">
                <el-date-picker placeholder="选择日期"
                                value-format="yyyy-MM-dd 00:00:00"
                                format="yyyy-MM-dd"
                                v-model="form.fulltimeCadresTime"
                                type="date"/>
              </el-form-item>
              <el-form-item label="是否团支部书记" prop="isLeagueSecretary">
                <ai-select v-model="form.isLeagueSecretary" :selectList="dict.getDict('yesOrNo')"/>
              </el-form-item>
              <el-form-item label="是否妇联主席" prop="isWomenChairman">
                <ai-select v-model="form.isWomenChairman" :selectList="dict.getDict('yesOrNo')"/>
              </el-form-item>
              <el-form-item label="是否民兵连长" prop="isMilitiaCommander">
                <ai-select v-model="form.isMilitiaCommander" :selectList="dict.getDict('yesOrNo')"/>
              </el-form-item>
              <el-form-item label="是否村(居)民小组长" prop="isVillageLeader">
                <ai-select v-model="form.isVillageLeader" :selectList="dict.getDict('yesOrNo')"/>
              </el-form-item>
              <el-form-item label="是否网格员" prop="isGridman">
                <ai-select v-model="form.isGridman" :selectList="dict.getDict('yesOrNo')"/>
              </el-form-item>
              <el-form-item label="是否本土人才" prop="isLocalTalent">
                <ai-select v-model="form.isLocalTalent" :selectList="dict.getDict('yesOrNo')"/>
              </el-form-item>
              <el-form-item label="是否异地任职" prop="isWorkDifferent">
                <ai-select v-model="form.isWorkDifferent" :selectList="dict.getDict('yesOrNo')"/>
              </el-form-item>
              <el-form-item label="专业技术职务">
                <el-input v-model="form.expertisePosition" placeholder="请输入..." clearable/>
              </el-form-item>
              <el-form-item label="熟悉专业有何专长">
                <el-input v-model="form.professionalExpertise" placeholder="请输入..." clearable/>
              </el-form-item>
              <el-form-item label="其他职务" prop="workDifferent">
                <el-input v-model="form.workDifferent " placeholder="请输入..." clearable/>
              </el-form-item>
            </el-row>
          </template>
        </ai-card>
        <tabs-card :instance="instance" :dict="dict" :permissions="permissions" :form.sync="form" editable/>
      </el-form>
      <ai-dialog :visible.sync="dialog" title="学历信息" width="720px" @onConfirm="handleSubmitEducation"
                 @closed="educationForm={}">
        <el-form :rules="rules" ref="educationForm" :model="educationForm" label-width="110px" size="small">
          <el-form-item label="学历类型" prop="educationType">
            <ai-select v-model="educationForm.educationType"
                       :selectList="dict.getDict('appVillageCadresEducationType')"/>
          </el-form-item>
          <el-form-item label="毕业院校" prop="graduatedSchool">
            <el-input v-model="educationForm.graduatedSchool" placeholder="请输入" clearable/>
          </el-form-item>
          <el-form-item label="学历" prop="educationalLevel">
            <ai-select v-model="educationForm.educationalLevel" :selectList="dict.getDict('education_village_rc')"/>
          </el-form-item>
          <el-form-item label="专业" prop="learnProfession">
            <el-input v-model="educationForm.learnProfession" placeholder="请输入" clearable/>
          </el-form-item>
          <el-form-item label="毕业时间:" prop="graduationTime">
            <el-date-picker placeholder="选择毕业日期"
                            v-model="educationForm.graduationTime"
                            type="date"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            format="yyyy-MM-dd"/>
          </el-form-item>
        </el-form>
      </ai-dialog>
    </template>
    <template #footer>
      <el-button class="delete-btn" @click="$router.push({})">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </ai-detail>
</template>
<script>
import {mapState} from "vuex";
import TabsCard from "./tabsCard";

export default {
  name: "functionaryCreate",
  components: {TabsCard},
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
  },
  inject: ['top'],
  computed: {
    ...mapState(["user"]),
    detailTitle() {
      return !this.isEdit ? '添加干部档案' : '编辑干部档案'
    },
    isEdit() {
      return !!this.$route.query.id
    },
    disabledLevel() {
      if (!!this.form.workAreaId) {
        let code = JSON.parse(JSON.stringify(this.form.workAreaId))
        if (/0{10}$/g.test(code)) {
          return 1
        } else if (/0{8}$/g.test(code)) {
          return 2
        } else if (/0{6}$/g.test(code)) {
          return 3
        } else if (/0{3}$/g.test(code)) {
          return 4
        } else return 5
      } else return -1
    },
    rules() {
      const IdNumberPass = (rule, value, callback) => {
        const IDREG = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        if (value) {
          if (IDREG.test(value)) {
            callback();
          } else {
            callback(new Error("身份证号格式错误"));
          }
        } else {
          callback(new Error("请填写身份证号"));
        }
      };
      return {
        workAreaId: [
          {required: true, validator: (r, v, cb) => /0{3}$/g.test(v) ? cb('任职地区必须选到村级') : cb(), trigger: "blur"}
        ],
        currentAreaId: [
          {validator: (r, v, cb) => v && /0{3}$/g.test(v) ? cb('任职地区必须选到村级') : cb(), trigger: "blur"}
        ],
        positionType: [
          {required: true, message: "请选择职务类别", trigger: "change"}
        ],
        workTime: [
          {required: true, message: "请选择任职时间", trigger: "change"}
        ],
        name: [{required: true, message: "请填写姓名", trigger: "blur"}],
        idNumber: [
          {required: true, validator: IdNumberPass, trigger: "blur"},
          {min: 18, max: 18, message: "身份证号码为18位数", trigger: "blur"}
        ],
        gender: [{required: true, message: "请选择性别", trigger: "blur"}],
        isSubordinate: [
          {required: true, message: "请选择是否镇街下派", trigger: "change"}
        ],
        isVillageMember: [
          {
            required: true,
            message: "请选择是否村(居)委会委员",
            trigger: "change"
          }
        ],
        isBranchMember: [
          {required: true, message: "请选择是否支委委员", trigger: "change"}
        ],
        isVillageSupervision: [
          {required: true, message: "请选择是否村(居)务监督委员会成员", trigger: "change"}
        ],
        villageMemberPosition1: [
          {required: true, message: "请选择村(居)委会委员职务"}
        ],
        isFulltimeCadres: [
          {required: true, message: "请选择是否专职干部", trigger: "change"}
        ],

        isCollegeOfficer: [
          {required: true, message: "请选择是否大学生村官", trigger: "change"}
        ],
        isLeagueSecretary: [
          {required: true, message: "请选择是否团支部书记", trigger: "change"}
        ],
        isMilitiaCommander: [
          {required: true, message: "请选择是否民兵连长", trigger: "change"}
        ],
        isGridman: [{required: true, message: "请选择是否网格员", trigger: "change"}],
        isWorkDifferent: [
          {required: true, message: "请选择是否异地任职", trigger: "change"}
        ],
        isWomenChairman: [
          {required: true, message: "请选择是否妇联主席", trigger: "change"}
        ],
        isVillageLeader: [
          {required: true, message: "请选择是否村(居)民小组长", trigger: "change"}
        ],
        isLocalTalent: [
          {required: true, message: "请选择是否本土人才", trigger: "change"}
        ],
        educationType: [
          {required: true, message: "请选择学历类型", trigger: "blur"}
        ],
        graduatedSchool: [
          {required: true, message: "请输入毕业院校", trigger: "blur"}
        ],
        educationalLevel: [
          {required: true, message: "请选择学历", trigger: "blur"}
        ],
        learnProfession: [
          {required: true, message: "请输入专业", trigger: "blur"}
        ],
        graduationTime: [
          {required: true, message: "请选择毕业时间", trigger: "blur"}
        ]
      }
    },
  },
  data() {
    return {
      dialog: false,
      form: {
        families: [],
        serves: [],
        negatives: [],
        assessments: [],
        educations: [],
        status: 1,

        isSubordinate: '0',
        isCollegeOfficer: '0',
        isVillageMember: '0',
        villageMemberPosition1: null,
        isBranchMember: '0',
        branchMemberPosition1: null,
        isVillageSupervision: '0',
        villageSupervisionPosition1: null,
        isFulltimeCadres: '0',
        fulltimeCadresPosition1: null,
        fulltimeCadresTime: null,
        isLeagueSecretary: '0',
        isWomenChairman: '0',
        isMilitiaCommander: '0',
        isVillageLeader: '0',
        isGridman: '0',
        isLocalTalent: '0',
        isWorkDifferent: '0',
      },
      educationForm: {},
    }
  },
  methods: {
    getDetail() {
      let {id} = this.$route.query
      this.instance.post(`/app/appvillagecadresnew/queryDetailById`, null, {
        params: {id}
      }).then(res => {
        if (res?.data) {
          let {idNumber, enterPartyTime, enterWorkTime} = res.data
          let {birthday} = this.idCardNoUtil.getIdCardInfo(idNumber)
          this.form = {
            ...res.data, birthday,
            enterPartyTimeShow: this.$dateFormat(enterPartyTime),
            enterWorkTimeShow: this.$dateFormat(enterWorkTime),
            age: this.$calcAge(idNumber)
          }
        }
      })
    },
    // 确认按钮
    handleSubmitEducation() {
      this.$refs.educationForm.validate(v => {
        if (v) {
          if (this.educationForm?.index > -1) {
            this.form.educations.splice(this.educationForm.index, 1, this.educationForm)
          } else {
            this.form.educations.push(this.educationForm)
          }
          this.dialog = false
        }
      })
    },
    //编辑 学历记录记录
    handleEditEducation(row, index) {
      this.educationForm = JSON.parse(JSON.stringify({...row, index}))
      this.dialog = true
    },
    //删除学历记录记录
    handleDelEducation(i) {
      this.form.educations.splice(i, 1)
    },
    getInfoFromResident(val) {
      this.form.idNumber = val.idNumber;
      this.form.name = val.name;
      this.form.avatarUrl = val.photo;
      this.form.age = val.age
      this.form.gender = val.sex
      this.form.birthday = this.$dateFormat(this.idCardNoUtil.getIdCardInfo(val.idNumber)?.birthday, "YYYY-MM-DD 00:00:00")
      this.$forceUpdate()
    },
    handleSubmit() {
      this.$refs.cadresForm.validate(v => {
        if (v) {
          this.instance.post("/app/appvillagecadresnew/addOrUpdate", {
            ...this.form,
            birthday: this.$dateFormat(this.form.birthday, 'YYYY-MM-DD 00:00:00')
          }).then(res => {
            if (res?.code == 0) {
              this.$message.success("提交成功!")
              if (this.isEdit) {
                this.$router.push({query: this.$route.query})
              } else {
                this.$router.push({})
              }
            }
          })
        }
      })
    },
    handleIdNumberInfo(v) {
      if (this.idCardNoUtil.checkIdCardNo(v)) {
        let {birthday, sex} = this.idCardNoUtil.getIdCardInfo(v)
        this.form.birthday = birthday
        this.form.gender = sex
        this.$forceUpdate()
      }
    }
  },
  created() {
    this.dict.load(
        "education_village_rc",
        "cadrePositionType",
        "healthCondition",
        "politicsStatus",
        "householdRelation",
        "presentPost",
        "partyPosition",
        "sex",
        "faithType",
        "nation",
        "appVillageSubsidyForm",
        "yesOrNo",
        "appFulltimeCadresPosition1",
        "appVillageCadresAssessmentResult",
        "appVillageSupervisionPosition1",
        "appBranchMemberPosition1",
        "appVillageCadresEducationType",
        "appVillageMemberPosition1"
    )
    this.form.workAreaId = JSON.parse(JSON.stringify(this.top.areaId))
    this.isEdit && this.getDetail()
  },
}
</script>
<style lang="scss" scoped>
.functionaryCreate {
  height: 100%;
  position: relative;

  ::v-deep .el-button--text {
    .iconfont {
      color: inherit;
      font-size: inherit;
    }
  }

  .wrap {
    flex-wrap: wrap;
  }

  .el-form-item {
    .el-input, .el-select, .el-date-editor {
      width: 100%;
    }
  }

  ::v-deep .ai-card__body {
    .el-form-item {
      width: 50%;
      flex-shrink: 0;

      &[row] {
        width: 100%;
      }

      &[column] {
        height: 100%;
      }

      &[layout] {
        margin-bottom: 0;
      }

      .AiPersonSelect {
        margin-left: 8px;
      }
    }
  }

  ::v-deep .el-table__empty-text {
    height: 88px;
    line-height: 88px;
  }


  .el-icon-delete:hover {
    color: #f46;
  }
}
</style>
