<template>
  <view class="pb-50rpx">
    <loading-view v-if="isFirstLoading"></loading-view>
    <view class="bg-primary h-420rpx p-base bottom-bg">
      <view class="text-xl font-medium text-white">提交申请</view>
      <view class="py-30rpx -mx-base mt-40rpx">
        <cu-steps mode="icon" icon="checkmark-circle-fill" active-color="#ffffff" active-text-color="#fff"
          un-active-text-color="#fff" un-active-color="#A6A6A6" :list="numList" :current="-1" :text-style="{
            marginTop: '30rpx',
            color: '#fff',
          }"></cu-steps>
      </view>
    </view>
    <view class="-mt-120rpx px-base relative">
      <view class="bg-white rounded-xs card h-170rpx px-24rpx py-18rpx">
        <view class="text-lg text-black">提交申请</view>
        <view class="text-lg text-hex-808080 mt-25rpx">请描述您的问题，并上传相关资料。</view>
      </view>

      <view class="bg-white rounded-xs mt-30rpx p-base">
        <view class="text-lg text-black">商品信息</view>
        <view class="mt-16rpx flex">
          <u-image class="flex-none" border-radius="15rpx" width="190" height="190" :src="goods.cover"
            :lazy-load="true"></u-image>
          <view class="ml-10rpx">
            <view class="text-hex-808080 text-lg h-90rpx">{{ goods.name }}</view>
            <view class="text-black text-lg mt-6rpx"> 单价:￥{{ goods.sell_price }} </view>
            <view class="text-right">
              <u-number-box v-model="num" :min="1" :max="goods.quantity"></u-number-box>
            </view>
          </view>
        </view>
      </view>
      <view class="bg-white rounded-xs mt-30rpx p-base">
        <view class="bg-white rounded-xs  ">
          <view class="flex text-lg items-center" @tap="typeShow = true">
            <view class="w-120rpx">
              <text class="imt">类型：</text>
            </view>
            <view class="flex-1 text-right text-hex-808080">
              <text class="mr-10rpx">{{ typeText }}</text>
              <u-icon name="arrow-right"></u-icon>
            </view>
          </view>
        </view>
        <view class="text-lg text-black mt-10rpx imt">问题描述 </view>
        <view class="mt-10rpx">
          <textarea class="min-h-130rpx w-full" placeholder-style="text-h999" placeholder="为了更好的解决您的问题，请尽量描述详细"
            maxlength="100" auto-height v-model="content"></textarea>
          <!-- 图片 -->
          <view class="py-12rpx grid grid-cols-3 gap-20rpx">
            <view class="relative w-full" style="padding-top: 100%;" v-for="(img, index) in tempFilePaths" :key="index">
              <view class="img absolute left-0 top-0 w-full h-full">
                <image class="img1 w-full h-full" :src="img"></image>
                <view
                  class="absolute bg-hex-f30606 rounded-full w-48rpx h-48rpx flex items-center justify-center  -top-10rpx -right-10rpx text-gray"
                  @tap="onDeleteImg(index)">
                  <u-icon size="20" color="#ffffff" name="close"></u-icon>
                </view>
              </view>
            </view>
            <view class="relative w-full" style="padding-top: 100%;" v-if="tempFilePaths.length < maxImgLength">
              <view class="img absolute left-0 top-0 w-full h-full" @tap="openImage">
                <u-icon name="camera"></u-icon>
                <text class="text-28rpx mt-6rpx">图片</text>
              </view>
            </view>
            <!-- 字数统计 -->
            <!-- <view class="text-h999 absolute right-18rpx bottom-30rpx">{{ content.length }}/100</view> -->
          </view>
        </view>
      </view>
      <view class="login-btn my-35rpx px-base" @tap="onSubmit"> 提交申请 </view>
    </view>

    <u-select v-model="typeShow" @confirm="onChangeType" :list="typeList" :default-value="type"></u-select>
   <!-- <u-action-sheet :list="list" @tap="uploadImge" v-model="show"></u-action-sheet> -->
  </view>
</template>
<script>
  import {
    album,
    camera
  } from '@/utils/author.js'
  import uploadImage from '@/utils/ossutil/uploadFile.js';
import loadingView from '../../components/loading-view/loading-view.vue';
  export default {
  components: { loadingView },
    data() {
      return {
        isFirstLoading:true,
        show: false,
        list: [{
            text: '拍摄',
            fontSize: 28,
            color: '#383838'
          },
          {
            text: '从相册选择',
            fontSize: 28,
            color: '#383838'
          }
        ],
        id: '',
        goodsId: '',
        tempFilePaths: [], //本地保存的图片
        imgList: [],
        num: 1,
        maxImgLength: 6,
        type: [],
        content: '',
        typeShow: false,
        orderInfo: {},

        numList: [{
            name: '提交申请',
          },
          {
            name: '客服审核',
          },
          {
            name: '客户确认',
          },
          {
            name: '完成',
          },
        ],
      };
    },
    computed: {
      typeText() {
        return this.typeList[this.type[0]]?.label ?? '请选择';
      },
      goods() {
        return this.orderInfo?.products?.find(({
          id
        }) => id == this.goodsId) ?? {};
      },
      typeList() {
        const price = this.goods.total_amount
        const isprice = price > 0 ? true : false
        let arr = [{
            value: 1,
            label: '退款退货',
          },
          {
            value: 2,
            label: '退款',
          },
          {
            value: 3,
            label: '换货',
          },
          {
            value: 4,
            label: '漏发',
          },
        ]
        if (this.goods.is_gift) {
          arr = [{
              value: 3,
              label: '换货',
            },
            {
              value: 4,
              label: '漏发',
            },
          ]
        } else if (!this.goods.is_gift && !isprice) {
          arr = [{
              value: 1,
              label: '退款退货',
            },
            {
              value: 3,
              label: '换货',
            },
            {
              value: 4,
              label: '漏发',
            },
          ]
        }
        return arr
      }
    },
    onLoad({
      id,
      goodsId
    }) {
      this.id = id;
      this.goodsId = goodsId;
      this.getOrderInfo();
    },
    methods: {
      async getOrderInfo() {
        try {
          const resData = await this.$api.get(`/v1/order/orders/${this.id}`);
          this.orderInfo = resData;
        } catch (error) {

        }finally{
          this.isFirstLoading = false
        }
      },
      //商品提交
      async onSubmit() {
        if (this.typeList[this.type[0]]?.value == null || this.typeList[this.type[0]]?.value == '') return this.$u
          .toast('请选择类型');
        if (this.content == null || this.content == '') return this.$u.toast('请填写描述');
        if (!this.tempFilePaths.length) return this.$u.toast('请上传相关资料');
        await this.uploads()
        const params = {
          type: this.typeList[this.type[0]]?.value,
          order_product_id: this.goodsId,
          description: this.content,
          images: this.imgList,
          num: this.num,
        };
        // if (params.type == null || params.type == '') return this.$u.toast('请选择类型');
        // if (params.description == null || params.description == '') return this.$u.toast('请填写描述');
        // if (!params.images.length) return this.$u.toast('请上传相关资料');
        const {
          id
        } = await this.$api.post('/v1/after-sales', params);
        this.$u.route({
          url: '/pageA/after_sales_detail/index',
          type: 'redirectTo',
          params: {
            id: id
          }
        })
      },
      //类型改变
      onChangeType(val) {
        this.type = [this.typeList.findIndex((e) => e.value == val[0].value)];
      },
      onDeleteImg(index) {
        this.tempFilePaths.splice(index, 1);
      },
      //上传的图片
      async uploadImge(index) {
        //相机
        if (index == 0) {
          // #ifdef APP-PLUS
          // let result = await camera()
          // if (!result) return
          // #endif
          this.openImage('camera')
        } else {
          //相册
          // #ifdef APP-PLUS
          // let result = await album()
          // if (!result) return
          // #endif
          this.openImage('album')
        }
      },
      openImage(val) {
        uni.chooseImage({
          count: this.maxImgLength - this.tempFilePaths.length,
          // sourceType: [val],
          sizeType: ['compressed'],
          success: async (res) => {
            res.tempFilePaths.forEach(item => {
              this.tempFilePaths.push(item)
            })
          },
          fail: (err) => {
            console.log(err)
          }
        })
      },
      //上传
      async uploads() {
        const resData = await this.$api.post('/v1/oss-sts');
        // const host = `https://${resData.bucket}.${resData.region_id}.aliyuncs.com/`
       const host = `https://${resData.bucket}.${resData.host}/`;
        const arr = []
        try {
          for (let i = 0; i < this.tempFilePaths.length; i++) {
            const upFile = new Promise((r) => {
              uploadImage(
                this.tempFilePaths[i], {
                  uploadImageUrl: host,
                  AccessKeySecret: resData.AccessKeySecret,
                  OSSAccessKeyId: resData.AccessKeyId,
                  stsToken: resData.SecurityToken,
                  timeout: 3600,
                  dir: 'app/order/',
                },
                (result) => {
                  this.imgList.push(result)
                  r()
                },
                (err) => {
                  console.log(err);
                },
              );
            })
            arr.push(upFile)
          }
        } catch (err) {
          console.log(err);
          this.$u.toast(err.message || err.errMsg);
        }
        return Promise.all(arr)
      },
      onUpload() {
        const canCount = this.maxImgLength - this.tempFilePaths.length;
        if (canCount <= 0) {
          return this.$u.toast('最多上传6张！');
        }
        this.imgList = []
        this.show = true
      },
    },
  };
</script>
<style lang="scss" scoped>
  .bottom-bg {
    width: 100%;
    text-align: center;
    color: #fff;
    background: $u-type-primary;
    clip-path: ellipse(120% 100% at 50% 0%);
  }

  .card {
    box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.12);
  }

  .imt {
    position: relative;
    padding-left: 20rpx;

    &::before {
      content: '*';
      color: #d43030;
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
    }
  }

  .img {
    width: 100%;
    height: 100%;
    color: #999;
    border-radius: 8rpx;
    background-color: #eee;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
</style>
