<template>
  <div>
    <van-nav-bar left-arrow fixed placeholder @click-left="goBack">
      <template #title>
        <div class="tb_main">
          {{ contractorName }}<p v-if="showBtn"><span class="tb" @click="handleSign">签字完成</span><span class="tb" @click="handleHangUp">异常挂起</span></p>
        </div>
      </template>
    </van-nav-bar>

    <van-popup v-model="showSignPopup" closeable position="right" :style="{ height: '100%' }" >
      <van-cell-group style="width: 100%;height:100%;overflow: hidden;padding-top: 10px;padding-bottom: 10px;">
        <div class="signature-box" @mousedown="canvasTTdown" @touchstart="canvasTTdown">
          <vue-esign
            ref="esign"
            class="mySign"
            :width="500"
            :height="height"
            :isCrop="signature.isCrop"
            :lineWidth="signature.lineWidth"
            :lineColor="signature.lineColor"
            :bgColor.sync="signature.bgColor"
          />
        </div>
        <img src="../../../../assets/images/sunVillage_info/signature_icon_10.png" id="canvasTT" style="position:absolute;top: 50%;left: 50%;transform: translate(-50%,-50%)" alt="">
        <div class="signature-footer">
          <van-button @click="handleReset" class="clearBtn" type="info" plain  size="small">清空画板</van-button>
          <van-button @click="handleGenerate" type="info" size="small">保存签字</van-button>
        </div>
      </van-cell-group>
    </van-popup>

    <van-dialog v-model="showRemark" title="异常挂起原因" show-cancel-button confirmButtonText="保存" cancelButtonText="关闭"
                :before-close="onBeforeClose" @confirm="handleConfirm">
      <van-form ref="remarkForm" class="remarkForm">
        <van-field v-model="remark" label="挂起原因:" type="textarea" rows="4" placeholder="请输入挂起原因" required
                   :rules="[{ required: true }]" input-align="left" label-width="auto" />
      </van-form>
    </van-dialog>

  </div>
</template>
<script>
  import { getDept } from "@/api/contracted";
  import { contractorSignature, hangUp } from "@/api/contracted/cbf";
  import vueEsign from "vue-esign";
  import $ from "jquery";

  export default {
    name: 'contractedVillageHeader',
    props: ['deptId', 'contractorCode', 'contractorName', 'surveyStatus', 'taskStatus'],
    components: {
      vueEsign
    },
    data() {
      return {
        // 控制签字面板的显示和隐藏
        showSignPopup: false,
        height: null,
        //电子签名
        signature: {
          lineWidth: 6, // 画笔的线条粗细
          lineColor: "#000000", // 画笔的颜色
          bgColor: "", // 画布的背景颜色
          resultImg: "", // 最终画布生成的base64图片
          isCrop: false, // 是否裁剪，在画布设定尺寸基础上裁掉四周空白部分
        },
        // 控制异常信息备注提示框的显示和隐藏
        showRemark: false,
        // 异常备注信息
        remark: null,
        // 控制签字按钮和挂起按钮的显示和隐藏
        showBtn: true,
      };
    },
    created() {
      this.height = window.screen.height * 1.28 - 20;
      if (this.taskStatus === '2' && this.surveyStatus !== '3') {
        this.showBtn = true;

      } else {
        this.showBtn = false;
      }
    },
    methods: {
      goBack() {
        getDept(this.deptId).then(response => {
          this.$router.push({path:'/contracted/village/contractor', query: { deptId: this.deptId, deptName: response.data.deptName }});
        });
      },
      handleSign() {
        this.showSignPopup = true;
        this.handleReset();
      },
      canvasTTdown() {
        $('#canvasTT').css('display', 'none');
      },
      // 清空画板
      handleReset() {
        if (this.$refs.esign) {
          this.$refs.esign.reset();
        }
        $('#canvasTT').css('display', 'block')
      },
      // 生成签字图片
      handleGenerate() {
        this.$refs.esign
          .generate() // 使用生成器调用把签字的图片转换成为base64图片格式
          .then((res) => {
            this.signature.resultImg = res;
            let wj = this.dataURLtoBlob(res);
            let param = new FormData()  // 创建form对象
            param.append('file', wj)  // 通过append向form对象添加数据
            param.append('cbfbm', this.contractorCode);
            contractorSignature(param).then(response => {
              if (response.code === 200) {
                this.$toast({
                  icon: 'success', // 找到自己需要的图标
                  message: '签字成功',
                  duration: "1000",
                  onClose: () => {
                    this.showSignPopup = false;
                    this.goBack();
                  }
                });
              }
            });
          })
          .catch((err) => {
            // 画布没有签字时会执行这里提示一下
            this.$toast.fail('请签名后再保存签字');
          });
      },
      dataURLtoBlob(dataurl, filename = 'file') {
        let arr = dataurl.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let suffix = mime.split('/')[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], `${filename}.${suffix}`, {
          type: mime
        })
      },
      // 异常挂起
      handleHangUp() {
        this.showRemark = true;
        this.remark = null;
      },
      // van-dialog 点击confirm事件不自动关闭
      onBeforeClose(action, done) {
        if (action === 'confirm') {
          return done(false);
        } else {
          return done();
        }
      },
      handleConfirm() {
        this.$refs.remarkForm.validate().then(() => {
          let data = new FormData()  // 创建form对象
          data.append('cbfbm', this.contractorCode);
          data.append('remark', this.remark);
          hangUp(data).then(response => {
            if (response.code === 200) {
              this.$toast({
                icon: 'success',
                message: '当前承包方调查已被挂起',
                duration: '2000',
                onClose: () => {
                  this.showRemark = false;
                  this.goBack();
                }
              });
            }
          });
        }).catch(() => {
          this.$notify({ type: 'danger', message: '请填写备注信息' });
        });
      }
    }
  }
</script>
<style scoped lang="scss">

  /deep/ .remarkForm .van-cell__value {
    border: 1px solid #b0b3ba;
    border-radius: 5px;
    padding: 0 15px;
    .van-field__control {
      color: #646566;
    }
  }

  .tb_main{
    position: relative;
    p{
      position: absolute;
      display: inline-block;
      margin-left: 10PX;
    }
  }

  .tb{
    font-size: 12px;
    color: #ff8900;
    background: #daf6e7;
    border: 1px solid #d7be6e;
    padding: 2PX 8PX;
    border-radius: 50PX;
    margin-right: 5PX;
  }

  .signature-box {
    border: 1px dashed #666;
    margin: 2px 20px;
    height: 100%;
    /*canvas{*/
    /*  height: 100%!important;*/
    /*}*/
  }

  .signature-footer {
    transform: rotate(90deg);
    width: auto;
    position: absolute;
    top: 50%;
    left: 0PX;

    .clearBtn {
      margin-left: 15px;
    }
  }
</style>
