<template>
  <div>
    <basic-container class="econtract-header" v-if="permission.manage_econtract_viewColumn">
      <ul class="header">
        <!--<li>
          <h3>电子签章管理</h3>
        </li>-->
        <li v-if="econtractStatus.sealOn == 0">电子签章未开通，请申请开通电子签章 <el-button type="primary"
            @click="handelEnableSignature">申请开通电子签章</el-button>
        </li>
        <li v-else-if="econtractStatus.sealOn == 1">电子签章已申请，正在审核中...</li>
        <li v-else-if="econtractStatus.sealOn == 2">电子合同状态：<span v-if="econtractStatus.contractOn">启用</span><span
            v-else>未启用</span></li>
        <li v-show="econtractStatus.contractOn">电子签章：<el-button @click="handelViewSignature" type="primary">查
            看</el-button><el-button @click="handelResetPwd">重置密码</el-button></li>
      </ul>
    </basic-container>

    <basic-container>
      <div class="econtract">
        <!--申请电子签章dialog-->
        <el-dialog title="申请电子签章" append-to-body :visible.sync="dialogVisible" width="30%" :before-close="handleClose"
          class="applyEcontract">
          <el-form :model="applyEcontractForm" ref="applyEcontractForm" label-width="100px" class="demo-ruleForm"
            :rules="ruleValidate">
            <el-form-item label="上传《电子签章申请表》：" prop="authUrlId" :label-position="labelPosition" label-width="210px">
              <el-upload :show-file-list="false" :on-progress="() => {
                  uploading = true;
                }
                " :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :http-request="httpRequest">
                <div v-loading="uploading">
                  <img class="contract-signature-image" :src="applyEcontractForm.authUrlId || imageUrl" />
                </div>
                <div slot="tip" class="el-upload__tip">*请上传高清扫描文件</div>
              </el-upload>
              <div class="uploadEcontractBtn" @click="handleDownload"><i class="el-icon-download"
                  style="color: #409EFF;"></i>下载《电子签章申请表》模板</div>
              <!-- <p class="uploadImgP">上传图片大小限制5M以内</p> -->
            </el-form-item>
            <el-form-item label="请设置签章密码：" prop="pwd" :label-position="labelPosition" label-width="210px">
              <el-col :span="16">
                <el-input type="number" maxlength="6"
                  onKeypress="return(/^[0-9]*$/.test(String.fromCharCode(event.keyCode)))"
                  v-model="applyEcontractForm.pwd" show-password placeholder="请输入六位数字密码">
                </el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="请再次输入签章密码：" prop="confirmpwd" :label-position="labelPosition" label-width="210px">
              <el-col :span="16">
                <el-input type="number" maxlength="6"
                  onKeypress="return(/^[0-9]*$/.test(String.fromCharCode(event.keyCode)))"
                  v-model="applyEcontractForm.confirmpwd" show-password placeholder="请再次输入六位数字密码"></el-input>
              </el-col>
            </el-form-item>
            <!--

          <el-form-item label=""  prop="checked" :label-position="labelPosition" label-width="210px">
            <el-col :span="16">
              <el-checkbox v-model="applyEcontractForm.checked"><span>我已阅读并同意</span><a style="color: #02A7F0;">《申请数字证书协议》</a></el-checkbox>
            </el-col>
          </el-form-item>-->
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitApply">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog :visible.sync="dialogVisible1">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>

        <!--重置密码dialog-->
        <el-dialog title="重置密码" :visible.sync="resetPwdDialogVisible" append-to-body width="30%">
          <el-form class="econtract-resetForm" label-position="right" :model="resetPwdForm" :rules="resetPwdRules"
            ref="resetPwdForm">
            <el-form-item label="手机号码：" :label-width="formLabelWidth" prop="account">
              <span>{{ phone }}</span>
            </el-form-item>
            <el-form-item label="请输入验证码：" :label-width="formLabelWidth" prop="code">
              <el-input v-model="resetPwdForm.code" autocomplete="off" style="width: 50%;"></el-input>
              <el-button :disabled="msgKey" type="primary" @click="getCode">{{ msgText }}</el-button>
            </el-form-item>
            <el-form-item label="请设置新密码：" :label-width="formLabelWidth" prop="pwd">
              <el-input type="number" maxlength="6"
                onKeypress="return(/^[0-9]*$/.test(String.fromCharCode(event.keyCode)))" v-model="resetPwdForm.pwd"
                autocomplete="off" show-password placeholder="请输入六位数字密码"></el-input>
            </el-form-item>
            <el-form-item label="请再次输入新密码：" :label-width="formLabelWidth" prop="pwd2">
              <el-input type="number" maxlength="6"
                onKeypress="return(/^[0-9]*$/.test(String.fromCharCode(event.keyCode)))" v-model="resetPwdForm.pwd2"
                autocomplete="off" show-password placeholder="请再次输入六位数字密码"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="resetPwdDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitResetPwd">确 认</el-button>
          </div>
        </el-dialog>

        <!-- /查看签章dialog -->
        <el-dialog title="查看" :visible.sync="calibrationDialog" width="500px" :modal="false"
          class="calibrationForm excelBox checkForm">
          <el-form :model="viewSignatureForm" :rules="rules">
            <el-form-item label="公章：" prop="authUrlId">
              <div v-loading="uploading">
                <img class="companyInfo-upload-image" :src="'data:image/png;base64,' + viewSignatureForm.imgStr" />
              </div>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
          </div>
        </el-dialog>
      </div>
      <el-form size="small" label-position="right" :inline="true" style="padding-left: 10px;padding-right: 10px;">
        <el-row :span="24">
          <!-- <el-form-item >
          <el-radio-group v-model="search.status" size="small" @change="changeCategory">
            <el-radio-button
              v-for="(item,key,index) in esignatureState"
              :key="index"
              :label="item.value"
            >{{item.label}}</el-radio-button>
          </el-radio-group>
        </el-form-item><br/> -->

          <el-form-item label="合同编号:">
            <el-input v-model="search.contractNo" placeholder="合同编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="岗位名称:">
            <el-input v-model="search.servicesName" placeholder="岗位名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="员工姓名:">
            <el-input v-model="search.userName" placeholder="员工姓名" clearable></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="search.searchStatus" placeholder="请选择筛选条件">
              <el-option v-for="item in searchTypeList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="monthData" type="daterange" range-separator="至" start-placeholder="请选择开始日期"
              end-placeholder="请选择结束日期" value-format="yyyy-MM-dd hh:mm:ss" format="yyyy-MM-dd"
              @change="getDateValueStime">
            </el-date-picker>
          </el-form-item>
          <tool-tip></tool-tip>
          <div class="searchBtn">
            <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜 索</el-button>
            <el-button size="small" icon="el-icon-delete" @click="handleClear">清 空</el-button>
          </div>
        </el-row>
      </el-form>
      <content-index ref="waiting" @refresh="handleClear"></content-index>
    </basic-container>
  </div>
</template>
<script>
import contentIndex from './contentIndex'//待签发
import {
  apply,
  applyStatus,
  getCode,
  resetPwd,
  viewSignature,

} from "@/api/manage/econtract";
import { getTemplate } from "@/api/resource/template";
import httpRequest from "./httpRequest";
import { mapGetters } from 'vuex'
export default {
  components: {
    contentIndex,
  },
  data() {
    const validatePwd = (rule, value, callback) => {
      if (value != this.resetPwdForm.pwd) {
        callback(new Error('两次输入密码不一致'));
      }
      else {
        callback();
      }
    };
    const validPwdNums = (rule, value, callback) => {
      if (value.length != 6 || isNaN(Number(value))) {
        callback(new Error('请输入6位数的数字密码'));
      }
      else {
        callback();
      }
    }
    const apply_validPwdNums = (rule, value, callback) => {
      if (value.length != 6 || isNaN(Number(value))) {
        callback(new Error('请输入6位数的数字密码'));
      }
      else {
        callback();
      }
    }
    const apply_validatePwd = (rule, value, callback) => {
      if (value != this.applyEcontractForm.pwd) {
        callback(new Error('两次输入密码不一致'));
      }
      else {
        callback();
      }
    };
    /* const validateChecked=(rule,value,callback)=>{
       if(!value){
         callback(new Error('请先阅读并同意《申请数字证书协议》'))
       }
       else{
         callback();
       }
     }*/
    return {
      //申请签章校验
      ruleValidate: {
        authUrlId: [
          {
            required: true, message: '请上传电子签章申请表', trigger: 'blur'
          }
        ],
        pwd: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            validator: apply_validPwdNums, trigger: 'blur'
          }
        ],
        confirmpwd: [
          {
            required: true, message: '请输入确认密码', trigger: 'blur'
          },
          {
            validator: apply_validatePwd, trigger: 'blur'
          }
        ],
        /*checked:[
          {
            validator:validateChecked,trigger:'blur'
          },
        ]*/
      },
      //重置密码校验
      resetPwdRules: {
        code: [
          {
            required: true, message: '请输入验证码', trigger: 'blur'
          }
        ],
        pwd: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            validator: validPwdNums, trigger: 'blur'
          }
        ],
        pwd2: [
          {
            required: true, message: '请输入确认密码', trigger: 'blur'
          },
          {
            validator: validatePwd, trigger: 'blur'
          }
        ]

      },
      phone: '',
      formLabelWidth: '150px',
      search: {
        // status:''
      },
      msgTime: 120,
      resetPwdDialogVisible: false,
      resetPwdForm: {},
      viewSignatureForm: {},
      calibrationDialog: false,
      msgKey: false,
      msgText: '获取验证码',
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      monthData: '',
      monthDataEtime: '',
      rules: {
        authUrlId: [
          {
            required: true,
            message: "请上传电子签章申请表",
            trigger: "change",
          },
        ],
      },
      imageUrl: "/manage/img/idcard-h.png",
      putFile: '',
      fileUrl: '',
      econtractStatus: '',
      loading: false,
      uploading: false,
      dialogVisible: false,
      labelPosition: 'right',
      applyEcontractForm: {
        pwd: ''
      },
      dialogImageUrl: '',
      dialogVisible1: false,
      disabled: false,
      searchTypeList: [
        {
          label: '员工签署日期',
          value: 0
        },
        {
          label: '企业签署日期',
          value: 1
        },
        {
          label: '合同生效日期',
          value: 2
        },
        {
          label: '合同失效日期',
          value: 3
        },
      ]
    };
  },
  methods: {
    //页面加载执行
    onLoad() {
      this.econtractStatus.sealOn = 0;//电子合同是否启用，0=未启用
      //applyStatus
      // applyStatus().then((res) => {
      //   this.econtractStatus = res.data.data;
      //   //this.econtractStatus.sealOn = 1
      // });
    },
    /**上传图片**/
    httpRequest,
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.applyEcontractForm.authUrlId = URL.createObjectURL(file.raw);
      this.uploading = false;
    },
    beforeAvatarUpload(file) {

      const isJPG = ["image/png", "image/jpeg", "image/svg+xml", "image/gif"].indexOf(file.type) != -1;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传图片格式不正确');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      this.fileUrl = file;
      return isJPG && isLt2M;
    },
    //下载电子签章表
    handleDownload() {
      getTemplate('sqb').then(res => {
        window.open(res.data.data)
      })
    },
    handleSearch() {
      //this.search.belong = this.monthLast;
      // if(this.monthData){
      //   this.search.stime=this.monthData[0];
      //   this.search.etime=this.monthData[1];
      // }

      this.$refs.waiting.onLoad(this.page, this.search);
      // if (this.search.status === 0) {
      //   this.$refs.waiting.onLoad(this.page, this.search);
      // } else if (this.search.status === 1) {
      //   this.$refs.onging.onLoad(this.page, this.search);
      // } else if (this.search.status === 2) {
      //   this.$refs.finished.onLoad(this.page, this.search);
      // }
    },
    handleClose(done) {
      done();
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => {});
    },
    changeCategory() {
      this.search = {
        // status: this.search.status,
        contractNo: '',
        companyName: '',
        servicesName: '',
        userName: '',
        stime: '',
        stimeEnd: '',
        etime: '',
        etimeEnd: ''
      }
      this.timeValue = '';
      this.monthData = '';
      this.monthData1 = '';
      this.monthDataEtime = '';
      this.monthLast = '';
    },
    handleClear() {
      //let curStatus = this.search.status;
      this.search = {
        // status: curStatus,
        contractNo: '',
        companyName: '',
        servicesName: '',
        userName: '',
        stime: '',
        stimeEnd: '',
        etime: '',
        etimeEnd: ''
      }
      this.timeValue = '';
      this.monthData = '';
      this.monthData1 = '';
      this.monthDataEtime = '';
      this.monthLast = '';
      this.handleSearch()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          return false;
        }
      });
    },
    submitApply() {
      this.$refs.applyEcontractForm.validate(valid => {
        let fd = new FormData();
        fd.append('file', this.fileUrl);
        fd.append('password', this.applyEcontractForm.pwd);
        if (valid) {
          apply(
            fd
          )
            .then(() => {
              this.onLoad()
            })
            .catch(() => {
              this.loading = false;
            });
          this.dialogVisible = false;
        }
      })

    },
    handelResetPwd() {
      this.phone = this.userInfo.account;
      var pat = /(\d{3})\d*(\d{4})/;
      this.phone = this.phone.replace(pat, '$1****$2');
      this.resetPwdDialogVisible = true;
      this.resetPwdForm = {};
    },
    /*获取验证码*/
    getCode() {
      this.msgKey = true;
      this.msgText = "发送中...";
      getCode(this.userInfo.account)
        .then(() => {
          this.msgText = "剩余" + 120 + "s";
          this.msgKey = true;
          const time = setInterval(() => {
            this.msgTime--;
            this.msgText = "剩余" + this.msgTime + "s";
            if (this.msgTime <= 0) {
              this.msgTime = 120;
              this.msgText = "重新获取";
              this.msgKey = false;
              clearInterval(time);
            }
          }, 1000);
        })
        .catch(() => {
          this.msgText = "重新获取";
          this.msgKey = false;
        });

    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    submitResetPwd() {
      this.$refs.resetPwdForm.validate(valid => {
        if (valid) {
          resetPwd(this.userInfo.account, this.resetPwdForm.pwd, this.resetPwdForm.code).then(() => {
            this.$message.success('密码重置成功');
            this.resetPwdDialogVisible = false;
          })
            .catch((err) => {
              this.$message.error(err);
            })
        }
      })
    },
    //查看签章
    handelViewSignature() {
      viewSignature().then(res => {
        this.viewSignatureForm.imgStr = res.data.data;
        this.calibrationDialog = true;
      })
      // window.open('http://jlfiles.oss-cn-zhangjiakou.aliyuncs.com/upload/20210320/b89d611d7f371c8f08d08edc79cfd4b2.pdf')
    },
    //
    handelEnableSignature() {
      this.applyEcontractForm = {}
      this.imageUrl = "/manage/img/idcard-h.png"
      this.dialogVisible = true;
    },
    getDateValueStime(val) {
      this.search.stime = val[0];
      this.search.etime = val[1];
    },
  },
  created() {
    this.onLoad();
  },
  computed: {
    ...mapGetters(['userInfo', 'permission'])
  }
};
</script>
<style scoped>
* {
  margin: 0;
  padding: 0;
}

.el-form--inline .el-form-item {
  margin-right: 10px;
}

.companyInfo-upload-image {
  height: 200px;
  width: 200px;
}

.contract-signature-image {
  width: 150px;
  height: 100px;
}

.econtract {
  background: #ffffff;
  margin-left: 10px;
  font-size: 14px;
}

.econtract-header {
  margin-bottom: 10px;
}

.econtract-header /deep/ .el-card__body {
  padding: 5px 16px !important;
}

.header {
  clear: both;
  height: 50px;
  margin: 0;
  padding: 0;
  padding-left: 10px;
}

.header li {
  list-style-type: none;
  float: left;
  margin-right: 50px;
  line-height: 50px;
}

.header li h3 {
  margin-left: 10px;
  font-size: 18px;
}

.header li a {
  color: #409EFF;
  margin-right: 20px;
  cursor: pointer;
}

.el-button {
  padding: 8px 10px;
  margin-left: 10px;
}

.applyEcontract /deep/ .el-input__inner {
  width: 210px;
  height: 30px;
}

.uploadEcontractBtn {
  cursor: pointer;
}

.uploadEcontractBtn:hover {
  color: #409EFF;
}

.econtract-resetForm /deep/ .el-form-item__content {
  text-align: left;
}

.searchBtn {
  display: inline-block;
}

.econtract-resetForm .el-form-item {
  margin-bottom: 30px !important;
}

.demo-ruleForm .el-form-item {
  margin-bottom: 20px !important;
}</style>
