<template>
  <div>
    <el-form 
      ref="checkForm"
      label-width="100px" 
      :model="checkForm"
    >
      <el-row>
        <el-col
          v-for="(item, $index) in formData"
          v-show="filterBlock(item.parent,item.display_expression)"
          :key="$index"
          :span="12"
        >
          <el-form-item
            v-if="item.field_type === 'string'"
            :label="item.field_name"
          >
            <el-input
              v-model="checkForm[item.field_key]"
              placeholder="请输入"
              @input="keyChange(item.field_key)"
            />
          </el-form-item>
          <el-form-item
            v-else-if="item.field_type === 'int'"
            :label="item.field_name"
          >
            <el-input
              v-model="checkForm[item.field_key]"
              type="number"
              placeholder="请输入"
              @input="keyChange(item.field_key)"
            />
          </el-form-item>
          <el-form-item
            v-else-if="item.field_type === 'float'"
            :label="item.field_name"
          >
            <el-input
              v-model="checkForm[item.field_key]"
              type="number"
              placeholder="请输入"
              @input="keyChange(item.field_key)"
            />
          </el-form-item>
          <el-form-item
            v-else-if="item.field_type === 'date'"
            :label="item.field_name"
          >
            <el-date-picker
              v-model="checkForm[item.field_key]"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              @change="keyChange(item.field_key)"
            />
            <!--</el-date-picker>-->
          </el-form-item>
          <el-form-item
            v-else-if="item.field_type === 'datetime'"
            :label="item.field_name"
          >
            <el-date-picker
              v-model="checkForm[item.field_key]"
              type="datetime"
              placeholder="选择日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
              @change="keyChange(item.field_key)"
            />
            <!--</el-date-picker>-->
          </el-form-item>
          <el-form-item
            v-else-if="item.field_type === 'select'"
            :label="item.field_name"
          >
            <el-select
              v-model="checkForm[item.field_key]"
              style="width: 100%"
              placeholder="请选择"
              @change="keyChange(item.field_key)"
            >
              <el-option
                v-for="item1 in item.field_choice"
                :key="item1"
                :label="item1"
                :value="item1"
              />
              <!--</el-option>-->
            </el-select>
          </el-form-item>
          <el-form-item
            v-else-if="item.field_type === 'selects'"
            :label="item.field_name"
          >
            <el-select
              v-model="checkForm[item.field_key]"
              style="width: 100%"
              multiple
              placeholder="请选择"
            >
              <el-option
                v-for="item1 in item.field_choice"
                :key="item1"
                :label="item1"
                :value="item1"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="hasPicture">
        <el-form-item label="图表">
          <div>
            <img id="canvasImg" src="./../../assets/glass.png" style="width:500px;height: 300px;display: none">
            <div style="position: relative;display: flex;flex-direction: column;
                 border: 1px solid #DCDFE6;">
              <canvas id="canvas" width="500" height="300">
                您的浏览器不支持绘图，请升级或更换浏览器！
              </canvas>
              <input type="text" value="" class="hide" id="txt" placeholder="请输入文字">
              <textarea class="hide" id="word" cols="15" rows="5" placeholder="请输入文字" autofocus></textarea>
              <input id="inputV" type="hidden" value="1">
              <div class="canvasBtnWrap">
                <div class="canvasBtn" @click="error1">标记</div>
                <div class="canvasBtn" @click="word1()">文字</div>
                <div class="canvasBtn" @click="back()">回退</div>
                <div class="canvasBtn" @click="saveTu()">保存</div>
              </div>
              <div id="res"></div>
            </div>
          </div>
        </el-form-item>
      </el-row>
      <div style="text-align: right">
      <el-button type="primary" @click="judgeForm">
      合格验证
      </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { upFile } from "@/api/file";
  let preDrawAry = [];
  export default {
    name: "index",
    props: {
      results:{
        type:Array,
        default: () => {
          return []
        }} ,
      formID: {
        type:Number,
        default:0
      },
      hasPicture:{
        type:Boolean,
        default:false
      }
    },
    mounted() {
      let that = this;
      this.form = this.formID;
      // debugger;
      // console.log(this.results);
      this.formData=this.results;
      this.formData=[...this.formData];
      for(let i=0;i<this.results.length;i++){
        let key = this.results[i].field_key;
        that.checkForm[key]='';
        that.$set(that.checkForm,key,'')
      }
      // debugger;
      // console.log(that.checkForm);
      let listJudge = this.formData.filter(item => {
        return item.need_judge === true;
      });
      listJudge.forEach(item => {
        let obj = new Object();
        obj = item;
        obj.judge = false;
        that.judgeList.push(obj)
      });
      setTimeout(function(){
        that.canvasInit();
      },500);
    },
    data(){
      return{
        checkForm:{},
        canvas:null,
        ctx:null,
        myCanvas_rect:null,
        Txt:null,
        word:null,
        widths:0,
        heights:0,
        lineW:3,
        colorF:"#e42343",
        imgData:'',
        canvasImg:'',
        formData:[],//表单数组
        judgeList:[],//判定数组
      }
    },
    methods:{
      filterBlock(parent,rule){
        // debugger;
        let that = this;
        if(parent!==''&&parent!==null&&parent!==undefined){
          if(rule!==''&&rule!==null&&rule!==undefined){
            let reg = /\{(.+?)\}/g;
            //let str = rule.replace(temp,'').replace('$','');//=='有'
            //let y = that.checkForm[key];
            if(rule.indexOf('||')>-1||rule.indexOf('&&')>-1){
              let tam = '', arr = [];
              if(rule.indexOf('||')>-1){
                arr = rule.split('||');
              }else{
                arr = rule.split('&&');
              }
              for (let i = 0;i<arr.length;i++){
                //获取判断依据
                let a = '';
                a = arr[i].replace(/`/g,'');
                a = '`'+ a+'`';
                let tem =a.match(reg)[0];
                let ky = tem.replace(/\{|\}/g, '');//qipao
                if(that.checkForm[ky]){
                  //替换变量
                  a = a.replace(ky, 'yyy');
                  let yyy = "'"+that.checkForm[ky]+"'";
                  if(eval(eval( a))){
                    tam += 'true';
                  }else{
                    tam += 'false';
                  }
                }else{
                  tam += 'false';
                }
              }
              let rea = true;
              if(rule.indexOf('||')>-1){
                if( tam.indexOf('true')>-1){
                  rea = true;
                }else{
                  rea = false;
                }
              }else{
                if( tam.indexOf('false')>-1){
                  rea = false;
                }else{
                  rea = true;
                }
              }
              return rea;
            }else{
              let temp =rule.match(reg)[0];
              let key = temp.replace(/\{|\}/g, '');//qipao
              let  a = rule.replace(key, 'yy');
              a = a.replace(key, 'yy');
              let yy = "'"+that.checkForm[key]+"'";
              return eval(eval(a));
              // return eval("'"+y+"'"+str);
            }
          }else{
            return false;
          }
        }else{
          return true;
        }
      },
      keyChange(key){
        key;
        this.$forceUpdate();
       /* debugger;
        let y = this.checkForm[key];
        this.$set(this.checkForm,key,y);*/
        // this.filterBlock();
      },
      /*  base64ToFile  */
      canvasInit(){
        let that = this;
        preDrawAry = [];
        that.canvas = document.getElementById('canvas');
        that.ctx = that.canvas.getContext('2d');
        that.myCanvas_rect = that.canvas.getBoundingClientRect();
        that.Txt = document.getElementById('txt');
        that.word = document.getElementById('word');
        that.widths = that.myCanvas_rect.width;
        that.heights = that.myCanvas_rect.height;
        setTimeout(function(){
          that.draw();
        },500);
      },
      draw(){
        let canvasImg = document.getElementById("canvasImg");
        canvasImg.style.width = '500px';
        canvasImg.style.height = '300px';
        this.ctx.drawImage(canvasImg,0,0,500,300);
      },
      // 叉号
      error1(){
        let canvas1 = document.getElementById('canvas');
        let ctx1 = canvas1.getContext('2d');
        this.Txt.style.display="none";
        document.getElementById('word').style.display="none";
        ctx1.closePath();
        canvas1.onmousedown=function () {
          this.imgData= ctx1.getImageData(0,0,canvas1.width,canvas1.height);
          preDrawAry.push(this.imgData);
          ctx1.beginPath();
          ctx1.strokeStyle = "#e42343";
          ctx1.lineWidth = "3";
          ctx1.lineJoin="round";
        };
        //鼠标按下的位置
        canvas1.onmouseup=function (ev) {
          let oldX = ev.offsetX;
          let oldY = ev.offsetY;
          ctx1.moveTo(oldX,oldY);
          ctx1.lineTo(ev.offsetX+10,ev.offsetY+10);
          ctx1.moveTo(ev.offsetX+10,ev.offsetY);
          ctx1.lineTo(ev.offsetX,ev.offsetY+10);
          ctx1.stroke();
        };
        this.ctx.closePath();
      },
      // 文字先写字
      text(){
        let canvas2 = document.getElementById('canvas');
        let ctx2 = canvas2.getContext('2d');
        let Txt2 = document.getElementById('txt');
        Txt2.style.display="block";
        document.getElementById('word').style.display="none";
        ctx2.font="16px Microsoft Yahei";
        canvas2.onmousedown=function (ev) {
          this.imgData=ctx2.getImageData(0,0,canvas2.width,canvas2.height);
          preDrawAry.push(this.imgData);
          var v = Txt2.value;
          //            console.log(v);
          if (v != '') {
            var oldX = ev.offsetX;
            var oldY = ev.offsetY;
            // console.log(oldX,oldY);
            ctx2.moveTo(oldX,oldY);
            canvas2.onmouseup=function () {
              ctx2.fillStyle=this.colorF;
              ctx2.fillText(v,oldX,oldY);
              canvas2.TextAutoLine(v,canvas2,oldX,oldY,20);
              // Txt.value = "";
              Txt2.style.display="none";
            }
          }
        }
      },

      // 文字
      word1(){
        let canvas3 = document.getElementById('canvas');
        let ctx3 = canvas3.getContext('2d');
        let Txt3 = document.getElementById('txt');
        let word3 = document.getElementById('word');
        Txt3.style.display="none";
        ctx3.font="16px Microsoft Yahei";
        canvas3.onmousedown=function () {
          ctx3.closePath();
        }
        canvas3.onmouseup=function (ev) {
          var inputV= document.getElementById('inputV').value;
          if(inputV == 1){
            document.getElementById('word').focus();
            //               console.log(ev.offsetX,ev.offsetY);
            var oldX = ev.offsetX;
            var oldY = ev.offsetY;
            word3.style.display="block";
            word3.style.left=oldX+'px';
            word3.style.top =oldY+'px';

            word3.onblur=function () {
              let v = word3.value;
              if(v != '' && v != ' '){
                this.imgData=ctx3.getImageData(0,0,canvas3.width,canvas3.height);
                let img = ctx3.getImageData(0,0,canvas3.width,canvas3.height);
                // debugger;
                preDrawAry.push(img);
                ctx3.moveTo(oldX,oldY);
                ctx3.fillStyle="#e42343";
                let lineWidth = 0;
                let canvasWidth = canvas3.width;
                let lastSubStrIndex= 0;
                for(let i=0;i<v.length;i++){
                  lineWidth+=ctx3.measureText(v[i]).width;
                  if(lineWidth>canvasWidth-oldX){
                    ctx3.fillText(v.substring(lastSubStrIndex,i),oldX,(oldY+10));
                    oldY+=20;
                    lineWidth=0;
                    lastSubStrIndex=i;
                  }
                  if(i==v.length-1){
                    ctx3.fillText(v.substring(lastSubStrIndex,i+1),oldX,(oldY+10));
                  }
                }
                inputV ="2";
                word3.value = "";
              }
            }
          }
        }
      },
      // 文字过长超出换行toDataURL()
      canvasTextAutoLine(str,canvas,initX,initY,lineHeight){
        let ctx = canvas.getContext("2d");
        let lineWidth = 0;
        let canvasWidth = canvas.width;
        let lastSubStrIndex= 0;
        for(let i=0;i<str.length;i++){
          lineWidth+=ctx.measureText(str[i]).width;
          if(lineWidth>canvasWidth-initX){
            ctx.fillText(str.substring(lastSubStrIndex,i),initX,initY);
            initY+=lineHeight;
            lineWidth=0;
            lastSubStrIndex=i;
          }
          if(i==str.length-1){
            ctx.fillText(str.substring(lastSubStrIndex,i+1),initX,initY);
          }
        }
      },
      // 撤销
      back(){
        this.word.style.display="none";
        this.Txt.style.display="none";
        if(preDrawAry.length>0) {
          var popData = preDrawAry.pop();
          this.ctx.putImageData(popData, 0, 0);
        }
      },
      // 回退一次
      put(){
        this.ctx.putImageData(this.imgData,0,0);
      },
      //保存
      saveTu(){
        this.word.style.display="none";
        this.Txt.style.display="none";
        let canvas = document.getElementById('canvas');
        let image = new Image();
        image = canvas.toDataURL('image/png');
        this.canvasImg = image;
        let file = this.base64ToFile(image);
        let formData = new FormData();
        formData.append('file', file);
        upFile(formData).then((res) => {
          res;
          // console.log(res);
        })
      },
      base64ToFile(baseUrl) {
        let arr = baseUrl.split(',');
        // let type = arr[0].match(/:(.*?);/)[1];   // 解锁图片类型
        let bytes = atob(arr[1]); // 解码base64
        let n = bytes .length;
        let bufferArray = new Uint8Array(n);
        while (n--) {
          bufferArray[n] = bytes.charCodeAt(n);
        }
        // let fileOfBlob = new File([bufferArray], new Date()+'.jpg');
        return new File([bufferArray ],'draw.jpg');
      },
      /*  base64ToFile  */
      judgeForm(){
        let that = this ,
          reg = /\{(.+?)\}/g,
          judgeList = this.judgeList;
        for(let i=0;i<judgeList.length;i++){
          let arr = [],str = '';
          let item = judgeList[i].rule_expression.replace(/`/g,'');
          if(item.indexOf('||')>-1){
            arr = item.split('||');
          }else if(item.indexOf('&&')>-1){
            arr = item.split('&&');
          }else{
            arr.push(item);
          }
          //对每个条件进行判定，如果符合，
          for (let i = 0;i<arr.length;i++){
            //获取判断依据
            let a = '`'+ arr[i]+'`';
            let tem =a.match(reg)[0];
            let ky = tem.replace(/\{|\}/g, '');//qipao
            //有值时进行判断
            if(that.checkForm[ky]!==''&&that.checkForm[ky]!==null&&that.checkForm[ky]!==undefined){
              //替换变量
              a = a.replace(ky, 'yyy');
              let yyy = "'"+that.checkForm[ky]+"'";
              // debugger;
              if(eval(eval( a))){
                str += 'true';
              }else{
                str += 'false';
              }
            }
          }
          if(str.indexOf('true')>-1){
            that.judgeList[i].judge = true;
          }else{
            that.judgeList[i].judge = false;
          }
        }
        let real = that.judgeList.filter(item=>{
          return item.judge==true;
        });
        if(real.length>0){
          alert("检验不合格！")
        }else{
          alert("检验合格！")
        }
      },
    }
  }
</script>

<style scoped>
  canvas {
    width:500px!important;
    /*border: 1px solid #000000;*/
    cursor: crosshair;
    margin: auto;
  }

  .canvasBtnWrap {
    display: flex;
    /*flex-direction: column;*/
    /*width: 80px;*/
    /*padding-left: 20px;*/
    justify-content: flex-end;
  }

  .canvasBtn {
    width: 70px;
    height: 35px;
    line-height: 35px;
    border: 1px solid #aaaaaa;
    text-align: center;
    border-radius: 15px;
    margin-right: 10px;
    margin-bottom: 10px;
  }
  .hide {
    display: none;
  }

  #txt {
    position: absolute;
    top: 1%;
    left: 1%;
    width: 150px;
    height: 30px;
    border: 1px solid #e42343;
  }

  #word {
    position: absolute;
    width: 200px;
    height: 70px;
    padding: 0 2px;
    background: none;
    color: #e42343;
    border: 1px dashed #b9b9b9;
  }

  #word::-webkit-input-placeholder {
    color: #e42343;
  }

  #word::-moz-placeholder {
    color: #e42343;
  }

  #word::placeholder {
    color: #e42343;
  }

  #res {
    display: inline-block;
  }
</style>
