<template>
  <view>
    <loading-view v-if="isFirstLoading"></loading-view>
    <view class="h-420rpx p-base bottom-bg">
      <view class="text-lg font-extrabold text-white text-left">{{detail.state|saleText}}</view>
      <view class="py-30rpx -mx-base mt-40rpx">
        <block v-if="detail.state!=7">
          <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="current" :text-style="{
             marginTop: '30rpx',
             color: '#fff',
           }"></cu-steps>
        </block>
        <block v-else>
          <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="numLists" :current="current" :text-style="{
             marginTop: '30rpx',
             color: '#fff',
           }"></cu-steps>
        </block>
      </view>
    </view>
    <view class="-mt-120rpx px-base relative">
      <view class="bg-white rounded-xs card h-170rpx pl-24rpx py-18rpx flex"
        @tap="$u.route('/pageA/after_sales_logistics/index',{id:detail.id})">
        <view class="flex-1 w-0">
          <view class="text-lg text-black">{{detail.state|saleText}}</view>
          <view class="text-lg text-hex-808080 mt-25rpx line-1">{{detail.remarks?detail.remarks:'资料已提交，请耐心等待客服审核'}}</view>
        </view>
        <view class="flex items-center pr-20rpx text-hex-808080">
          <u-icon name="arrow-right" size="30"></u-icon>
        </view>
      </view>
      <view class="bg-white rounded-xs mt-30rpx p-base">
        <view class="text-lg text-black">{{detail.type|typeList}} </view>
        <view class="mt-36rpx">
          <view class="text-hex-808080">问题描述：{{detail.description}}</view>
          <view class="grid grid-cols-3 gap-x-45rpx gap-y-23rpx mt-14rpx">
            <u-image v-for="(item,index) in detail.images" :key="index" class="flex-none" border-radius="8rpx"
              width="190" height="190" :src="item" :lazy-load="true"></u-image>
          </view>
            <block >
              <view class="flex items-center justify-between mt-30rpx">
                <view>回复：</view>
                <block v-if="detail.type==1||detail.type==2">
                  <view v-if="detail.state==3 || detail.state==4 ||detail.state==5" class="text-hex-d43030">退款金额：{{detail.amount}}元</view>
                </block>
              </view>
              <view class="mt-base">{{detail.remarks?detail.remarks:'资料已提交，请耐心等待客服审核'}}</view>
            </block>
        </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="detail.product.cover"
            :lazy-load="true"></u-image>
          <view class="ml-10rpx flex-1">
            <view class="text-hex-808080 text-lg h-90rpx">{{detail.product.name}}</view>
            <view class="flex justify-between mt-6rpx">
              <view class="text-black text-lg flex-1"> 单价：￥{{detail.product.sell_price}} </view>
              <view class="text-black text-lg flex-1"> 数量：{{detail.product.num}} </view>
            </view>
          </view>
        </view>
      </view>
     <!-- <view class="bg-white rounded-xs mt-30rpx p-base"> -->
        <!-- 货运单号 -->
        <block v-if="(detail.type==1 ||detail.type==3)&&detail.state==3 ">
          <view class="flex items-center mt-40rpx ">
            <view>退货运单号：</view>
            <u-input class="bg-white" border placeholder="请输入运单号" v-model="textContent" />
          </view>
        </block>
        <!-- 打回重填 -->
        <block v-if="detail.state==1">
          <view class="bg-white rounded-xs mt-30rpx p-base">
           <!-- <view class="bg-white rounded-xs "> -->
              <view class="text-lg text-black flex 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>
        </block>
        </view>
        <view>
        <view class="py-35rpx px-base">
          <view class="login-btn " v-if="detail.state==1" @tap="onSubmit"> 补充资料 </view>
          <view class="login-btn " v-if="detail.state==3" @tap="onConfirm"> 确认 </view>
          <view class="login-btn mt-base" v-if="detail.state==1 ||detail.state==2 ||detail.state==3" @tap="cancelShow=true">
            取消申请 </view>
        </view>
    <!--  </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>
    <cu-modal v-model="cancelShow"   @confirm="confirm" confirm-color="#378264" show-cancel-button
      content="是否取消申请"></cu-modal>
  </view>
</template>
<script>
  import {
    album,
    camera
  } from '@/utils/author.js'
  import uploadImage from '@/utils/ossutil/uploadFile.js';
  export default {
    data() {
      return {
        isFirstLoading:true,
        id:'',
        show: false,
        list: [{
            text: '拍摄',
            fontSize: 28,
            color: '#383838'
          },
          {
            text: '从相册选择',
            fontSize: 28,
            color: '#383838'
          }
        ],
        detail: {
          product: {}
        },
        textContent: '', //退货运单号
        tempFilePaths: [], //
        imgList: [],
        maxImgLength: 6,
        content: '',
        numList: [{
            name: '提交申请',
          },
          {
            name: '客服审核',
          },
          {
            name: '客户确认',
          },
          {
            name: '完成',
          },
        ],
        numLists: [{
            name: '提交申请',
          },
          {
            name: '取消申请',
          },
          {
            name: '完成',
          },
        ],
        typeShow: false,
        type: [],
        content: '',
        cancelShow:false
      };
    },
    computed: {
      current() {
        return this.detail.state - 2
      },
      typeText() {
        return this.typeList[this.type[0]]?.label ?? '请选择';
      },
      typeList(){
         const price=Number(this.detail.product.total_amount)
         const isprice=price>0?true:false
        let arr=[
          {
              value: 1,
              label: '退款退货',
            },
            {
              value: 2,
              label: '退款',
            },
            {
              value: 3,
              label: '换货',
            },
            {
              value: 4,
              label: '漏发',
            },
        ]
        if(this.detail.product.is_gift){
          arr=[
              {
                value: 3,
                label: '换货',
              },
              {
                value: 4,
                label: '漏发',
              },
          ]
        }else if(!this.detail.product.is_gift && !isprice){
          arr=[
            {
                value: 1,
                label: '退款退货',
              },
              {
                value: 3,
                label: '换货',
              },
              {
                value: 4,
                label: '漏发',
              },
          ]
        }
        return arr
      }
    },
    onLoad({
      id
    }) {
      this.id=id
      this.getDate(id)
    },
    methods: {
      //获取详情
      async getDate(id) {
        try{
          let resDate = await this.$api.get(`/v1/after-sales/${id}`)
          this.detail = resDate
        }catch(err){}finally{
          this.isFirstLoading=false
        }
      },
      //类型改变
      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.domain}/`;
        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
      },
      //补充资料
      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()
        let obj = {
          type: this.typeList[this.type[0]]?.value,
          description: this.content,
          images: this.imgList
        }
        // if (obj.type == null || obj.type == '') return this.$u.toast('请选择类型');
        // if (obj.description == null || obj.description == '') return this.$u.toast('请填写描述');
        // if (!obj.images.length) return this.$u.toast('请上传相关资料');
        let resDate = await this.$api.put(`/v1/after-sales/${this.detail.id}`,obj)
        this.$u.toast('提交成功')
        this.getDate(this.id)
      },
      //确认收货
      async onConfirm() {
        let obj = {}
        if ((this.detail.type == 1 || this.detail.type == 3) && !this.textContent) {
          return this.$u.toast('请输入运单号，并用逗号隔开')
        }
        if (this.detail.type == 1 || this.detail.type == 3) {
          obj.tracking_number = this.textContent
        }
        let resDate = await this.$api.put(`/v1/after-sales/${this.detail.id}/agree`, obj)
        this.getDate(this.id)
      },
      //取消申请
    async  confirm(){
          try{
            await this.$api.delete(`/v1/after-sales/${this.detail.id}`, {}, {
              custom: {
                loading: true
              },
            });
            this.$u.toast("取消成功")
            uni.navigateBack()
            uni.$emit('refresh')
          }catch(err){}
      },
    },
  };
</script>
<style lang="scss" scoped>
  .card {
    box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.12);
  }

  .bottom-bg {
    width: 100%;
    text-align: center;
    color: #fff;
    background: $u-type-primary;
    clip-path: ellipse(120% 100% at 50% 0%);
  }

  .clipPath {
    clip-path: ellipse(120% 40% at 50% 0%) !important;
  }

  .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>
