<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:45%;"
      >
        <el-radio-group v-model="form.certificateType" @change="changeCertificateType">
          <el-radio :label="1">个人证书</el-radio>
          <el-radio :label="2">企业证书</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="签字公司"
        prop="company"
        style="width:45%;"
        v-if="form.certificateType===2"
      >
          <el-select
              v-model="form.company"
              placeholder="请选择"
              style="width: 400px;"
              clearable
              @visible-change="changeCompany"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.dictValue"
                :value="item.dictKey"
              ></el-option>
          </el-select>
      </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&&form.company!=3"
        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-if="form.certificateType!==1&&form.company!=3"
      >
        <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%;"
        v-if="form.company!=3"
      >
        <el-input
          v-model="form.certificatePassword"
          style="width:400px;"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="签章类型"
        style="width:45%;"
        prop="pfxType"

      >
        <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: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:100%;"
        prop="certificateFileUrl"
        v-if="form.company!=3"
      >
        <el-upload
          class="upload-demo" action="#" multiple :limit="1" :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:100%;" prop="signatureFileUrl" v-if="form.company!=3">
        <el-upload
          class="upload-demo" action="#" multiple :limit="1" :auto-upload="false" accept='.jpg,.png'
          :file-list="form.signatureFileUrl" :before-remove="beforeRemove2" :on-change="changecertificateFileUrl2"
        >
          <div style="position: relative; display: flex; align-items: center;">
            <el-button size="small" type="primary">上传文件</el-button>
            <div style="position: relative; display: flex;align-items: center; color: #1A1A1A; cursor: default;" @click.stop="stopClick">
              <el-input v-model="form.wide" style="width:60px; margin-left: 24px;" placeholder="宽度" size="small" :disabled="form.signatureFileUrl.length<=0"></el-input>
              <div style="display: inline-block; margin-left: 8px;">x</div>
              <el-input v-model="form.high" style="width:60px; margin-left: 8px;" placeholder="高度" size="small" :disabled="form.signatureFileUrl.length<=0"></el-input>
              <el-button size="small" type="warning" style="margin-left: 12px" :disabled="form.signatureFileUrl.length <= 0 " @click.stop="signaturePreview">预览</el-button>
            </div>
          </div>
          <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, picPresave, prePicture, compressAndUpload } from "@/api/certificate/list";
import {getDictionary as getDictbiz} from "@/api/system/dictbiz";
export default {
  data () {
    return {
      form: {
        certificateType: 1,
        certificateUserName: '',
        certificateId: '',//所持证书者身份证ID
        enterpriseUnifiedCode: '',//企业统一社会信用代码
        certificateNumber: '',
        certificatePassword: '123456',
        certificateUserId: '',
        pfxType: '',
        certificateFileUrl: [],//证书文件
        certificateFileName: '',//证书文件名称
        signatureFileUrl: [],//签名体图片
        signatureFileName: '',//签名体图片文件名称
        signPfxDeputieList: [],
        company:2,
        wide: '',
        high: ''
      },
      rules: {
        company:[{ required: false, message: '请选择', trigger: 'change' }],
        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' }],
        certificateNumber:[],
        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: [],//
      options:[],
      signatureId: '',
    }
  },
  methods: {
   // 根据条件动态设置 dependentField 的验证规则
   updateDependentFieldValidation() {
      const conditionFieldValue = this.form.company;
      console.log(conditionFieldValue,'conditionFieldValue');
      // 清空 dependentField 的验证规则
      this.rules.certificateNumber = [];

      // 根据条件字段的值来决定是否必填
      if (conditionFieldValue === 3) {
        // 设置为必填项
        this.rules.certificateNumber.push({ required: true, message: 'Dependent Field 是必填项', trigger: 'change' });
      }else{
        this.rules.certificateNumber = [];
      }
    },
    //获取签字公司
    getOptions() {
      getDictbiz({
        code: 'es_type_name'
      }).then((res) => {

        this.options = res.data.data;
      this.options.forEach((ele)=>{
          ele.dictKey=Number(ele.dictKey)
        })
      })
      console.log( this.options,' this.options');
    },
    selectUser(){
      let _this = this;
      this.userData.forEach(vo => {
        if(_this.form.certificateUserId == vo.id){
          _this.form.certificateId = vo.idNumber;
          console.log(vo,'vo');
           _this.form.certificateUserName=vo.realName

        }
      });
    },
    changeCompany(){
      this.$forceUpdate()
      this.updateDependentFieldValidation()
    },
    async init () {

      if (this.$route.query.id != 0) {
        await this.getById()
      }
      this.queryProjectAndContract()//获取项目和合同段

    },
    //#region
   cancel() {
    const { value, certificateTypeValue, searchinput, pageindex, pagesize } = this.$route.query;
    this.$router.push({
      path: '/certificate/list',
      query: {
        value,
        certificateTypeValue,
        searchinput,
        pageindex,
        pagesize
      }
    });
  },
    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,
            wide: this.form.wide,
            high: this.form.high,
          }

          if (this.form.certificateFileUrl[0]&&this.form.certificateFileUrl[0].name&&this.form.certificateFileUrl[0].raw && 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.certificateFileUrl&&this.form.certificateFileUrl[0]&&this.form.certificateFileUrl[0].raw){
               fromData.certificateFileUrl = this.form.certificateFileUrl[0].raw
            }

            console.log(this.form.certificateFileUrl,'this.form.certificateFileUrl');
          }

          if (this.form.signatureFileUrl[0]&&this.form.signatureFileUrl[0].name && this.form.signatureFileUrl[0].status === "ready") {
            const url = await this.prePictureApi()
            if (url) {
              fromData.wide = this.form.wide
              fromData.high = this.form.high
            }
            let fileData = await this.compressAndUploadApi(this.form.signatureFileUrl[0].raw, fromData.wide, fromData.high);
            fromData.signatureFileUrl = fileData.link;
            fromData.signatureFileName = fileData.originalName;
          } else {
            if(this.form.signatureFileUrl&&this.form.signatureFileUrl[0]&&this.form.signatureFileUrl[0].raw){
              const url = await this.prePictureApi()
              if (url) {
                fromData.wide = this.form.wide
                fromData.high = this.form.high
              }
               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
          }
         console.log(fromData,'fromData');
         console.log(this.form,'fromData');
         if(this.form.company=='3'){
          fromData.certificateType=3
         }
          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: "请填写完整关联项目!"
            })
          }
        }
      })
    },

    async compressAndUploadApi(file, wide, high) {
      let fromData = new FormData();
      fromData.append('file', file);
      fromData.append('wide', wide);
      fromData.append('high', high);
      const { data: res } = await compressAndUpload(fromData)
      if (res.code == 200) {
        return res.data;
      }
    },

    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]
      this.form.wide = ''
      this.form.high = ''
    },
    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
        if(res.data.certificateType!==1){
          this.form.company=res.data.certificateType
          this.form.certificateType=2
        }

        if(res.data.certificateFileUrl&&this.form.certificateFileName){
           this.form.certificateFileUrl = [{ raw: res.data.certificateFileUrl, name: this.form.certificateFileName }]
        }else{
          this.form.certificateFileUrl=[]
        }
          if(res.data.signatureFileUrl&&this.form.signatureFileName){
           this.form.signatureFileUrl = [{ raw: res.data.signatureFileUrl, name: this.form.signatureFileName }]
        }else{
          this.form.signatureFileUrl = []
        }
        //宽度
        this.form.wide = res.data.wide ? res.data.wide : ''
        //高度
        this.form.high = res.data.high ? res.data.high : ''
      }
    },
    async save (da) {//新增
      const { data: res } = await save(da)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '新增电签成功!'
        })
        // this.$router.push('/certificate/list')
       this.$router.push({
          path: '/certificate/list',
          query: {
            value: this.$route.query.value,
            certificateTypeValue: this.$route.query.certificateTypeValue,
            searchinput: this.$route.query.searchinput,
            pageindex: this.$route.query.pageindex,
            pagesize: this.$route.query.pagesize
          }
        });
      }
    },
    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')
         this.$router.push({
          path: '/certificate/list',
          query: {
            value: this.$route.query.value,
            certificateTypeValue: this.$route.query.certificateTypeValue,
            searchinput: this.$route.query.searchinput,
            pageindex: this.$route.query.pageindex,
            pagesize: this.$route.query.pagesize
          }
        });
      }
    },
    //#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 = '';
        }
      })
    },
    //改变证书类型
    changeCertificateType(val){
      if(val==1){
        console.log(this.form.company,'公司');
        this.form.company=2
        this.$forceUpdate();//强制刷新视图
        this.updateDependentFieldValidation()
      }
    },
    //预览
    async signaturePreview() {
      const form = this.form
      const isImg = form.signatureFileUrl.length <= 0
      if (isImg) {
        this.$message({
          message: '请先上传签名图片',
          type: 'error'
        })
        return false
      }
      const file = form.signatureFileUrl[0].raw
      if (!file) {
        this.$message({
          message: '请重新上传签名文件',
          type: 'error'
        })
        return false
      }
      const url = await this.prePictureApi()
      if (!url) return
      window.open(url, '_blank')
    },
    async prePictureApi() {
      const form = this.form
      const file = form.signatureFileUrl[0].raw
      if (!file) return false
      let fromData = new FormData();
      if (typeof file === 'object') {
        fromData.append('file', file);
        fromData.append('fileStr', '');
      } else {
        fromData.append('file', '');
        fromData.append('fileStr', file);
      }
      fromData.append('wide', form.wide);
      fromData.append('high', form.high);
      const { data: res } = await prePicture(fromData)
      const data = res.data;
      if (!data.preUrl) return false
      this.form.wide = data.wide //宽度
      this.form.high = data.high //高度
      return data.preUrl
    },
    stopClick() {},
  },
  created () {
    this.getOptions()
    this.init()
    this.queryRole()//获取角色方
    this.findUserByName()//关联用户
    this.findPfxType();//查询企业签章类型
  },
  mounted () {
    this.updateDependentFieldValidation();
  }
}
</script>

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