<template>
  <view class="container">
    <uv-form labelPosition="top" labelWidth="100" :model="formModel" :rules="deliveryRules" ref="deliveryFormRef">
      <view class="formContent">
        <view class="title">{{ formModel.scene == 'ORIGIN' ? '开始' : '完成' }}配送信息</view>
        <uv-line color="#a8a8a8"></uv-line>
        <uv-form-item label="司机姓名" prop="driverName" v-if="formModel.scene == 'ORIGIN'">
          <uv-input placeholder="请输入内容" v-model="formModel.driverName" clearable />
        </uv-form-item>
        <uv-form-item label="配送车牌" prop="plateNo" v-if="formModel.scene == 'ORIGIN'">
          <uv-input placeholder="请输入内容" v-model="formModel.plateNo" clearable />
        </uv-form-item>
        <uv-form-item label="司机电话" prop="driverPhone" v-if="formModel.scene == 'ORIGIN'">
          <uv-input placeholder="请输入内容" maxlength="11" type="number" v-model="formModel.driverPhone" clearable />
        </uv-form-item>
        <uv-form-item label="位置信息" prop="lng">
          <view class="carPickerText" :style="formModel.lng ? 'color: #303133;' : ''" @tap="getCurrentLocation">{{ formModel.lng ? '获取成功' : '请点击获取当前位置'}}</view>
        </uv-form-item>
        <uv-form-item label="司机签名" prop="SIGN_DRIVER" v-if="formModel.scene == 'ORIGIN'">
          <uv-button type="warning" text="去签名" v-if="!formModel.SIGN_DRIVER" @tap="goSign('SIGN_DRIVER')"></uv-button>
          <uv-image height="80" mode="heightFix" v-if="formModel.SIGN_DRIVER" @tap="previewImage(formModel.SIGN_DRIVER[0].url)" :src="formModel.SIGN_DRIVER[0].url"></uv-image>
        </uv-form-item>
        <uv-form-item label="配送人签名" prop="SIGN_COURIER" v-if="formModel.scene == 'ORIGIN'">
          <uv-button type="warning" text="去签名" v-if="!formModel.SIGN_COURIER" @tap="goSign('SIGN_COURIER')"></uv-button>
          <uv-image height="80" mode="heightFix" v-if="formModel.SIGN_COURIER" @tap="previewImage(formModel.SIGN_COURIER[0].url)" :src="formModel.SIGN_COURIER[0].url"></uv-image>
        </uv-form-item>
        <uv-form-item label="接收人签名" prop="SIGN_RECEIVER" v-if="formModel.scene == 'DEST'">
          <uv-button type="warning" text="去签名" v-if="!formModel.SIGN_RECEIVER" @tap="goSign('SIGN_RECEIVER')"></uv-button>
          <uv-image height="80" mode="heightFix" v-if="formModel.SIGN_RECEIVER" @tap="previewImage(formModel.SIGN_RECEIVER[0].url)" :src="formModel.SIGN_RECEIVER[0].url"></uv-image>
        </uv-form-item>
        <uv-form-item label="现场照片" prop="PHOTO_SITE">
          <uv-upload
            :fileList="formModel.PHOTO_SITE"
            name="PHOTO_SITE"
            :maxCount="10"
            @afterRead="afterRead($event, 'PHOTO_SITE')" 
            @delete="deleteImg(index, 'PHOTO_SITE')"
            ></uv-upload>
        </uv-form-item>
        <uv-form-item label="单据照片" prop="PHOTO_BILL" v-if="formModel.scene == 'ORIGIN'">
          <uv-upload
            :fileList="formModel.PHOTO_BILL"
            name="PHOTO_BILL"
            :maxCount="1"
            @afterRead="afterRead($event, 'PHOTO_BILL')" 
            @delete="deleteImg(index, 'PHOTO_BILL')"
            ></uv-upload>
        </uv-form-item>
      </view>
    </uv-form>

    
    <view class="btn">
      <uv-button type="primary" text="确定" size="large" style="width: 100%;" class="mainBtn" @tap="startForm">{{ formModel.scene == 'ORIGIN' ? '开 始 配 送' : '完 成 配 送'}}</uv-button>
    </view>
  </view>
</template>

<script setup>
import { ref, onUnmounted, getCurrentInstance } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { uploadDeliveryAttachment, startOrder } from "@/api/index"

const deliveryFormRef = ref()
const formModel = ref({
  orderNo: null,
  scene: '',
  lng: '',
  lat: '',
})
const deliveryRules = ref({
  'driverName': {
    type: 'string',
    required: true,
    message: '请输入司机姓名',
    trigger: ['blur', 'change']
  },
  'plateNo': [
    {
      type: 'string',
      required: true,
      message: '请输入配送车牌',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        // 自定义校验逻辑
        return uni.$uv.test.carNo(value)
      },
      message: '请输入正确的车牌',
      trigger: ['blur', 'change']
    }
  ],
  'driverPhone': [
    {
      type: 'string',
      required: true,
      message: '请输入司机电话',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        // 自定义校验逻辑
        return uni.$uv.test.mobile(value)
      },
      message: '请输入正确的手机号',
      trigger: ['blur', 'change']
    }
  ],
  'lng': {
    type: 'number',
    required: true,
    message: '请点击获取当前位置',
    trigger: ['blur', 'change']
  },
  'SIGN_DRIVER': {
    type: 'array',
    required: true,
    message: '请司机签名',
    trigger: ['blur', 'change']
  },
  'SIGN_COURIER': {
    type: 'array',
    required: true,
    message: '请配送人签名',
    trigger: ['blur', 'change']
  },
  'SIGN_RECEIVER': {
    type: 'array',
    required: true,
    message: '请接收人签名',
    trigger: ['blur', 'change']
  },
  'PHOTO_SITE': {
    type: 'array',
    required: true,
    message: '请上传现场照片',
    trigger: ['blur', 'change']
  },
  'PHOTO_BILL': {
    type: 'array',
    required: true,
    message: '请上传单据照片',
    trigger: ['blur', 'change']
  }
})

const getCurrentLocation = () => {
  if (formModel.value.lng) {
    return
  }
  uni.showLoading({
    title: '获取当前位置中...'
  })
  uni.getLocation({
    type: 'gcj02', // 高德地图使用gcj02坐标系
    success: (res) => {
      console.log(res)
      uni.$uv.toast('获取当前位置成功')
      formModel.value.lng = res.longitude
      formModel.value.lat = res.latitude
      deliveryFormRef.value.validateField("lng")
      uni.hideLoading()
    },
    fail: (err) => {
      reject(err);
    }
  });
}

// 去签名页面
const goSign = (type) => {
  // 移除之前的事件监听器避免重复
  uni.$off('getSignImg')

  uni.navigateTo({
    url: '/pages/index/signature?bizType=' + type + '&scene=' + formModel.value.scene,
    success: () => {
      // 监听签名返回事件
      const eventHandler = (e) => {
        console.log('getSignImg', e)
        // signBase64.value = e.base64
        // signTempimg.value = e.path
        formModel.value[type] = [{url: e.url[0], scene: formModel.value.scene, bizType: type}]
      }
      
      // 监听一次自定义事件
      uni.$once('getSignImg', eventHandler)
      
      // 页面卸载时移除监听（避免内存泄漏）
      // uni.$off('getSignImg', eventHandler)
    }
  })
}

// 预览
const previewImage = (img) => {
  let arr = []
  arr.push(img)
  uni.previewImage({
    urls: arr,
  })
}

// 上传照片
const afterRead = async (event, type) => {
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  console.log(event)
  let files = event.file.url
  let formData = {
    scene: formModel.value.scene,
    bizType: type
  }
  console.log(files)
  uploadDeliveryAttachment(files, formData).then(res => {
    console.log(res)
    if (!formModel.value[type] || formModel.value[type].length == 0) {
      formModel.value[type] = []
    }
    res.data.forEach(item => {
      formModel.value[type].push({url: item, scene: formModel.value.scene, bizType: type})
    })
  })
}

// 删除图片
const deleteImg = (index, type) => {
  formModel.value[type].splice(index, 1)
}


const startForm = () => {
  deliveryFormRef.value.validate().then(res => {
    let attachments = []
    if (formModel.value.scene == "ORIGIN") {
      attachments = [...formModel.value.SIGN_DRIVER, ...formModel.value.SIGN_COURIER, ...formModel.value.PHOTO_SITE, ...formModel.value.PHOTO_BILL]
    } else {
      attachments = [...formModel.value.SIGN_RECEIVER, ...formModel.value.PHOTO_SITE]
    }
    let params = {
      ...formModel.value,
      attachments: attachments,
    }
    console.log(params)
    startOrder(params).then(res => {
      console.log(res)
      uni.$uv.toast('开始配送')
      uni.navigateBack({ delta: 1 })
    })
  }).catch(errors => {
  })
}


onLoad((options) => {
  formModel.value.orderNo = options.orderNo
  formModel.value.scene = options.type
  formModel.value.billNoCk = options.billNoCk
})

onShow(() => {
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
  console.log("协助")
  uni.$off('getSignImg')
})
</script>

<style scoped lang="scss">
.container {
  padding: 32rpx;
  background-color: #F6F8FA;
  min-height: calc(100vh - 192rpx);
  padding-bottom: 160rpx;
  .title {
    font-weight: bold;
    color: #333333;
    padding: 20rpx 0;
  }
  .formContent {
    background-color: white;
    border-radius: 20rpx;
    padding: 0 20rpx;
  }
  .carPickerText{
    padding: 16rpx 18rpx;
    padding-left: 20rpx;
    color: #c0c4cc;
    border: #dadbde 1px solid;
    border-radius: 8rpx;
    width: 100%;
  }
  .btn {
    position: fixed;
    width: calc(100vw - 64rpx);
    bottom: 0;
    left: 32rpx;
    z-index: 99;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

</style>