<template>
  <view>
    <l-label title="流程名称：">{{ taskParam.taskName }}</l-label>
    <l-label title="当前操作：">{{ typeText }}{{ type === 'sign' ? '' : ` [${taskParam.name}]` }}</l-label>
    <l-organize-picker
      v-if="type === 'sign'"
      v-model="staff"
      title="加签人员"
      placeholder="请选择加签人员"
      type="user"
      required
      arrow
    />

    <!-- 手写签名 canvas 区 -->
    <template v-if="Number(taskParam.isSign) === 1">
      <view class="cu-form-group"><view class="title">手写签名：</view></view>
      <view class="sign-area bg-white">
        <canvas
          v-if="canvas"
          @touchmove="signMove"
          @touchstart="signStart($event)"
          @touchend="signEnd"
          @touchcancel="signEnd"
          disable-scroll="true"
          canvas-id="sign-canvas"
          id="sign-canvas"
          class="sign-canvas"
        ></canvas>
      </view>
      <view class="sign-action padding-bottom text-right">
        <l-button @click="clearSign" color="red" style="margin-right: 15px;">清空签名板</l-button>
      </view>
    </template>

    <l-textarea v-model="remark" :placeholder="`输入${typeText}意见`" title="审核意见：" />
	
	<!-- 弹层 -->
	<l-modal v-model="modal" @close="reviewer = ''" title="指派审核人">
		<l-checkbox-picker @input="(e)=>{reviewer = e}" :value="reviewer" :readonly="false" :range="reviewerList"
			required title="审核人" />
		<l-button @click="userAssign" color="blue" class="block" block>确定指派</l-button>
		<l-button @click="()=>{modal = false;reviewer = ''}" line="blue" class="block margin-top-sm" block>取消</l-button>
	</l-modal>

    <view class="padding margin-top bg-white">
      <l-button @click="submit" class="block" size="lg" color="green" block>提交流程{{ typeText }}</l-button>
    </view>
  </view>
</template>

<script>
import get from 'lodash/get'

let context = null
let touchs = []

export default {
  data() {
    return {
      type: 'sign',
      typeText: '',

      staff: '',
      remark: '',
      taskParam: {},
      canvas: true,
	  
	  modal: false,
	  reviewer: [],
	  reviewerList: [],
	  reviewerListId:'',
	  submitPostData:null,
    }
  },

  async onLoad() {
    await this.init()
  },

  methods: {
    // 页面初始化
    async init() {
      this.taskParam = this.GET_PARAM()
      this.type = this.taskParam.type
      this.typeText = this.taskParam.type === 'sign' ? '加签' : '审核'

      if (Number(this.taskParam.isSign) === 1) {
        this.canvasInit()
      }
    },

    // 初始化签名区 canvas
    canvasInit() {
      this.canvas = true
      context = uni.createCanvasContext('sign-canvas')
      context.setStrokeStyle('#000')
      context.setLineWidth(5)
      context.setLineCap('round')
      context.setLineJoin('round')
      touchs = []
    },
	
	// 指派审核人
	async userAssign() {
		if(!this.reviewer.length){
			this.modal = false
			this.TOAST('请选择审核人')
			return
		}
		// let formdata = new FormData()
		// formdata.append("data",this.taskParam.formreq)
		const res = await this.HTTP_POST('learun/adms/newwf/instance', this.taskParam.formreq, `指派审核人时发生错误`)
		if(!res){
			return
		}
		
		this.submitPostData.auditors = JSON.stringify({[this.reviewerListId]:this.reviewer.toString()})
		delete this.submitPostData.formreq
		// this.submitPostData.auditors[this.reviewerListId] = this.reviewer
		// console.log(this.submitPostData)
		
		uni.showLoading({
			title: '提交中...'
		});
				
		const success = await this.HTTP_POST(
		  this.type === 'sign' ? 'learun/adms/newwf/sign' : 'learun/adms/newwf/auditors',
		  this.submitPostData,
		  `提交[${this.typeText}]时发生错误`
		)
		
		if (!success) {
			uni.hideLoading();
            return
		}
		
		this.EMIT('task-list-change')
		this.NAV_BACK(2)
		uni.hideLoading();
		this.TOAST(`已成功提交${this.typeText}`, 'success')
		
	},
	newguid() {
		return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	},

    // 点击「提交」按钮
    async submit() {
      if (this.type === 'sign' && !this.staff) {
        this.CONFIRM('请补全必填项', '必须指定一个加签用户')
        return
      }

      const postData = {
        operationCode: this.taskParam.code,
        operationName: this.taskParam.name,
        processId: this.taskParam.processId,
        taskId: this.taskParam.taskId,
        des: this.remark,
        formreq: this.taskParam.formreq
      }

      if (this.type === 'sign') {
        postData.userId = this.staff
      } else {
        postData.auditors = this.taskParam.auditors
      }

      // 需要手写签名时，将 canvas 导出为 base64 格式
      // 各个平台写法均不相同，需要注意
      if (Number(this.taskParam.isSign) === 1) {
        // H5 平台，canvasToTempFilePath 的结果直接为画布的 base64
        // #ifdef H5
        const [err, { tempFilePath }] = await uni.canvasToTempFilePath({ canvasId: 'sign-canvas' })
        postData.signUrl = tempFilePath
        // #endif

        // App 平台，canvasToTempFilePath 输出文件，上传后台转为 base64 格式
        // #ifdef APP-VUE
        const [err, { tempFilePath }] = await uni.canvasToTempFilePath({ canvasId: 'sign-canvas' })
        const signBase64 = await this.HTTP_UPLOAD2('/learun/adms/annexes/wxbase64',tempFilePath,{folderId:this.newguid()})
        postData.signUrl = 'data:image/png;base64,' + signBase64
        // #endif

        // 微信小程序，canvasToTempFilePath 输出文件，使用文件管理器以 base64 格式读取文件即可
        // #ifdef MP-WEIXIN
        const [err, { tempFilePath }] = await uni.canvasToTempFilePath({ canvasId: 'sign-canvas' })
        postData.signUrl = 'data:image/png;base64,' + uni.getFileSystemManager().readFileSync(tempFilePath, 'base64')
        // #endif

        // #ifdef MP-ALIPAY
        // 钉钉小程序，context.toTempFilePath 输出文件，上传后台转为 base64 格式
        // #ifdef MP-DINGTALK
        const filePath = await new Promise((res, rej) => {
          context.toTempFilePath({
            success: ({ filePath }) => {
              res(filePath)
            },
            fail: () => {
              rej()
            }
          })
        })

        const signBase64 = await this.HTTP_UPLOAD('/annexes/wxtobase64', filePath)
        postData.signUrl = 'data:image/png;base64,' + signBase64
        // #endif

        // 支付宝小程序，context.toDataURL 直接输出 base64 字符串
        // #ifndef MP-DINGTALK
        postData.signUrl = await context.toDataURL('image/png', 1)
        // #endif
        // #endif
      }
	  
	  // 是否需要指派审核人
	  let isNext = this.taskParam.currentNode.isNext
	  if (this.taskParam.next == '2') {
	  	isNext = '1';
	  }
	  if (isNext == '1') {
	  	let params = {
	  		code: this.taskParam.schemeCode,
	  		processId: this.taskParam.processId,
	  		taskId: this.taskParam.taskId,
	  		nodeId: this.taskParam.currentNode.id,
	  		operationCode: this.taskParam.code,
	  	}
	  	const userList = await this.HTTP_GET('learun/adms/newwf/auditer', params, `获取审核人时发生错误`)
	  	if (!userList) {
	  		return
	  	}
		
		let arr = Object.entries(userList)
		this.reviewerListId = arr[0][0]
		this.reviewerList =  arr[0][1].map(item => {
	  		return {
	  			text: item.Name,
	  			value: item.Id
	  		}
	  	})
		this.submitPostData = postData
		if(this.reviewerList.length>1){
			this.modal = true
			return
		}			
	  }

      const success = await this.HTTP_POST(
        this.type === 'sign' ? 'learun/adms/newwf/sign' : 'learun/adms/newwf/audit',
        postData,
        `提交[${this.typeText}]时发生错误`
      )

      if (!success) {
        return
      }

      this.EMIT('task-list-change')
      this.NAV_BACK(2)
      this.TOAST(`已成功提交${this.typeText}`, 'success')
    },

    // 手写板事件（开始拖动）
    signStart(e) {
      touchs.push({
        x: e.changedTouches[0].x,
        y: e.changedTouches[0].y
      })
    },

    // 手写板事件（拖动签名）
    signMove(e) {
      touchs.push({
        x: e.touches[0].x,
        y: e.touches[0].y
      })
      this.drawLine()
    },

    // 手写板事件（签名结束）
    signEnd(e) {
      touchs = []
    },

    // 手写板事件（绘出线型）
    drawLine() {
      if (touchs.length < 2) {
        return
      }

      const [p1, p2] = touchs
      touchs.shift()
      context.moveTo(p1.x, p1.y)
      context.lineTo(p2.x, p2.y)
      context.stroke()
      context.draw(true)
    },

    // 清除手写板
    // 阿里小程序无法使用 clearRect 来清空，因此直接重新渲染 canvas
    clearSign() {
      // #ifndef MP-ALIPAY
      context.clearRect(0, 0, 9999, 9999)
      context.draw()
      context.setStrokeStyle('#000')
      context.setLineWidth(5)
      context.setLineCap('round')
      context.setLineJoin('round')
      // #endif

      // #ifdef MP-ALIPAY
      // 阿里系小程序无法 clearRect 清空画布，必须重新渲染 canvas
      this.canvas = false
      this.$nextTick(() => {
        this.canvasInit()
      })
      // #endif
    }
  }
}
</script>

<style lang="less" scoped>
.sign-area {
  min-height: 500rpx;
  margin: 23rpx;
  border: 2rpx dashed #444444;

  .sign-canvas {
    width: 700rpx;
    height: 500rpx;
  }

  .sign-action {
    text-align: right;
  }
}
</style>
