<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
          v-model="form.certificateUserId"
          style="width:400px;"
          placeholder="请选择"
        >
          <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: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)"
            :disabled='!form.signPfxDeputieList[key].projectId'
            v-model="form.signPfxDeputieList[key].contractId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in ContractSection"
              :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="请选择参建方"
          >
            <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 } from "@/api/certificate/list";
export default {
  data () {
    return {
      form: {
        certificateType: 1,
        certificateUserName: '',
        certificateId: '',//所持证书者身份证ID
        enterpriseUnifiedCode: '',//企业统一社会信用代码
        certificateNumber: '',
        certificatePassword: '',
        certificateUserId: '',
        certificateFileUrl: [],//证书文件
        signatureFileUrl: [],//签名体图片
        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', }],
      },
      ParticipationConstruction: [],//参见项目方
      projectMeiju: [],//项目
      ContractSection: [],//合同段
      userData: [],//关联用户
    }
  },
  methods: {
    //#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,
          }
          if (this.form.certificateFileUrl[0].name) {
            fromData.certificateFileUrl = await this.addFileInfo(this.form.certificateFileUrl[0].raw)
          } else {
            fromData.certificateFileUrl = this.form.certificateFileUrl[0].raw
          }

          if (this.form.signatureFileUrl[0].name) {
            fromData.signatureFileUrl = await this.addFileInfo(this.form.signatureFileUrl[0].raw)
          } 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: '',
      })
    },
    focusContractSection (projectId) {//获取合同段数据
      this.projectMeiju.forEach(val => {
        if (val.id == projectId) {
          this.ContractSection = val.contractInfoList
          return
        }
      })
    },
    changeProjectId (key) {//项目id发生改变
      this.form.signPfxDeputieList[key].contractId = ''
    },
    //#endregion

    //#region //接口
    async getById () {//获取详细信息
      const { data: res } = await getById({ id: this.$route.query.id })
      if (res.code == 200) {
        this.form = res.data
        this.form.certificateFileUrl = [{ raw: res.data.certificateFileUrl }]
        this.form.signatureFileUrl = [{ raw: res.data.signatureFileUrl }]
      }
    },
    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()
      if (res.code == 200) {
        this.projectMeiju = 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.link
      }
    },
    async update (da) {//编辑保存接口
      const { data: res } = await update(da)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '修改电签成功!'
        })
        this.$router.push('/certificate/list')
      }
    },
    //#endregion
  },
  created () {
    if (this.$route.query.id != 0) {
      this.getById()
    }
    this.findUserByName()//关联用户
    this.queryRole()//获取角色方
    this.queryProjectAndContract()//获取项目和合同段
  },
}
</script>

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