<template>
  <view class="ctr" v-if="data !== null">
    <view class="form-group">
      <view class="group-name flex-l line-after">
        <me-icon class="icon" type="icon-info" color="#E18F00" size="40rpx"></me-icon>
        <text class="text">服务完成后请提交信息</text>
      </view>
      <view class="item upload">
        <view class="info flex-l">
          <view class="title flex-l">拍照打卡</view>
          <view class="desc flex-l">请上传完成图片（最多 10 张）</view>
        </view>
        <view class="imgs-ctr">
          <view class="img-item" v-for="(imgUrl, index) in submitData.complete_images" :key="index">
            <view @click="helpers.previewImage(imgUrl)" class="img-ctr" :style="{marginRight: (index+1) % 4 === 0 ? '0' : '55rpx'}">
              <image class="img" mode="aspectFill" :src="imgUrl"></image>
            </view>
            <view class="del" @click="delImg(index)">
              <me-icon class="icon" type="icon-close-circle-fill" color="var(--importantColor)" size="40rpx"></me-icon>
            </view>
          </view>

          <view @click="upload('complete')" class="up-ctr flex-direction-column" hover-class="auto-mask-layer-radius4"
                hover-start-time="0" hover-stay-time="50">
            <me-icon class="icon" type="icon-upload-cloud-fill" color="var(--summaryColor)" size="36rpx"></me-icon>
            <view class="up flex-c">点击上传</view>
          </view>
        </view>
      </view>
    </view>
    <view class="form-group">
      <view class="group-name flex-l line-after">
        <me-icon class="icon" type="icon-info" color="#E18F00" size="40rpx"></me-icon>
        <text class="text">提交收款信息</text>
      </view>
      <view class="item input flex-sb line-after" v-if="data.order_info.receive_type === 1">
        <view class="title flex-l">优惠信息</view>
        <view class="uni-input flex-r">{{data.order_info.online_amount}}元抵扣{{data.order_info.discount_amount}}元</view>
      </view>
      <view class="item input flex-sb line-after" @click="selectFinalPaymentMethod()">
        <view class="title flex-l">收款方式</view>
        <view v-if="submitData.final_payment_method === null" class="select-ctr flex-r">请选择收款方式</view>
        <view v-else class="select-ctr flex-r select">{{submitData.final_payment_method === 1 ? '线下尾款' : '线上尾款'}}</view>
      </view>
      <!--      线下收款需选择尾款收款方-->
      <view v-if="submitData.final_payment_method === 1" class="item input flex-sb line-after" @click="selectOfflineTotalType()">
        <view class="title flex-l">尾款收款方</view>
        <view v-if="submitData.offline_total_type === 0" class="select-ctr flex-r">请选择尾款收款方</view>
        <view v-else class="select-ctr flex-r select">{{submitData.offline_total_type === 1 ? '师傅收' : '公司收'}}</view>
      </view>
      <view class="item input flex-sb line-after">
        <view class="title flex-l">收款金额</view>
        <view class="input-ctr">
          <input type="digit" v-model="submitData.amount" class="uni-input" placeholder-class="placeholder-class" placeholder="请输入收款金额"/>
        </view>
      </view>
      <view class="item upload">
        <view class="info flex-l">
          <view class="title flex-l">收款信息</view>
          <view class="desc flex-l">请上传收款成功图片（最多 1 张）</view>
        </view>
        <view class="imgs-ctr">
          <view v-if="submitData.payment_image === ''" @click="upload('collectPayment')" class="up-ctr flex-direction-column" hover-class="auto-mask-layer-radius4"
                hover-start-time="0" hover-stay-time="50">
            <me-icon class="icon" type="icon-upload-cloud-fill" color="var(--summaryColor)" size="36rpx"></me-icon>
            <view class="up flex-c">点击上传</view>
          </view>
          <view v-else class="img-item">
            <view @click="helpers.previewImage(submitData.payment_image)" class="img-ctr">
              <image class="img" mode="aspectFill" :src="submitData.payment_image"></image>
            </view>
            <view class="del" @click="delPaymentImg()">
              <me-icon class="icon" type="icon-close-circle-fill" color="var(--importantColor)" size="40rpx"></me-icon>
            </view>
          </view>

        </view>
      </view>
    </view>
    <me-empty-space height="376"></me-empty-space>
    <view class="bottom">
      <me-button @click="submit()" text="提 交" width="686rpx" icon-type="icon-checkbox-circle" margin-top="32rpx"></me-button>
    </view>
  </view>
</template>

<script setup>

import MeIcon from "../../components/me-icon/me-icon.vue";
import MeEmptySpace from "../../components/me-empty-space/me-empty-space.vue";
import MeButton from "../../components/me-button/me-button.vue";
import helpers from "../../utils/helpers";
import {ref, reactive} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import api from "../../api/api";
import {throttle} from "../../utils/throttle";
import enums from "../../utils/enums";

/**
 * 上传完成图片
 * @param type 上传类型:complete=完成图片,collectPayment=收款图片
 */
const upload = (type) => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original'],
    sourceType: ['camera'],
    success: (chooseImageRes) => {
      if (chooseImageRes.tempFiles[0].size / 1024 / 1024 > 10) {
        return helpers.showToast('照片不能超过10M')
      }

      uni.showLoading({
        title: '上传中'
      });

      let tempFilePath = chooseImageRes.tempFilePaths[0]
      api.getOssParams({name: tempFilePath}).then(res => {
        uni.uploadFile({
          url: res.cdnurl,
          filePath: tempFilePath,
          name: 'file',
          timeout: 30 * 1000,
          formData: {
            'signature': res.signature,
            'ossAccessKeyId': res.OSSAccessKeyId,
            'policy': res.policy,
            'key': res.key,
          },
          success(r) {
            if (r.statusCode === undefined || r.statusCode !== 204) {
              helpers.showToast('上传文件失败')
              return
            }

            let fullUrl = res.cdnurl + '/' + res.key

            if (type === 'complete') {
              submitData.complete_images.push(fullUrl)
            }

            if (type === 'collectPayment') {
              submitData.payment_image = fullUrl
            }

            helpers.showToast('上传成功')
          },
          fail(e) {
            helpers.showToast('上传文件失败')
            console.log(e)
          },
          complete() {
            helpers.delayHideLoading()
          }
        });
      }).catch(() => {})
    }
  });
}

//删除完成图片
const delImg = (idx) => {
  submitData.complete_images.splice(idx, 1)
  helpers.showToast('图片已删除')
}

//删除收款图片
const delPaymentImg = () => {
  submitData.payment_image = ''
  helpers.showToast('图片已删除')
}

//提交
const submit = throttle(() => {
  if (!validate()) {
    return false
  }

  uni.showModal({
    title: '提示信息',
    confirmText: '确认',
    content: '确认已完成所有服务？',
    success: function (res) {
      if (res.confirm) {
        uni.showLoading({
          title: '提交中'
        });

        let data = helpers.deepObj(submitData)
        data.complete_images = (submitData.complete_images).join(',')
        data.order_dispatch_id = id.value

        api.completeService(data).then(() => {
          helpers.delayHideLoading()
          uni.showToast({
            title: '已完成服务',
            icon: "success"
          })
          setTimeout(() => {
            uni.navigateBack();
          }, 1000)
        }).catch(() => {})
      }
    }
  });
})

const id = ref(null)
onLoad((params) => {
  id.value = params.id
  init()
})

const data = ref(null)
const init = () => {
  api.orderInfo({order_dispatch_id: id.value}).then(res => {
    if (res.status !== enums.ORDER_DISPATCH_STATUS.STATUS_CLOCK) {
      return helpers.showToast('该订单不可完成')
    }

    data.value = res
  }).catch(() => {})
}

//提交数据
const submitData = reactive({
  complete_images: [],//完成图片
  final_payment_method: null,//尾款支付方式：1=线下尾款,2=线上尾款
  offline_total_type: 0,//尾款收款方：1=师傅收,2=公司收
  amount: '',//收款金额
  payment_image: '',//收款图片
})

const selectFinalPaymentMethod = () => {
  uni.showActionSheet({
    itemList: ['线下尾款', '线上尾款'],
    success: function (res) {
      submitData.final_payment_method = res.tapIndex + 1
    },
    fail: function (res) {
      console.log(res.errMsg);
    }
  });
}

const selectOfflineTotalType = () => {
  uni.showActionSheet({
    itemList: ['师傅收', '公司收'],
    success: function (res) {
      submitData.offline_total_type = res.tapIndex + 1
    },
    fail: function (res) {
      console.log(res.errMsg);
    }
  });
}

//验证提交数据
const validate = () => {
  if (submitData.complete_images.length === 0) {
    helpers.showToast('请上传完成图片')
    return false
  }

  if (submitData.final_payment_method === null) {
    helpers.showToast('请选择收款方式')
    return false
  }

  if (submitData.final_payment_method === 1 && submitData.offline_total_type === 0) {
    helpers.showToast('请选择尾款收款方')
    return false
  }

  if (submitData.amount === '') {
    helpers.showToast('请输入收款金额')
    return false
  }

  if (submitData.payment_image === '') {
    helpers.showToast('请上传收款信息')
    return false
  }

  return true
}

</script>

<style lang="scss" scoped>
.ctr {
  padding: 0 32rpx;
  box-sizing: border-box;
  height: 100vh;
  .bottom {
    width: 100%;
    padding-top: 20rpx;
    padding-bottom: 68rpx;
    background: var(--pageBgColor);
    box-sizing: border-box;
    position: fixed;
    bottom: 0;
  }
}
</style>













