<template>
  <div class="app-container">
    <el-card class="box-card card-spe-con">
      <!-- 状态页签 -->
      <el-tabs v-model="activeName" @tab-click="handleClick" class="after-sale-tabs">
        <el-tab-pane name="first">
          <div slot="label">未处理{{ numFormatter(untreatedNum) }}</div>
        </el-tab-pane>
        <el-tab-pane name="second">
          <div slot="label">处理中{{ numFormatter(inProcessNum) }}</div>
        </el-tab-pane>
        <el-tab-pane name="third">
          <div slot="label">已完成{{ numFormatter(completedNum) }}</div>
        </el-tab-pane>
      </el-tabs>
      <div class="table-all-con">
        <!-- 搜索条件 -->
        <el-form class="form-params" :model="queryParams" label-width="auto" :inline="true" size="small">
          <el-form-item label="申请时间" prop="applyTime">
            <el-date-picker
              v-model="queryParams.applyTime"
              type="daterange"
              align="left"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="商品名称" prop="goods_title">
            <el-input
              v-model="queryParams.goods_title"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="退换货类型" prop="refund_type">
            <el-select v-model="queryParams.refund_type" placeholder="全部类型" clearable width="120px">
              <el-option v-for="item in userNeedOptions" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="总订单号" prop="order_sn">
            <el-input
              style="width:250px;"
              v-model="queryParams.order_sn"
              placeholder="请输入商品订单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="商品订单号" prop="goods_order_sn">
            <el-input
              style="width:250px;"
              v-model="queryParams.goods_order_sn"
              placeholder="请输入商品订单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="买家手机号" prop="mobile">
            <el-input
              style="width:250px;"
              v-model="queryParams.mobile"
              placeholder="请输入买家手机号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="退换货原因" prop="reason">
            <el-select v-model="queryParams.reason" placeholder="全部类型" size="small" clearable>
              <el-option v-for="item in needMsgOptions" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="searchList">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 表头 -->
        <div class="table-header-spe">
          <el-table class="title_table hxz-el-table" align="center">
            <el-table-column label="商品图/商品名称" align="center"></el-table-column>
            <el-table-column label="退换货类型" align="center" width="120"></el-table-column>
            <el-table-column label="退换货原因" align="center" width="120"></el-table-column>
            <el-table-column label="申请时间" align="center" width="120"></el-table-column>
            <el-table-column label="到期时间" align="center" width="120"></el-table-column>
            <el-table-column label="买家手机号" align="center" width="120"></el-table-column>
            <el-table-column label="当前处理进度" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="120"></el-table-column>
          </el-table>
        </div>
        <!-- 列表 -->
        <div class="table-all-body-con">
          <el-card v-for="(item, index) in afterSaleList" :key="index" class="order-card">
            <div slot="header" class="el-card-header-spe">
              <div style="float:left;">
                <span>总订单号：</span>
                <span>{{ item.order_sn }}</span><span style="margin: 0 0 0 30px;">商品订单号：</span>
                <span>{{ item.goods_order_sn }}</span>
              </div>
              <div style="float:right;">
                <span>订单状态：</span>
                <span>{{ orderDeliveryFormatter(item.goods_status) }}</span>
              </div>
            </div>
            <div class="item-table">
              <el-table
                border
                :show-header="false"
                :data="[item]">
                <el-table-column label="商品图/商品名称" align="center">
                  <template slot-scope="scope">
                    <div class="img-title-table">
                      <img v-if="scope.row.thumb" style="width:60px;height:60px;" :src="scope.row.thumb"/>
                      <div class="ml10">{{ scope.row.title }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="退换货类型" align="center" width="120">
                  <template slot-scope="scope">
                    <span v-if="scope.row.refund_type == 1">仅退款</span>
                    <span v-if="scope.row.refund_type == 2">退货退款</span>
                  </template>
                </el-table-column>
                <el-table-column label="退换货原因" align="center" width="120">
                  <template slot-scope="scope">
                    <span v-if="scope.row.reason==1">协商一致退款</span>
                    <span v-if="scope.row.reason==2">质量问题</span>
                    <span v-if="scope.row.reason==3">物流问题</span>
                    <span v-if="scope.row.reason==4">假冒品牌</span>
                    <span v-if="scope.row.reason==5">少件/漏发/破损/污渍</span>
                    <span v-if="scope.row.reason==6">7天无理由</span>
                    <span v-if="scope.row.reason==7">拍错/多拍/不想要</span>
                    <span v-if="scope.row.reason==8">其他</span>
                  </template>
                </el-table-column>
                <el-table-column label="申请时间" align="center" width="120">
                  <template slot-scope="scope">
                    {{formatter(scope.row.created_time)}}
                  </template>
                </el-table-column>
                <el-table-column label="到期时间" align="center" width="120">
                  <template slot-scope="scope">
                    <span v-if="scope.row.status==5">-</span>
                    <span v-else>{{formatter(scope.row.deadline)}}</span>
                    
                  </template>
                </el-table-column>
                <el-table-column prop="mobile" label="买家手机号" align="center" width="120"></el-table-column>
                <el-table-column label="当前处理进度" align="center" :formatter="refundStatusText"></el-table-column>
                <el-table-column label="操作" align="center" width="120">
                  <template slot-scope="scope">
                    <el-button size="small" type="text" @click="handleInfo(scope.row)">详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </div>
        <!-- 分页 -->
        <div class="pagination-con" v-if="total > 0">
          <el-pagination
            :page-size="pageSize"
            :current-page="currentPage"
            :page-sizes="[20, 40, 60, 80, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>

    </el-card>

    <!-- 售后详情 弹窗 -->
    <el-dialog title="售后详情" width="75%" class="after-sale-dialog" :visible.sync="dialogAfterSale"
               :destroy-on-close="true" :close-on-click-modal="false" center>
      <Edit v-if="dialogAfterSale" :as-good-id="asGoodId"></Edit>
    </el-dialog>
  </div>
</template>

<script>
  import {getRetreatList, getTabCountData} from '@/api/module/retreat'
  import {dateFormat} from '@/utils'
  import Edit from './../edit'

  export default {
    name: "Index",
    components: {
      Edit
    },
    data() {
      return {
        goodsStatus: 1,
        activeName: 'first',
        untreatedNum: '', // 未处理
        inProcessNum: '', // 处理中
        completedNum: '', // 已完成
        queryParams: {
          status: 0,
          applyTime: [],
          order_sn: '',
          goods_title: '',
          refund_type: '',
          goods_order_sn: '',
          reason: '',
          mobile:''
        },
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        // 退换货类型
        userNeedOptions: [
          {value: -1, label: '全部类型'},
          {value: 1, label: '仅退款'},
          {value: 2, label: '退货退款'},
        ],
        // 退换货原因
        needMsgOptions: [
          {value: -1, label: '全部原因'},
          {value: 1, label: '协商一致退款'},
          {value: 2, label: '质量问题'},
          {value: 3, label: '物流问题'},
          {value: 4, label: '假冒品牌'},
          {value: 5, label: '少件/漏发/破损/污渍'},
          {value: 6, label: '7天无理由'},
          {value: 7, label: '拍错/多拍/不想要'},
          {value: 8, label: '其他'},
        ],
        // fullHeight: 0,
        // afterSaleHeight: 200,
        currentPage: 1,
        pageSize: 20,
        total: 0,
        // 售后列表
        afterSaleList: [],
        // 售后详情
        dialogAfterSale: false,
      }
    }, // data end
    watch: {
      // fullHeight(val) {
      //   let formHeight = document.getElementsByClassName('form-params')[0].clientHeight;
      //   let tabsHeight = document.getElementsByClassName('after-sale-tabs')[0].clientHeight;
      //   this.afterSaleHeight = val - formHeight -tabsHeight - 40 - 40
      // }
    },
    created() {
      // this.$nextTick(() => {
      //   this.fullHeight = document.getElementsByClassName('box-card')[0].clientHeight
      // })
    },
    mounted() {
      this.searchList();
      this.getTabCount();
      // let fuck = 'undefined'
      // let a = Number(fuck)
      // console.log(250,a);
    },
    methods: {
      /** 发货状态 */
      orderDeliveryFormatter(status) {
        let text = '-'
        if (status == 0) {
          text = '未发货'
        }else if (status == 1) {
          text = '已发货'
        }else if (status == 2) {
          text = '已收货'
        }else if (status == 3) {
          text = '配货中'
        }else if (status == 4) {
          text = '拒收'
        }
        return text
      },
      /** 获取 售后 tab 数量 */
      getTabCount() {
        getTabCountData().then(res => {
          if (res.code == 1) {
            this.untreatedNum = res.data.untreated_num
            this.inProcessNum = res.data.in_process_num
            this.completedNum = res.data.completed_num
          }
        });
      },
      /** tab 数量 转化 */
      numFormatter(num) {
        let numStr = ''
        let number = Number(num);
        if (number) {
          numStr = number <= 99 ? '（' + num + '）' : '（99+）'
        } else {
          numStr = ""
        }
        // if (num == '' || num == 0) {
        //   numStr = ''
        // } else if (0 < num <= 99) {
        //   numStr = '（' + num + '）'
        // } else if (num > 99) {
        //   numStr = '99+'
        // }
        return numStr
      },
      /** 顶部 状态页签切换
       * 1-未处理；2-处理中；3-已完成
       * */
      handleClick() {
        // 搜索条件初始化
        this.resetSearchParams();

        switch (this.activeName) {
          case 'first':
            this.goodsStatus = 1
            break
          case 'second':
            this.goodsStatus = 2
            break
          case 'third':
            this.goodsStatus = 3
            break
          default:
            break
        }
        // 列表 查询
        this.getList();
      },
      /** 时间格式处理 */
      // applyTimeChange() {
      //   if( !Array.isArray(this.queryParams.applyTime) ) {
      //     this.queryParams.applyTime = [];
      //   }
      // },
      /** 售后进度 文案 */
      refundStatusText(row) {
        let text = '--'
        if(row.close_reason == 6) {
          text = '买家取消，售后关闭'
        }else {
          if (row.refund_type == 1) {
            if(row.status == 1) {
              text = '等待卖家同意仅退款'
            } else if (row.status == 5) {
              text = '卖家同意退款，售后完成'
            } else if (row.status == -1) {
              text = '卖家拒绝仅退款，售后关闭'
            }
          } else if (row.refund_type == 2) {
            if(row.status == 1) {
              text = '等待卖家同意退货退款'
            } else if (row.status == 2) {
              text = '等待买家退货'
            } else if (row.status == 3) {
              text = '等待卖家同意退款或拒收包裹'
            } else if (row.status == 5) {
              text = '卖家收货、同意退款，退款完成'
            } else if (row.status == -1) {
              text = '卖家拒绝退货退款'
            }
          }
        }

        return text
      },
      searchList() {
        this.currentPage = 1;
        this.getList();
      },
      /** 列表查询 */
      getList() {
        let params = {
          page: this.currentPage,
          limit: this.pageSize,
          status: this.goodsStatus,
        }

        if (this.queryParams.applyTime && this.queryParams.applyTime.length === 2) {
          params['apply_start_time'] = new Date(this.queryParams.applyTime[0]).getTime() / 1000
          params['apply_end_time'] = new Date(this.queryParams.applyTime[1]).getTime() / 1000
        }

        if (this.queryParams.goods_title != '') {
          params['goods_title'] = this.queryParams.goods_title;
        }

        if (this.queryParams.refund_type != -1 && this.queryParams.refund_type != '') {
          params['refund_type'] = this.queryParams.refund_type;
        }

        if (this.queryParams.goods_order_sn != '') {
          params['goods_order_sn'] = this.queryParams.goods_order_sn;
        }

        if (this.queryParams.order_sn != '') {
          params['order_sn'] = this.queryParams.order_sn.trim();
        }
        if (this.queryParams.mobile != '') {
          params['mobile'] = this.queryParams.mobile;
        }

        if (this.queryParams.reason != -1 && this.queryParams.reason != '') {
          params['reason'] = this.queryParams.reason;
        }

        getRetreatList(params).then(res => {
          if (res.code === 1) {
            this.afterSaleList = res.data.data;
            this.total = res.data.count;
          }
        });

        this.getTabCount();
      },
      /** 重置 操作 */
      resetQuery() {
        this.resetSearchParams();
        this.getList();
      },
      /** 售后 订单 详情 */
      handleInfo(row) {
        // let id = row.refund_sn ? row.refund_sn : '';
        this.asGoodId = row.refund_sn ? row.refund_sn : ''
        // this.$router.push({
        //   path: '/system/repeat/edit',
        //   query: { refund_sn: id }
        // });
        this.dialogAfterSale = true;
      },
      /** 调整 列表当前页面 最大展示条数 */
      handleSizeChange(val) {
        this.pageSize = val;
        this.getList();
      },
      /** 列表 跳转到 第 几 页 */
      handleCurrentChange(val) {
        this.currentPage = val
        this.getList();
      },
      /** 搜索条件初始化 */
      resetSearchParams() {
        this.pageSize = 20;
        this.currentPage = 1;
        this.queryParams = {
          status: 0,
          applyTime: [],
          order_sn: '',
          goods_title: '',
          refund_type: '',
          goods_order_sn: '',
          reason: '',
          mobile: ''
        }
      },
      /** 搜索条件 键盘enter */
      handleQuery() {

      },
      /** 时间戳转化 格式化 */
      formatter(time) {
        return dateFormat(time * 1000, 'Y-m-d H:i:s')
      },
    } // methods end
  }
</script>

<style scoped>
  .card-spe-con {
    height: 100%;
    /*overflow: auto;*/
  }
  .card-spe-con ::v-deep  .el-card__body {
    height: calc(100% - 40px);
    overflow: hidden;
  }
  /*::v-deep  .el-dialog__body {*/
  /*  height: 100%;*/
  /*  overflow: hidden;*/
  /*}*/
  ::v-deep  .el-tabs__header{
    margin: 0;
  }
  ::v-deep  .after-sale-tabs .el-tabs__item {
    line-height: 30px;
  }

  ::v-deep  .el-form--inline .el-form-item {
    margin-right: 15px;
  }

  .table-all-con {
    height: calc(100% - 40px);
    overflow: auto;
    padding-top: 15px;
  }

  .table-all-body-con {
    /*height: calc(100% - 102px);*/
    /*overflow: auto;*/
  }

  /* 列表table 样式 */
  .order-card {
    margin: 10px 0 12px;
  }

  .order-card ::v-deep  .el-card__header {
    padding: 0;
    min-height: fit-content;
  }

  .el-card-header-spe {
    overflow: hidden; /* 此为父元素，子元素都浮动了，所以，这样处理，撑开自己的高度 */
    font-size: 14px;
    padding: 10px 12px;
    background-color: #f0f0f5;
    /*background-color: #909399;*/
  }

  .table-header-spe {
    background-color: #F7F8FA;
    padding: 0 34px 0 22px;
    margin: 5px 0;
  }

  ::v-deep  .title_table .el-table__body-wrapper {
    display: none !important;
    height: 0 !important;
  }

  ::v-deep  .title_table tr th {
    border-bottom: 0 !important;
  }

  ::v-deep  .title_table::before {
    height: 0;
  }

  .img-title-table {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .ml10 {
    margin-left: 10px;
  }

  .pagination-con {
    text-align: center;
    margin-top: 15px;
  }

  .after-sale-dialog {
    height: 90%;
    overflow: hidden;
  }

  .after-sale-dialog ::v-deep  .el-dialog {
    overflow: hidden;
    height: 100%;
  }

  .after-sale-dialog ::v-deep  .el-dialog__body {
    overflow: auto;
    height: calc(100% - 120px);
    padding: 10px 20px;
  }
</style>
