<template>
  <uni-popup ref="signRef" type="share" :is-mask-click="false" safeArea backgroundColor="#fff" class="popup-box">
    <view class="modal-box">
      <view class="modal-head">
        <text @tap="close">取消</text>
        <text class="text-title">签名</text>
      </view>
      <view class="modal-content">
        <view>
          <radio-group @change="radioChange" class="radio-group" v-if="isCallSign">
            <label class="radio-box">
              <view>
                <radio value="write" :checked="signType==='write'"/>
              </view>
              <view>手写签名</view>
            </label>
            <label class="radio-box">
              <view>
                <radio value="sign" :checked="signType==='sign'"/>
              </view>
              <view>签章</view>
            </label>
          </radio-group>
					<uni-data-select
						v-model="signUrl"
						:localdata="signOptions"
						:clear="false"
						@change="change"
						v-if="signType==='sign'"
						class="select-box"
					/>
					<view  v-else :style="{height: 'calc(100vh - '+(isCallSign?140:100)+'px)',display:'flex',alignItems: 'center'}"> 
						<view class="signCanvas" :style="{width:canvasw+'px',height:canvash+'px'}"> 
							<canvas :key="Date.now()"
								canvas-id="signCanvas"
								id="signCanvas"
								disable-scroll
								:hidpi="false"
								@touchstart="touchstart"
								@touchmove="touchmove"
								@touchend="touchend"
								@touchcancel="touchcancel"
							/>
						</view>
					</view>
        </view>
        <view class="btns">
          <button class="btn" @click="clear" v-if="signType==='write'">重置</button>
          <button class="btn primary-btn" @click="save" :loading="_this.loading">保存</button>
        </view>
      </view>
    </view>
  </uni-popup>
</template>
<script setup>
  import { reactive, onMounted, getCurrentInstance, ref } from "vue";
  import { getStampPage } from '@/common/api/signature/index';
  
  const props = defineProps({
    isCallSign: {
      type: Boolean,
      default: false,
    },
  })
  const _this = reactive({
    loading: false,
  });
  const emits = defineEmits(['confirm'])
   
  let data = reactive({
    ctx: null, //绘图图像
    points: [], //路径点集合
    path: "",
    flag: false,
  });
  const instance = ref(null);
  const signRef = ref();
  const signType = ref('write')
  const signOptions = ref([]);
  const signUrl = ref('');
	const canvasw = ref(0);
	const canvash = ref(0);
	const pixelRatio=ref(1);
  onMounted(() => {
		setCavasWidth()
    instance.value = getCurrentInstance();
		getOptions()
  });
  
  function open() {
		init();
		getOptions()
    signRef.value.open(); 
  }
  function setCavasWidth(){
		if(signType.value === 'write'){
			uni.getSystemInfo({
			  success: function (res) {
			    canvasw.value = (res.windowWidth-20);
			    canvash.value = canvasw.value*8/11;  
					pixelRatio.value=res.pixelRatio;
			  },
			}); 
		} 
		init();
	}
  function init() {
    data.ctx = uni.createCanvasContext("signCanvas", instance.value);
    data.ctx.lineWidth = 6;
    data.ctx.lineCap = "round";
    data.ctx.lineJoin = "round";
    data.flag = false; 
  }
  function touchstart(e) {
    let startX = e.changedTouches[0].x;
    let startY = e.changedTouches[0].y;
    let startPoint = { X: startX, Y: startY };
    data.points.push(startPoint);
    data.ctx.beginPath();
  }
  function touchmove(e) {
    let moveX = e.changedTouches[0].x;
    let moveY = e.changedTouches[0].y;
    let movePoint = { X: moveX, Y: moveY };
    data.points.push(movePoint); //存点
    let len = data.points.length;
    if (len >= 2) {
      draw(); //绘制路径
    }
  }
  function touchend(e) {
    data.points = [];
  }
  function touchcancel(e) {
    touchend();
  }
  function draw() {
    let point1 = data.points[0];
    let point2 = data.points[1];
    data.points.shift();
    data.ctx.moveTo(point1.X, point1.Y);
    data.ctx.lineTo(point2.X, point2.Y);
    data.ctx.stroke();
    data.ctx.draw(true);
    data.flag = true;
  }
   
  function save() {
    _this.loading = true;
    let url = ''
		
    if(signType.value === 'write'){ 
			uni.canvasToTempFilePath(
				{
					x: 0,
					y: 0,
					width: canvasw.value/pixelRatio.value, // 画布得宽度,单位px
					height: canvash.value/pixelRatio.value, // 画布得高度,单位px
					canvasId: "signCanvas",
					success: function (res) { 
						url = res.tempFilePath; 
						_this.loading = false;
						emits('confirm', signType.value, url)
					},
				},
				instance.value
			); 
    }else {
      url = signUrl.value;
			_this.loading = false;
			emits('confirm', signType.value, url) 
			clear()
    } 
  }
  //清空画布
  function clear() {
    uni.getSystemInfo({
      success: function (res) {
        let canvasw = res.windowWidth;
        let canvash = res.windowHeight;
        data.ctx.clearRect(0, 0, canvasw, canvash);
        data.ctx.draw(false);
        data.flag = false;
      },
    });
  }
  async function getOptions() {
    const res = await getStampPage(0, {
      limit: 1,
      size: 100,
    });
    if(res.data.list && res.data.list.length){
      signOptions.value = res.data.list.map(item=>{
        return {
          text: item.name,
          value: item.fileUrl
        }
      })
    }
 
  }
    
  function radioChange(evt){ 
    signType.value = evt.detail.value;
		setCavasWidth()
  }
  
  function close() {
    signRef.value.close();
  }
  
  defineExpose({
    open,
    close
  })
</script>

 
<style lang="less" scoped>
  .uni-popup {
    z-index: 999;
  }
  .modal-box {
    width: 100vw;
    height: 100vh;
    .modal-head {
      display: flex;
      align-items: center;
      height: 50px;
      background-color: #fff;
      font-size: 15px;
      padding: 0 20px;
      .text-title {
        position: absolute;
        left: 70px;
        right: 70px;
        font-size: 16px;
        font-family: Microsoft YaHei-Bold, Microsoft YaHei;
        font-weight: bold;
        text-align: center;
      }
    }
    .modal-content {
      padding: 5px 10px;
      height: calc(100% - 50px);
      box-sizing: border-box;
      .radio-group{
        display: flex;
        justify-content: center;
        .radio-box{
          display: flex;
          &:first-child{
            margin-right: 20px;
          }
        }
      }
			.select-box{
			  margin: 10px 0;
			  width: 100%
			}
      .signCanvas{
        width: 100%;
        border:1px solid #ddd;
        
        #signCanvas{
          height: 100%;
          width: 100%
        }
      }
      .btns {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .btn {
        width: 90px;
        height: 28px;
        margin: 0 5px;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .primary-btn {
        background: #5E95FF;
        color:#fff;
      }
    }
  }
</style>