<template>
  <basic-container class="addList">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="170px"
      :inline="true"
    >
      <el-form-item
        label="证书类型"
        prop="certificateType"
        style="width:100%;"
      >
        <el-radio-group v-model="form.certificateType">
          <el-radio :label="1">个人证书</el-radio>
          <el-radio :label="2">企业证书</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="证书所有者"
        prop="certificateUserName"
        style="width:45%;"
      >
        <el-input
          v-model="form.certificateUserName"
          style="width:400px;"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="所持证书者身份证ID"
        prop="certificateId"
        v-if="form.certificateType==1"
        style="width:45%;"
      >
        <el-input
          v-model="form.certificateId"
          style="width:400px;"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="企业统一社会信用代码"
        style="width:45%;"
        prop="enterpriseUnifiedCode"
        v-else
      >
        <el-input
          v-model="form.enterpriseUnifiedCode"
          style="width:400px;"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="证书编号"
        prop="certificateNumber"
        style="width:45%;"
      >
        <el-input
          v-model="form.certificateNumber"
          style="width:400px;"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="证书密码"
        prop="certificatePassword"
        style="width:45%;"
      >
        <el-input
          v-model="form.certificatePassword"
          style="width:400px;"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="证书文件"
        style="width:45%;"
        prop="certificateFileUrl"
      >
        <el-upload
          class="upload-demo"
          action="#"
          multiple
          :limit="2"
          :auto-upload="false"
          accept='.pfx'
          :file-list="form.certificateFileUrl"
          :before-remove="beforeRemove"
          :on-change="changecertificateFileUrl"
        >
          <el-button
            size="small"
            type="primary"
          >上传文件</el-button>
          <div
            slot="tip"
            class="el-upload__tip"
          >支持上传文件格式为pfx文件</div>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="关联用户"
        style="width:45%;"
        prop="certificateUserId"
        v-if="form.certificateType==1"
      >
        <el-select
          filterable
          v-model="form.certificateUserId"
          style="width:400px;"
          placeholder="请选择"
          @change="selectUser"
        >
          <el-option
            v-for="item in userData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="签章类型"
        style="width:45%;"
        prop="pfxType"
        v-else
      >
        <el-select
          v-model="form.pfxType"
          style="width:400px;"
          placeholder="请选择"
        >
          <el-option
            v-for="item in pfxType"
            :key="item.dictKey"
            :label="item.dictValue"
            :value="item.dictKey"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="签名体图片"
        style="width:100%;"
        prop="signatureFileUrl"
      >
        <el-upload
          class="upload-demo"
          action="#"
          multiple
          :limit="2"
          :auto-upload="false"
          accept='.jpg,.png'
          :file-list="form.signatureFileUrl"
          :before-remove="beforeRemove2"
          :on-change="changecertificateFileUrl2"
        >
          <el-button
            size="small"
            type="primary"
          >上传文件</el-button>
          <div
            slot="tip"
            class="el-upload__tip"
          >支持上传文件格式为JPG/PNG</div>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="关联项目"
        tyle="width:100%;"
        prop="signPfxDeputieList"
        v-if="form.certificateType==2"
      >
        <i
          class="el-icon-circle-plus"
          style="color:red;font-size:24px;line-height:40px;cursor: pointer;"
          @click="pushSignPfxDeputieList"
        ></i>
        <div
          v-for="(item,key) in form.signPfxDeputieList"
          :key='key'
        >
          <!-- 项目 -->
          <el-select
            style="width:300px;"
            class="martop20"
            v-model="form.signPfxDeputieList[key].projectId"
            placeholder="请选择"
            @change="changeProjectId(key)"
          >
            <el-option
              v-for="item in projectMeiju"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <!-- 合同段 -->
          <el-select
            style="width:300px;"
            class="marleft20 martop20"
            @focus="focusContractSection(form.signPfxDeputieList[key].projectId,key)"
            :disabled='!form.signPfxDeputieList[key].projectId'
            v-model="form.signPfxDeputieList[key].contractId"
            placeholder="请选择"
            @change="checkRoleRepeat(key)"
          >
            <el-option
              v-for="item in form.signPfxDeputieList[key].contractList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-select
            class="marleft20 martop20"
            style="width:300px;"
            v-model="form.signPfxDeputieList[key].roleId"
            placeholder="请选择参建方"
            @change="checkRoleRepeat(key)"
          >
            <el-option
              v-for="item in ParticipationConstruction"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <i
            class="el-icon-error marleft10"
            @click="deleteSignPfxDeputie(key)"
            style="fontSize:20px;color:#F0630A;cursor: pointer;"
          ></i>
        </div>
        <!-- signPfxDeputieList -->
      </el-form-item>
    </el-form>
    <div class="flexCenter">
      <el-button @click="cancel">取消</el-button>
      <el-button
        class="marleft30"
        type="primary"
        v-throttle='2000'
        @click="savess()"
      >保存</el-button>
    </div>
  </basic-container>
</template>

<script>
import { save, getById, findUserByName, queryRole, queryProjectAndContract, addFileInfo, update, findPfxType } from "@/api/certificate/list";
export default {
  data () {
    return {
      form: {
        certificateType: 1,
        certificateUserName: '',
        certificateId: '',//所持证书者身份证ID
        enterpriseUnifiedCode: '',//企业统一社会信用代码
        certificateNumber: '',
        certificatePassword: '',
        certificateUserId: '',
        pfxType: '',
        certificateFileUrl: [],//证书文件
        certificateFileName: '',//证书文件名称
        signatureFileUrl: [],//签名体图片
        signatureFileName: '',//签名体图片文件名称
        signPfxDeputieList: [],
      },
      rules: {
        certificateType: [{ required: true, message: '请选择', trigger: 'change' }],
        certificateUserName: [{ required: true, message: '请输入证书所有者', trigger: 'blur' }],
        // certificateId: [{ required: true, message: '请输入所持证书者身份ID', trigger: 'blur' }],
        enterpriseUnifiedCode: [{ required: true, message: '请输入企业统一社会信用代码', trigger: 'blur' }],
        certificateNumber: [{ required: true, message: '请输入证书编号', trigger: 'blur' }],
        certificatePassword: [{ required: true, message: '请输入证书密码', trigger: 'blur' }],
        certificateUserId: [{ required: true, message: '请选择关联用户', trigger: 'change' }],
        certificateFileUrl: [{ required: true, message: '请选择证书文件', trigger: 'change' }],
        signatureFileUrl: [{ required: true, message: '请选择签名体图片', trigger: 'change', }],
        signPfxDeputieList: [{ required: true, message: '请设置关联项目', trigger: 'change', }],
        pfxType: [{ required: true, message: '请选择签章类型', trigger: 'change', }],
      },
      ParticipationConstruction: [],//参见项目方
      projectMeiju: [],//项目
      ContractSection: [],//合同段
      userData: [],//关联用户
      pfxType: []//
    }
  },
  methods: {
    selectUser(){
      let _this = this;
      this.userData.forEach(vo => {
        if(_this.form.certificateUserId == vo.id){
          _this.form.certificateId = vo.idNumber;
        }
      });
    },
    async init () {
      if (this.$route.query.id != 0) {
        await this.getById()
      }
      this.queryProjectAndContract()//获取项目和合同段
    },
    //#region
    cancel () {//取消按钮
      this.$router.push('/certificate/list')
    },
    savess () {//保存按钮
      this.$refs.form.validate(async valid => {
        if (valid) {
          let fromData = {
            certificateType: this.form.certificateType,
            certificateUserName: this.form.certificateUserName,
            certificateNumber: this.form.certificateNumber,
            certificatePassword: this.form.certificatePassword,
            certificateId: this.form.certificateId,
            pfxType: this.form.pfxType
          }

          if (this.form.certificateFileUrl[0].name && this.form.certificateFileUrl[0].status === "ready") {
            let fileData = await this.addFileInfo(this.form.certificateFileUrl[0].raw);
            fromData.certificateFileUrl = fileData.link;
            fromData.certificateFileName = fileData.originalName;
          } else {
            fromData.certificateFileUrl = this.form.certificateFileUrl[0].raw
          }

          if (this.form.signatureFileUrl[0].name && this.form.signatureFileUrl[0].status === "ready") {
            let fileData = await this.addFileInfo(this.form.signatureFileUrl[0].raw);
            fromData.signatureFileUrl = fileData.link;
            fromData.signatureFileName = fileData.originalName;
          } else {
            fromData.signatureFileUrl = this.form.signatureFileUrl[0].raw
          }
          let tag = true
          let enterpriseUnifiedCode = ''
          if (this.form.certificateType == 1) {
            fromData.certificateUserId = this.form.certificateUserId//关联用户
          } else {
            this.form.signPfxDeputieList.forEach(val => {
              if (!val.projectId || !val.contractId || !val.roleId) {
                tag = false
                return
              } else {
                if (enterpriseUnifiedCode) {
                  enterpriseUnifiedCode += ','
                }
                enterpriseUnifiedCode += `${val.projectId}-${val.contractId}-${val.roleId}`
              }
            })
            fromData.projectContractRole = enterpriseUnifiedCode  //关联项目
            fromData.enterpriseUnifiedCode = this.form.enterpriseUnifiedCode
          }
          if (tag) {
            if (this.$route.query.id == 0) {
              this.save(fromData)//新增接口
            } else {
              fromData.id = this.form.id
              this.update(fromData)//编辑接口
            }
          } else {
            this.$message({
              type: 'error',
              message: "请填写完整关联项目!"
            })
          }
        }
      })
    },
    deleteSignPfxDeputie (key) {//删除关联项目
      this.form.signPfxDeputieList.splice(key, 1)
    },
    //#endregion

    //#region 上传文件得方法
    beforeRemove (file, fileList) {//证书文件删除回调
      this.form.certificateFileUrl = []
    },
    changecertificateFileUrl (file) {//证书文件变化回调
      this.form.certificateFileUrl = [file]
    },
    beforeRemove2 (file, fileList) {//签名体图片删除回调
      this.form.signatureFileUrl = []
    },
    changecertificateFileUrl2 (file) {//签名体图片变化回调
      this.form.signatureFileUrl = [file]
    },
    pushSignPfxDeputieList () {//添加关联项目
      // this.form.signPfxDeputieList.unshift({
      //   projectId: '',
      //   contractId: '',
      //   roleId: '',
      // })

      this.form.signPfxDeputieList.push({
        projectId: '',
        contractId: '',
        roleId: '',
        contractList: []
      })

    },
    focusContractSection (projectId, key) {//获取合同段数据
      this.projectMeiju.forEach(val => {
        if (val.id == projectId) {
          // this.ContractSection[key] = val.contractInfoList
          this.form.signPfxDeputieList[key].contractList = val.contractInfoList
        }
      })
    },
    changeProjectId (key) {//项目id发生改变
      this.form.signPfxDeputieList[key].contractId = ''
    },
    //#endregion

    //#region //接口
    async getById () {//获取详细信息
      const { data: res } = await getById({ id: this.$route.query.id })
      console.log(res);
      if (res.code == 200) {
        this.form = res.data
        this.form.certificateFileUrl = [{ raw: res.data.certificateFileUrl, name: this.form.certificateFileName }]
        this.form.signatureFileUrl = [{ raw: res.data.signatureFileUrl, name: this.form.signatureFileName }]
      }
    },
    async save (da) {//新增
      const { data: res } = await save(da)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '新增电签成功!'
        })
        this.$router.push('/certificate/list')
      }
    },
    async findUserByName () { //关联用户
      const { data: res } = await findUserByName()
      if (res.code == 200) {
        this.userData = res.data
      }
    },
    async queryRole () { //获取角色方
      const { data: res } = await queryRole()
      if (res.code == 200) {
        this.ParticipationConstruction = res.data
      }
    },
    async queryProjectAndContract () {//获取项目和合同段
      const { data: res } = await queryProjectAndContract()
      console.log(res);
      if (res.code == 200) {
        this.projectMeiju = res.data
        // this.form.signPfxDeputieList.forEach((val, key) => {
        //   this.ContractSection.push(res.data[key].contractInfoList)
        // })

        if(this.form.signPfxDeputieList.length > 0){
            this.form.signPfxDeputieList.forEach((val, key) => {
              this.projectMeiju.forEach((project, key) => {
                if(val.projectId == project.id){
                  val.contractList = project.contractInfoList;
                }
              })
            })
        }

        console.log(this.form.signPfxDeputieList);
      }
    },
    async findPfxType () {
      const { data: res } = await findPfxType({ typeOrStatus: 'pfx_type' })
      if (res.code == 200) {
        this.pfxType = res.data;
      }
    },
    async addFileInfo (file) {//上传图片
      let fromData = new FormData();
      fromData.append('file', file);
      const { data: res } = await addFileInfo(fromData)
      if (res.code == 200) {
        return res.data;
      }
    },
    async update (da) {//编辑保存接口
      const { data: res } = await update(da)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '修改电签成功!'
        })
        this.$router.push('/certificate/list')
      }
    },
    //#endregion

    //检测参建方是否重复
    checkRoleRepeat(index){
      let cur = this.form.signPfxDeputieList[index];
      if(!cur.roleId){
        return;
      }

      this.form.signPfxDeputieList.forEach((info,i)=>{
        if(i === index){
          return;
        }
        if(info.contractId == cur.contractId && info.roleId == cur.roleId){
          this.$message({
            message: "关联的项目参见方不可重复",
            type: 'error'
          });
          this.form.signPfxDeputieList[index].roleId = '';
        }
      })
    }
  },
  created () {
    this.init()
    this.queryRole()//获取角色方
    this.findUserByName()//关联用户
    this.findPfxType();//查询企业签章类型
  },
  mounted () {

  }
}
</script>

<style lang="scss" scoped>
</style>
