<template>
  <div class="app-container">

    <van-nav-bar left-arrow fixed placeholder @click-left="$router.push({path:'/contracted/index'})" >
      <template #title>
        <div class="tb_main">
          {{ $route.query.deptName }}
        </div>
      </template>
    </van-nav-bar>

    <div class="tap_block">
      <p @click="$router.push({path:'/contracted/village/contractor', query: { deptId: $route.query.deptId, deptName: $route.query.deptName }})">承包方</p>
      <p class="active">发包方</p>
      <p @click="$router.push({path:'/contracted/village/massif', query: { deptId: $route.query.deptId, deptName: $route.query.deptName }})">地块</p>
      <p @click="$router.push({path:'/contracted/village/map', query: { deptId: $route.query.deptId, deptName: $route.query.deptName }})">地图</p>
    </div>

    <div class="list_main">
      <van-form ref="formData">
        <van-field v-model="form.fbfbm" label="代码：" placeholder="<自动生成>" :border="false" input-align="right" label-width="auto" :disabled="true" maxlength="14">
          <!-- <template #button v-if="!isDisabled">
            <van-button size="mini" type="primary" native-type="button" @click="generateCode">生成代码</van-button>
          </template> -->
        </van-field>
        <van-field v-model="form.fbfmc" label="名称：" placeholder="请输入名称" required :rules="[{ required: true }]" :border="false" input-align="right" label-width="auto" maxlength="50" />
        <van-field v-model="form.fbffzrxm" label="负责人姓名：" placeholder="请输入负责人姓名" required :rules="[{ required: true }]" :border="false" input-align="right" label-width="auto" maxlength="50" />
        <van-field v-model="credentialTypeText" label="证件类型："
          placeholder="请选择证件类型"
          required
          :rules="[{ required: true }]"
          :border="false"
          input-align="right"
          right-icon="arrow-down"
          label-width="auto"
          readonly
          clickable
          @click="showCredentialType = true"
        />
        <van-popup v-model="showCredentialType" position="bottom">
          <van-picker
            show-toolbar
            :columns="credentialTypeOptions"
            value-key="dictLabel"
            @confirm="onConfirmTypeOptions"
            @cancel="showCredentialType = false"
          />
        </van-popup>
        <van-field v-model="form.fzrzjhm" label="证件号码：" placeholder="请输入证件号码" required :rules="[{ required: true }]" :border="false" input-align="right" label-width="auto" maxlength="30" />
        <van-field v-model="form.lxdh" label="联系电话：" placeholder="请输入联系电话" required :rules="[{ required: true }]" :border="false" input-align="right" label-width="auto" maxlength="15" />
        <van-field v-model="form.fbfdz" label="地址：" placeholder="请输入地址" required :rules="[{ required: true }]" :border="false" input-align="right" label-width="auto" maxlength="100" />
        <van-field v-model="form.yzbm" label="邮政编码：" placeholder="请输入邮政编码" required :rules="[{ required: true }]" :border="false" input-align="right" label-width="auto" maxlength="6" />
        <van-field v-model="form.fbfdcjs" label="调查记事：" placeholder="请输入调查记事" type="textarea" rows="3" required :rules="[{ required: true }]" :border="false" input-align="right" label-width="auto" maxlength="200" />
        <van-field label="签字图片：" readonly :border="false" label-width="auto" />
        <img :src="'/api'+form.fbfdcqz" width="100%" alt="" />
      </van-form>
      <div class="btn_main" v-if="taskStatus === '2'">
        <p class="btn" @click="submitForm">保存</p>
        <p class="btn1" @click="handleSign">签字</p>
      </div>
    </div>

    <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>

  </div>
</template>
<script>
  import Cookies from "js-cookie";
  import { listFbf, addFbf, updateFbf, manualSignature, generateEmployerCode } from "@/api/contracted/fbf";
  import vueEsign from "vue-esign";
  import $ from "jquery";

  export default {
    name: "contractedVillageContractor",
    components: {
      vueEsign
    },
    data() {
      return {
        form: {},                         // 发包方信息表单
        // isDisabled: false,                // 是否禁用
        credentialTypeOptions: [],        // 证件类型字典
        credentialTypeText: null,         // 证件类型标签名
        showCredentialType: false,        // 控制证件类型字典弹出层的显示和隐藏
        taskStatus: null,                 // 调查任务的完成状态：1表示已完成，2表示未完成

        // 控制签字面板的显示和隐藏
        showSignPopup: false,
        height: null,
        //电子签名
        signature: {
          lineWidth: 6, // 画笔的线条粗细
          lineColor: "#000000", // 画笔的颜色
          bgColor: "", // 画布的背景颜色
          resultImg: "", // 最终画布生成的base64图片
          isCrop: false, // 是否裁剪，在画布设定尺寸基础上裁掉四周空白部分
        },
      };
    },
    created() {
      this.taskStatus = Cookies.get('taskStatus');
      this.height = window.screen.height * 1.28 - 20;
      this.getDicts("cert_type").then(response => {
        this.credentialTypeOptions = response.data;
      });
      this.getDetail();
    },
    methods: {
      getDetail() {
        listFbf({deptId: this.$route.query.deptId}).then(response => {
          if (response.rows.length > 0) {
            this.form = response.rows[0];
            // this.isDisabled = true;
            this.$nextTick(() => {
              this.credentialTypeText = this.selectDictLabel(this.credentialTypeOptions, this.form.fzrzjlx);
            });
          } else {
            this.resetForm();
            // this.isDisabled = false;
          }
        });
      },
      /* generateCode() {
        generateEmployerCode({deptId: this.$route.query.deptId}).then(response => {
          this.$set(this.form, 'fbfbm', response.data);
        });
      }, */
      onConfirmTypeOptions(value){
        this.form.fzrzjlx = value.dictValue;
        this.credentialTypeText = value.dictLabel;
        this.showCredentialType = false;
      },
      submitForm() {
        this.$refs.formData.validate().then(() => {
          if (this.form.id) {
            updateFbf(this.form).then(response => {
              if (response.code == 200) {
                this.$toast({
                  icon: 'success',
                  message: '保存成功',
                  duration:"1000",
                });
              }
            });
          } else {
            this.form.deptId = this.$route.query.deptId;
            addFbf(this.form).then(response => {
              if (response.code == 200) {
                this.$toast({
                  icon: 'success',
                  message: '保存成功',
                  duration:"1000",
                  onClose: () => {
                    this.getDetail();
                  }
                });
              }
            });
          }
        }).catch(() => {
          this.$notify({ type: 'danger', message: '请填写完整的表单项' });
        });
      },
      resetForm() {
        this.form = {
          deptId: null,
          fbfbm: null,
          fbfmc: null,
          fbffzrxm: null,
          fzrzjlx: '1',
          fzrzjhm: null,
          lxdh: null,
          fbfdz: null,
          yzbm: null,
          fbfdcjs: null,
          fbfdcqz: null
        };
        this.credentialTypeText = '居民身份证';
      },
      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('deptId', this.$route.query.deptId);
            manualSignature(param).then(response => {
              if (response.code === 200) {
                this.$toast({
                  icon: 'success', // 找到自己需要的图标
                  message: '签字成功',
                  duration: "1000",
                  onClose: () => {
                    this.showSignPopup = false;
                    this.form.fbfdcqz = response.data;
                  }
                });
              }
            });
          })
          .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
        })
      },
    },
  };
</script>
<style scoped lang="scss">

  .app-container{
    background: #fff url("../../../../../static/images/contracted/contracted_index_bg.png") no-repeat center;
    background-size: 100% 100%;
    height: 100vh;
    padding: 0 4vw;
    overflow: hidden;
  }

  /deep/ .van-nav-bar{
    background: transparent;
  }

  /deep/ .van-nav-bar .van-icon{
    color: #000000;
  }

  /deep/ .van-hairline--bottom::after{
    border: none;
  }

  /deep/ .van-search__content{
    background: rgba(255,255,255,.5);
  }
  /deep/ .van-search{
    padding: 0;
    flex: 1;
  }

  /deep/ .van-ellipsis{
    overflow: initial;
  }

  /deep/ .van-field--disabled .van-field__label {
    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;
  }

  .tap_block{
    width: 100%;
    display: flex;
    justify-content: space-between;
    background: #ebfaf2;
    padding: 2PX 4PX;
    border-radius: 10PX;
    margin-top: 1vh;
    .active{
      background-image: linear-gradient(to right,#c6fe8b,#48e5a2);
      box-shadow: 0 0 10PX #cccccc;
      color: #333333;
    }
    p{
      width: 25%;
      text-align: center;
      padding: 5PX 0;
      border-radius: 10PX;
      color: #666666;
    }
  }

  .search_main{
    display: flex;
    margin-top: 2vh;
    .search_btn{
      background: rgba(255,255,255,.5);
      width: 25%;
      border-radius: 50PX;
      margin-left: 10PX;
      padding: 2PX;
      .active{
        background-image: linear-gradient(to right,#c6fe8b,#48e5a2);
        color: #333333;
        border-radius: 50PX;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
      }
    }
  }

  .second_tap{
    display: flex;
    align-items: center;
    margin-top: 1vh;
    p{
      background: #dbf1ea;
      border: 1px solid #cdcdcd;
      color: #5f5f5f;
      padding: 5PX 15PX;
      margin-right: 3vw;
      border-radius: 50PX;
    }
    .active{
      background: #99eecb;
      border-color: #48e5a2;
      color: #333333;
    }
  }

  .list_main{
    margin-top: 2vh;
    overflow-y: scroll;
    text-align: center;
    background: #ffffff;
    border-top-left-radius: 10PX;
    border-top-right-radius: 10PX;
    height: 88vh;
    .btn_main{
      .btn1{
        background-image: linear-gradient(to right,#ffd88e,#fc8a0e);
        box-shadow: 0 0 10PX #cccccc;
        padding: 10PX 0PX;
        border-radius: 50PX;
        display: inline-block;
        width: 30%;
        margin-top: 2vh;
        margin-left: 2vw;
      }
      .btn{
        background-image: linear-gradient(to right,#c6fe8b,#48e5a2);
        box-shadow: 0 0 10PX #cccccc;
        padding: 10PX 0PX;
        border-radius: 50PX;
        display: inline-block;
        width: 30%;
        margin-top: 2vh;
      }
    }

  }

  .mapBox{
    width: 94%;
    height: 50vw;
    background-image: linear-gradient(to right,#c6fe8b,#48e5a2);
    border-radius: 10PX;
    margin: 2vh auto;
  }

  .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>
