<template>
  <div class="refund">
    <goodsRefund :list="goodsInfo" />
    <div class="refund_content">
      <cr-cell v-if="+type === 1" is-link @click="openGoodsStatus">
        <template slot="title">
          <span class="refund_content_name">货物状态</span>
          <span class="refundType_select_color">{{ goodsStatusName }}</span>
        </template>
      </cr-cell>
      <cr-cell title="退款原因" is-link class="not-after" @click="cancel">
        <template slot="title">
          <span class="refund_content_name">退款原因</span>
          <span v-if="reasonName" class="refundType_select_color">{{ reasonName }}</span>
          <span v-else class="refundType_un_select_gray">请选择</span>
        </template>
      </cr-cell>
      <div
        v-if="refundData && refundData.childList && refundData.childList.length"
        class="refund-content-reason"
      >
        <span class="title">{{ refundData.childReasonDescription }}</span>
        <div class="content">
          <div v-for="(item, index) in refundData.childList" :key="item.reasonId">
            <div
              class="flex-col"
              :class="[item.selected ? 'active' : '']"
              @click="selectRefundType(index, item)"
            >
              <span class="text">{{ item.reasonName }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- v-if="+type === 1"  -->
      <cr-cell title="退款金额" class="border-top">
        <template slot="title" class="refund_content_cell">
          <div class="refund_content_wrapper">
            <span class="refund_content_name">退款金额</span>
            <div class="refund_content_block">
              <span class="refund_content_block_amount">
                ￥
                <!-- <span class="refundType_select_color">{{ refundMoeny }}</span> -->
                <cr-field
                  ref="inputRrefundMoeny"
                  v-model="refundMoeny"
                  :disabled="!refundData.canChangeRefundAmount"
                  type="number"
                >
                  <template v-if="refundData.canChangeRefundAmount" v-slot:button>
                    <div class="refund_content_mdf" @click="onEdit">
                      <cr-image
                        height="20px"
                        width="38px"
                        class="mdf-img"
                        src="https://img.lkbang.net/edit.2828ba07.png"
                      />
                      <!-- <span>修改</span> -->
                    </div>
                  </template>
                </cr-field>
              </span>
              <div v-if="refundData.amountDesc || amountDesc" class="refund_content_gray">
                {{ refundData.amountDesc || amountDesc }}
              </div>
            </div>
          </div>
        </template>
      </cr-cell>
      <div v-if="refundData && refundData.needPaymentInfo" class="payment-account">
        <div class="header ">
          支付宝收款账户
        </div>
        <cr-field
          v-model="payee"
          class="payment-account-item"
          name="账户姓名"
          label="账户姓名"
          placeholder="请输入账户姓名"
        />
        <cr-field
          v-model="receiptAccount"
          class="payment-account-item"
          name="账户帐号"
          label="账户帐号"
          placeholder="请输入账户帐号"
        />
      </div>
      <div class="refund_content_explain">
        <span class="refund_content_explain_title">退款说明</span>
        <cr-field
          v-model="remark"
          class="refund_content_explain_tex"
          type="textarea"
          placeholder="请输入退款内容"
          :max-length="70"
          :show-word-limit="true"
          autosize
          rows="3"
        />
      </div>
    </div>
    <div class="refund_picture">
      <div class="refund_picture_title">
        <span>上传凭证</span>
        <span>（最多6张）</span>
      </div>
      <cr-uploader
        v-model="orderList"
        :before-read="
          file => {
            asyncRead(file);
          }
        "
        max-number="6"
      />
    </div>
    <div class="refund_bottom">
      <button @click="submit">提交</button>
    </div>
    <cr-popup
      v-model="showCancelPopup"
      closeable
      round
      position="bottom"
      get-container="body"
      class="cancel-popup"
    >
      <div class="Cp__head">
        <div class="Cp__head-title">退款原因</div>
      </div>
      <cr-radio-group v-model="reasonName" class="Cp__list-wrap">
        <cr-cell-group class="Cp__list">
          <cr-cell
            v-for="(item, index) in applyReasonList"
            :key="index"
            :title="item.reasonName"
            @click="onCellClick(item)"
            @right-click="onCellClick(item)"
          >
            <template #right-icon>
              <div class="radiomark">
                <cr-radio ref="checkboxes" :name="item.reasonName" class="Cp__list-radio" />
              </div>
            </template>
          </cr-cell>
        </cr-cell-group>
      </cr-radio-group>
    </cr-popup>

    <cr-popup
      v-model="showStatusPopup"
      closeable
      round
      position="bottom"
      get-container="body"
      class="cancel-popup"
    >
      <div class="Cp__head">
        <div class="Cp__head-title">货物状态</div>
      </div>
      <cr-radio-group v-model="goodsStatusName" class="Cp__list-wrap">
        <cr-cell-group class="Cp__list">
          <cr-cell
            v-for="(item, index) in goodsStatusList"
            :key="index"
            :title="item.goodsStatusText"
            @click="onStatusClick(item)"
            @right-click="onStatusClick(item)"
          >
            <template #right-icon>
              <div class="radiomark">
                <cr-radio ref="checkboxes" :name="item.goodsStatusText" class="Cp__list-radio" />
              </div>
            </template>
          </cr-cell>
        </cr-cell-group>
      </cr-radio-group>
    </cr-popup>
  </div>
</template>
<script>
import goodsRefund from './components/goodsRefund';
import orderApi from '@/api/order.api';
import { upload } from 'qiniu-js';
import config from '../../config/index';
// import { isWxMp } from '@/service/validation.service';
import localStorage from '@/service/localStorage.service';
export default {
  components: {
    goodsRefund
  },
  data() {
    return {
      refundData: [],
      selectChildList: [],
      accountName: '',
      accountCode: '',
      orderNo: '',
      orderInfo: {},
      type: '',
      goodsInfo: {},
      showCancelPopup: false,
      orderReason: {},
      refundMoeny: '',
      applyReasonList: [],
      reasonName: '',
      remark: '',
      refundReasonId: '',
      token: '',
      maxLimit: 9, // 渲染有问题
      orderList: [],

      amountDesc: '',
      showStatusPopup: false,
      goodsStatus: '',
      goodsStatusName: '',
      goodsStatusList: [],
      refundMethodType: '',
      refundMethodPayType: '',
      applyCount: '',

      payee: '', // 收款人
      receiptAccount: '' // 收款账户
    };
  },
  mounted() {
    this.type = this.$route.query.type;
    this.$store.commit('CHANGE_TITLE', +this.type === 1 ? '我要退款' : '我要退货退款');
    this.orderSkuId = this.$route.query.orderSkuId;
    this.orderNo = this.$route.query.orderNo;
    this.serviceNo = this.$route.query.serviceNo || '';
    // this.orderSkuId = cookies.get("orderSkuId") || "";
    // this.orderNo = cookies.get("orderNo") || "";
    this.applyPageInfoV2();
    // this.refundAmount();
    // this.applyReason();
    this.getToken();

    // this.type = this.$route.query.type;
    // if (localStorage.get('orderInfo')) {
    //   this.orderInfo = localStorage.get('orderInfo');
    //   this.goodsInfo = this.orderInfo.currentSku;
    // }
    // if (this.$route.params.goodsInfo) {
    //   this.goodsInfo = this.$route.params.goodsInfo;
    // }
    // this.refundAmount();
    // this.applyReason();
    // this.getToken();
  },
  methods: {
    // 修改
    onEdit() {
      this.$nextTick(() => {
        this.$refs.inputRrefundMoeny.focus();
      });
    },
    // 选择退款类型
    selectRefundType(index) {
      if (this.refundData.childList[index].selected) {
        this.refundData.childList[index].selected = false;
      } else {
        this.refundData.childList[index].selected = true;
      }
      this.refundData = JSON.parse(JSON.stringify(this.refundData));
    },
    onCellClick(item) {
      this.reasonName = item.reasonName;
      this.refundReasonId = item.reasonId;
      this.showCancelPopup = false;
      item.childList &&
        item.childList.map(it => {
          it.selected = false;
        });
      this.refundData = item;
      this.refundMoeny = item.refundAmount;
    },
    cancel() {
      this.showCancelPopup = true;
    },

    onStatusClick(item) {
      this.reasonName = '';
      this.refundData = []; // 退款原因设置空
      this.goodsStatusName = item.goodsStatusText;
      this.goodsStatus = item.goodsStatus;
      this.showStatusPopup = false;
      // 如果货物状态数据只有一个，是编辑操作，不请求退货原因
      // if (this.goodsStatusList.length === 1) {
      //   return;
      // }
      this.applyReasonV2();
    },

    openGoodsStatus() {
      this.showStatusPopup = true;
      // this.reasonName = '';
      // this.refundData = []; // 退款原因设置空
    },
    async applyPageInfoV2() {
      const [res, error] = await orderApi.applyPageInfoV2({
        type: this.type,
        orderSkuId: this.orderSkuId,
        serviceNo: this.serviceNo
      });
      if (!error) {
        this.goodsInfo = res?.skuInfo || {};
        this.refundMoeny = res.refundAmount;
        this.initRefundMoeny = res.refundAmount;
        this.applyReasonList = res.applyReasonList;
        this.goodsStatusName = res.goodsStatusText;
        this.amountDesc = res.amountDesc; // 退款说明
        this.goodsStatusList = res.goodsStatusList; // 货物状态
        this.refundMethodType = res.refundMethodInfo?.type || '';
        this.refundMethodPayType = res.refundMethodPayType || '';
        this.applyCount = res?.applyCount || '';
        this.payee = res?.payee || ''; // 退款人
        this.receiptAccount = res?.receiptAccount || ''; // 退款账户
        if (this.serviceNo) {
          this.editRefundInfo(res);
        }
      }
    },
    editRefundInfo(editRes) {
      this.remark = editRes.remark;
      this.goodsStatus = editRes.goodsStatus;
      this.goodsStatusName = editRes.goodsStatusText;
      this.applyReasonList = editRes.applyReasonList;
      this.refundMethodPayType = editRes?.refundMethodPayType;
      this.reasonName = editRes.refundReasonName;
      this.refundReasonId = editRes.refundReasonId;
      if (this.applyReasonList.length) {
        this.refundData = this.applyReasonList[0];
        this.refundData.childList = editRes.childList;
      }
      this.orderList = (editRes.proofList || []).map(item => ({
        url: item,
        isImage: true,
        status: 'done'
      }));
    },

    async applyReasonV2() {
      const [res] = await orderApi.applyReasonV2({
        type: this.type,
        orderSkuId: this.goodsInfo.orderSkuId,
        goodsStatus: this.goodsStatus,
        serviceNo: this.serviceNo
      });
      if (res) {
        this.applyReasonList = res.applyReasonList;
      }
    },
    // // eslint-disable-next-line vue/no-dupe-keys
    // async refundAmount() {
    //   const [res] = await orderApi.refundAmount({
    //     orderSkuId: this.goodsInfo.orderSkuId
    //   });
    //   this.refundMoeny = res.refundAmount;
    // },
    async submit() {
      if (+this.type === 1 && !this.goodsStatusName) {
        this.$toast('请选择货物状态');
        return;
      }

      if (!this.reasonName) {
        this.$toast('请选择退款原因');
        return;
      }

      let childList = this.refundData.childList || [];
      // 存在子集 且未选择子集原因提示必填
      let selected = childList.some(item => item.selected === true);
      if (childList.length && !selected) {
        this.$toast('请选择退款子原因');
        return;
      }
      let { needPaymentInfo, needDescription, needUploadPic } = this.refundData;
      // 如何需要填写账户信息
      if (needPaymentInfo && !this.payee) {
        this.$toast('请输入账户姓名');
        return;
      }
      // 如何需要填写账户信息
      if (needPaymentInfo && !this.receiptAccount) {
        this.$toast('请输入账户帐号');
        return;
      }
      // 选择子原因中子项如果退货说明必填，则必填
      if (needDescription && !this.remark) {
        this.$toast('请输入退款说明');
        return;
      }
      // 选择子原因中子项如果上传凭证必填，则必填
      if (needUploadPic && !this.orderList.length) {
        this.$toast('请上传凭证');
        return;
      }
      const params = {
        refundMethodType: this.refundMethodType,
        refundMethodPayType: this.refundData.refundMethodPayType || this.refundMethodPayType,
        applyCount: this.applyCount,
        orderSkuId: this.orderSkuId,
        type: this.type,
        refundAmount: this.refundMoeny,
        refundReasonId: this.refundReasonId,
        refundReasonName: this.reasonName,
        remark: this.remark,
        agreeContract: true,
        payee: this.payee,
        childList: childList.filter(item => item.selected === true),
        receiptAccount: this.receiptAccount,
        proofList: this.orderList.map(({ url }) => {
          return url;
        })
      };
      if (this.goodsStatus) params.goodsStatus = this.goodsStatus;
      if (this.serviceNo) params.serviceNo = this.serviceNo;
      const [res] = await orderApi.applySubmit(params);
      if (res) {
        this.$toast('申请成功');
        if (this.serviceNo) {
          const timer = setTimeout(() => {
            this.$router.go(-1);
            clearTimeout(timer);
          }, 500);
          return;
        }
        if (+this.type === 1) {
          this.$router.replace({
            name: 'refundOnlyDetail',
            query: {
              orderSkuId: this.orderSkuId,
              vccToken: localStorage.get('vccToken')
            }
          });
          return;
        }
        this.$router.replace({
          name: 'refundDetail',
          query: {
            orderSkuId: this.orderSkuId,
            vccToken: localStorage.get('vccToken')
          }
        });
      }
    },
    asyncRead(file) {
      const that = this;
      let idx = that.orderList.length;
      if (file.length + idx >= +this.maxLimit) {
        file = file.splice(0, this.maxLimit - idx);
      }
      for (let key of file) {
        const observable = upload(key, null, this.token);
        const observer = {
          next() {
            that.orderList[idx] = {
              status: 'uploading'
            };
            that.orderList = [...that.orderList];
          },
          error(err) {
            console.log(err);
          },
          complete({ hash }) {
            const fileLink = config.qiniuHost + '/' + hash;
            that.orderList[idx] = {
              url: fileLink,
              isImage: true,
              status: 'done'
            };
            that.orderList = JSON.parse(JSON.stringify([...that.orderList]));
            idx = idx + 1;
          }
        };
        observable.subscribe(observer); // 上传开始
      }
      return;
    },
    getToken() {
      orderApi.getQiniuToken().then(res => {
        this.token = res[0].token;
      });
    }
  }
};
</script>
<style lang="less" scoped>
.radiomark {
  position: relative;
  &::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 1;
  }
}
.refund {
  @{deep} .cr-cell__value {
    padding: @padding-xs;
    background: #f7f8fa;
    border-radius: @border-radius-md;
  }
  @{deep} .cr-field--word-limit {
    color: @gray-4;
  }
  @{deep} .cr-cell {
    .text-size(13);
    padding: @padding-md+1 @padding-lg;
  }

  &_content {
    .text-size(13);
    margin-top: @padding-xs+1;
    background: @white;
    &_wrapper {
      display: flex;
      // align-items: center;
    }
    &_gray {
      .text-size(11);
      color: @gray-4;
    }
    &_block {
      display: flex;
      flex-direction: column;
      flex-grow: 1;
      &_amount {
        display: flex;
        flex-flow: row nowrap;
        /deep/ .cr-field--control {
          input:disabled,
          input[disabled] {
            color: #333;
            opacity: 1;
            -webkit-text-fill-color: #333; // ios 和 安卓9.0 必须添加此属性，才会生效
            -webkit-opacity: 1;
          }
        }

        .cr-cell {
          padding: 0;
          &:last-child::after {
            border-bottom: none;
          }
        }
        @{deep} .cr-cell__value {
          background: #fff;
          padding: 0;
        }
      }
    }
    &_name {
      display: inline-block;
      padding-right: @padding-xl;
      flex-shrink: 0;
    }
    &_mdf {
      align-items: baseline;
      display: flex;
      flex-shrink: 0;
      color: rgba(200, 201, 204, 1);
      .text-size(12);
    }
    &_explain {
      &_title {
        display: block;
        padding: @padding-md+1 @padding-lg 0;
      }
    }
    .not-after::after {
      border-bottom: none !important;
    }
    .border-top::before {
      border-top: 1px solid #f2f3f5;
      position: absolute;
      box-sizing: border-box;
      content: ' ';
      pointer-events: none;
      top: 0rem;
      left: 0.426667rem;
      right: 0;
      transform: scaleY(0.5);
    }

    .refund-content-reason {
      background-color: rgba(247, 248, 250, 1);
      border-radius: 8px;
      margin: 0 20px 12px 20px;
      padding: 8px 10px 11px;
      color: #666666;
      font-size: 12px;
      .content {
        display: flex;
        flex-flow: row wrap;
        margin-top: 8px;
        .flex-col {
          max-height: 28px;
          border-radius: 20px;
          border: 1px solid rgba(220, 222, 224, 1);
          padding: 3px 7px;
          display: flex;
          justify-content: center;
          align-items: center;
          margin: 0 8px 4px 0px;
          flex-flow: row nowrap;
          &:first-child {
            margin-left: 0px;
          }
          .text {
            overflow-wrap: break-word;
            font-size: 12px;
            text-align: left;
            white-space: nowrap;
          }
        }
        .active {
          color: rgba(236, 21, 0, 1);
          border: 1px solid rgba(236, 21, 0, 1);
        }
      }
    }
    .refundType_un_select_gray {
      color: #999999;
    }
    .payment-account {
      .header {
        font-size: 14px;
        color: rgba(51, 51, 51, 1);
        font-weight: 500;
        margin: 17px 0 14px 20px;
      }
      .payment-account-item {
        height: 48px;
      }
      /deep/ .cr-cell {
        display: flex;
        justify-content: center;
        align-items: center;
      }
      /deep/ .cr-cell__value {
        background: none;
      }
    }
  }
  &_picture {
    background: @white;
    margin-top: @padding-xs+1;
    padding: @padding-md+1 @padding-lg;
    &_title {
      .text-size(13);
      padding-bottom: @padding-sm+1;
      span:last-child {
        color: @gray-4;
      }
    }
  }
  &_bottom {
    margin-top: @padding-xs*10;
    padding-bottom: @padding-xl+6;
    text-align: center;
    button {
      width: 335px;
      height: 40px;
      border-radius: 20px;
      background: @gradient-red;
      color: @white;
      .text-size(14);
    }
  }
}

.order-list {
  padding: 0 @padding-sm;
}
.cancel-popup {
  @{deep} .cr-popup--close-top-right {
    top: 18px;
    right: 14px;
  }
}

.Cp {
  &__head {
    text-align: center;
    height: 47px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 @padding-md;
    border-bottom: 1px solid @grey-border;
    &-title {
      .text-size(16);
      color: @text-color;
      font-weight: bold;
    }
    &-desc {
      .text-size(13);
      color: @text-grey;
    }
  }
  &__list {
    flex: 1;
    max-height: 400px;
    overflow-y: auto;
    margin-bottom: 40px;
    &-radio {
      margin-right: 0;
    }
  }
  &__button {
    border-top: 1px solid @grey-border;
    padding: @padding-sm - 2 @padding-xs;
  }
  &__tip {
    width: 343px;
    margin: @padding-xs auto;
    background-color: @gray-1;
    border-radius: @border-radius-md;
    color: @gray-5;
    .text-size(12);
    text-align: center;
    padding: @padding-sm @padding-xs;
  }
}
</style>
