<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.aftersaleSn" clearable class="filter-item" style="width: 180px;"
                placeholder="请输入售后编号"/>
      <el-input v-model="listQuery.orderSn" clearable class="filter-item" style="width: 180px;"
                placeholder="请输入订单编号"/>
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 170px;"
                placeholder="请输入客户手机号码"/>
      <el-select v-model="listQuery.status" clearable class="filter-item" placeholder="请选择售后状态"  style="width: 150px;">
        <el-option value="1" label="待审核"/>
        <el-option value="2" label="待退款"/>
        <el-option value="3" label="已退款"/>
        <el-option value="4" label="已拒绝"/>
        <el-option value="5" label="用户取消"/>
        <el-option value="6" label="退款中"/>
      </el-select>
      <el-select v-model="listQuery.orderChannel" clearable class="filter-item" placeholder="请选择订单渠道"  style="width: 150px;">
        <el-option value="5" label="商城"/>
        <el-option value="26" label="抖音"/>
        <el-option value="103" label="快手"/>
        <el-option value="104" label="美团"/> 
      </el-select>
      <el-date-picker v-model="timeArray" type="datetimerange" class="filter-item" style="width:320px"
                      range-separator="至"
                      start-placeholder="申请开始日期" end-placeholder="申请结束日期" :picker-options="{}"
                      value-format="yyyy-MM-dd HH:mm:ss"/>
      <el-button v-permission="['GET /admin/aftersale/list']" class="filter-item" type="primary" icon="el-icon-search"
                 @click="handleFilter">查找
      </el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                 @click="handleDownload">导出
      </el-button>
    </div>

    <div class="operator-container" v-if="tab == 'uncheck'">
      <el-button v-permission="['GET /admin/aftersaleSn/batch-recept']" class="filter-item" type="success"
                 icon="el-icon-info" @click="handleBatchReceptConfirm">批量通过
      </el-button>
      <el-button v-permission="['GET /admin/aftersale/batch-reject']" class="filter-item" type="danger"
                 icon="el-icon-delete" @click="handleBatchReject">批量拒绝
      </el-button>
    </div>

    <el-tabs v-model="tab" @tab-click="handleClick">
      <el-tab-pane label="全部" name="all"/>
      <el-tab-pane label="待审核" name="uncheck"/>
      <el-tab-pane label="待退款" name="unrefund"/>
    </el-tabs>

    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" fit highlight-current-row
              @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55"/>
      <el-table-column align="center" label="售后编号" prop="aftersaleSn" width="150px"/>

      <el-table-column align="center" label="订单信息" prop="amount" width="300px">
        <template slot-scope="scope">
          <div style="text-align: left;">
            <span style="font-weight: 600;">订单编号:</span>{{ scope.row.order.orderSn }}<br/>
            <span style="font-weight: 600;">服务商品:</span>{{ scope.row.goodsName }}<br/>
            <span style="font-weight: 600;">下单时间:</span>{{ scope.row.order.createTime }}<br/>
            <span style="font-weight: 600;">服务属性:</span><span style="color:#09afff">{{
              scope.row.fraId == 293 ? "直营" :
                "加盟"
            }}</span>
            <span style="font-weight: 600;">订单渠道:</span>
            <el-tag>{{
                scope.row.order.orderChannel | channelsFilter
              }}
            </el-tag>
            <br/>
            <span style="font-weight: 600;">订单金额:</span> {{ scope.row.order.actualPrice }}<br/>
            <span style="font-weight: 600;">订单状态:</span>
            <el-tag :type="tagValue(scope.row.order.orderStatus)">{{
                scope.row.order.orderStatus | orderStatusFilter
              }}
            </el-tag>
            <span
              style="font-weight: 600;">预约状态</span>:
            <el-tag :type="tagValue(scope.row.bookStatus)">{{
                scope.row.bookStatus
              }}
            </el-tag>
            <br/>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="负责加盟商" prop="fraId" width="240">
        <template slot-scope="scope">
          <div style="text-align: left;">
            <span style="font-weight: 600;">加盟商Id:</span> {{ scope.row.fraId }}<br/>
            <span style="font-weight: 600;">加盟商名称:</span> {{ scope.row.fraName }}<br/>
            <span style="font-weight: 600;">联系方式:</span> {{ scope.row.fraMobile }}<br/>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="退款信息" prop="amount" width="230">
        <template slot-scope="scope">
          <div style="text-align: left;">
            <span style="font-weight: 600;">退款类型:</span>
            <el-tag :type="typeTag[scope.row.type]">{{
                refundTypeFilter(scope.row.type)
              }}
            </el-tag>
            <br/>
            <span style="font-weight: 600;">退款原因:</span> {{ scope.row.reason }}<br/>
            <span style="font-weight: 600;">退款金额:</span> {{ scope.row.amount }}<br/>
            <span style="font-weight: 600;">申请时间:</span> {{ scope.row.addTime }}<br/>
            <span v-if="scope.row.order.orderChannel == 103 && scope.row.status == 1" style="color: red;">
                <span style="font-weight: 900;">强退时间：</span>{{ expireTime(scope.row.addTime) }}<br/>
              </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="退款凭证图片" prop="picUrls">
        <template slot-scope="scope">
          <el-image v-for="item in scope.row.pictures" :key="item" :src="item" :preview-src-list="scope.row.pictures"
                    :lazy="true" style="width: 60px; height: 60px; margin-right: 5px;float:left;"/>
        </template>
      </el-table-column>

      <el-table-column align="center" label="退款处理" prop="amount" width="215">
        <template slot-scope="scope">
          <div style="text-align: left;">
            <span style="font-weight: 600;">处理结果:</span>
            <el-tag type="success">{{
                statusDesc[scope.row.status]
              }}
            </el-tag>
            <br/>
            <span style="font-weight: 600;">拒绝原因:</span> {{ scope.row.refusalRemark }}<br/>
            <span style="font-weight: 600;">退款处理人:</span> {{ scope.row.reundOperName }}<br/>
            <span style="font-weight: 600;">处理时间:</span> {{ scope.row.updateTime }}<br/>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="退款价格" prop="amount" />
      <el-table-column align="center" label="申请时间" prop="addTime" />
      <el-table-column align="center" label="处理结果" prop="status">
        <template slot-scope="scope">
          <el-tag type="success">{{ statusDesc[scope.row.status] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="拒绝原因" prop="refusalRemark" />

      <el-table-column align="center" label="退款处理人" prop="reundOperName" />
      <el-table-column align="center" label="处理时间" prop="updateTime" /> -->

      <el-table-column align="center" label="操作" min-width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleRead(scope.row)">详情</el-button>
          <el-button v-permission="['GET /admin/aftersale/getAftersaleLog']" type="primary" size="mini"
                     @click="handleAftersaleLog(scope.row)">操作日志
          </el-button>
          <el-button v-if="scope.row.status === 1" v-permission="['POST /admin/aftersale/recept']" type="success"
                     size="mini" @click="handleRefundCheck(scope.row)">通过
          </el-button>
          <el-button v-if="scope.row.status === 1" v-permission="['POST /admin/aftersale/reject']" type="danger"
                     size="mini" @click="handleReject(scope.row)">拒绝
          </el-button>
          <el-button v-if="scope.row.status === 2" v-permission="['POST /admin/aftersale/refund']" type="warning"
                     size="mini" @click="handleRefund(scope.row)">退款
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>

    <!-- 退款对话框 -->
    <el-dialog :visible.sync="refundDialogVisible" title="退款审核">
      <el-form ref="refundForm" :model="refundForm" :rules="rules" status-icon label-position="left" label-width="100px"
               style="width: 400px; margin-left:50px;">
        <el-form-item label="退款金额" prop="refundMoney">
          <!-- <el-input v-model="refundForm.refundMoney" :disabled="true" /> -->
          <el-input v-model="refundForm.refundMoney"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确定</el-button>
      </div>
    </el-dialog>
    <!-- 审核拒绝原因 -->
    <el-dialog :visible.sync="rejectFormDialogVisible" title="审核拒绝" width="800px">
      <el-form ref="rejectForm" :model="rejectForm" :rules="rejectRules" status-icon label-position="left"
               label-width="150px" style="width: 700px; ">
        <el-form-item label="拒绝内容" prop="reason">
          <el-input v-model="rejectForm.reason" type="textarea" placeholder="请输入拒绝原因" rows="3" maxlength="50"
                    show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rejectFormDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确定</el-button>
      </div>
    </el-dialog>

    <!-- 操作日志 -->
    <el-dialog :visible.sync="afterSaleLogDialogVisible" title="操作日志" center width="800px">
      <el-table :data="afterSaleLogList" style="width: 100%" border>
        <el-table-column label="操作人" prop="handlerName" width="200px">
        </el-table-column>
        <el-table-column prop="statusName" label="操作类型">
        </el-table-column>
        <el-table-column prop="comment" label="操作内容"></el-table-column>
        <el-table-column prop="createTime" label="操作时间"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="afterSaleLogDialogVisible = false">确定</el-button>
      </div>
    </el-dialog>

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100"/>
    </el-tooltip>


    <!-- 订单详情对话框 -->
    <orderInfoRef ref="orderInfoRef"/>

  </div>
</template>

<script>
import {
  aftersaleExport,
  batchReceptAftersale,
  batchRejectAftersale,
  checkBookStatus,
  listAftersale,
  receptAftersale,
  refundAftersale,
  rejectAftersale
} from "@/api/aftersale";
import moment from "moment";
import {list} from '@/api/dmRefund';
import {allChannel} from "@/api/channel";
import {getAftersaleLog} from "@/api/order";
import BackToTop from "@/components/BackToTop";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import {formatDate} from "@/utils/date";
import orderInfoRef from '@/views/order/components/orderInfoRef.vue'
import {statusMap,} from "@/api/enumUtils";
import _ from "lodash";

let vm;

export default {
  name: "Aftersale",
  components: {BackToTop, Pagination, orderInfoRef},
  beforeCreate() {
    vm = this;
  },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status];
    },
    channelsFilter(value) {
      const rs = vm.channels.filter((item) => {
        return item.id === value;
      });
      if (rs != null && rs.length > 0) {
        return rs[0].name;
      }
    },
  },
  data() {
    return {
      channels: [],
      list: [],
      total: 0,
      listLoading: true,
      tab: "all",
      timeArray: ['', ''],
      listQuery: {
        page: 1,
        limit: 20,
        aftersaleSn: undefined,
        orderId: undefined,
        orderSn: "",
        status: "",
        sort: "add_time",
        order: "desc",
      },
      typeTag: ["", "success", "warning"],
      // typeDesc: [
      //     "7天无理由退货",
      //     "个人原因 不喜欢",
      //     "价格问题",
      //     "发票问题",
      //     "物流问题",
      //     "质量问题",
      //     "未收货退款",
      //     "不退货退款",
      //     "退货退款",
      // ],
      typeDesc: [
        '未收货退款', '预约不上', '服务态度差', '门店定位问题', '买贵了', '不喜欢/不想要了', '约不到想要的服务时间', '超服务内容范围', '搬家了', '服务者离职'
      ],
      refundTypes: [],//退款原因
      citys: {
        1: '上海',
        2: '北京',
        3: '深圳',
        4: '南京',
        5: '苏州',
        6: '',
        7: '杭州',
        8: '青岛',
        9: '',
        10: '广州',
        11: '成都',
        12: '重庆',
        13: '昆山',
        15: "包头",
        16: "保定"
      },
      statusDesc: [
        "未申请",
        "待审核",
        "待退款",
        "已退款",
        "拒绝",
        "取消",
        "退款中",
      ],
      statusMap: statusMap,
      multipleSelection: [],
      contentDetail: "",
      contentDialogVisible: false,
      downloadLoading: false,
      orderDialogVisible: false,
      afterSaleLogDialogVisible: false,
      afterSaleLogList: [],
      orderDetail: {
        order: {},
        user: {},
        orderGoods: [],
      },
      rules: {
        refundMoney: [
          {required: true, message: "请输入退款金额", trigger: "blur"}
        ]
      },
      refundForm: {
        id: '',
        refundMoney: undefined
      },
      refundMoney: '',
      refundDialogVisible: false,
      rejectType: '',
      rejectFormDialogVisible: false,
      rejectForm: {
        id: '',
        reason: ''
      },
      rejectRules: {
        reason: [
          {required: true, message: '请输入拒绝原因', trigger: 'change'}
        ]
      },
      refundRow: {}
    };
  },
  created() {
    this.getList();
    allChannel().then((res) => {
      this.channels = res.data.data;
    });
    this.getRefundType();
  },
  methods: {
    getList() {
      this.listLoading = true;
      if (this.timeArray && this.timeArray.length === 2) {
        this.listQuery.start = this.timeArray[0];
        this.listQuery.end = this.timeArray[1];
      } else {
        this.listQuery.start = null;
        this.listQuery.end = null;
      }

      listAftersale(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    expireTime(time) {
      return moment(time).add(72, "hours").format("YYYY-MM-DD HH:mm:ss");
    },
    getRefundType() {
      list({page: 1, limit: 200}).then(res => {
        this.refundTypes = res.data.data.list
      })
    },
    tagValue(status) {
      if (status == "已退款" || status == "退款" || status == "202" || status == "203")
        return "warning";

      if (status == "待履约")
        return "success";

      return "";
    },
    refundTypeFilter(type) {
      if (type && type == 0) return "7天无理由退货";
      const rs = vm.refundTypes.filter(item => {
        return item.id == type;
      })
      if (rs && rs.length > 0) return rs[0].name;
      else return "";
    },
    formatTime(time) {
      if (time == null || time === "") {
        return "";
      }
      const date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    formatStepStatus(value, time) {
      if (value === 201) {
        // 待发货
        return 2;
      } else if (value === 301) {
        // 已发货
        return 3;
      } else if (value === 401 || value === 402) {
        // 已完成
        if (time != null && time != "undefined") {
          return 5;
        } else {
          return 4;
        }
      } else {
        // 待付款、已关闭、无限订单
        return 1;
      }
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleClick() {
      if (this.tab === "all") {
        this.listQuery.status = "";
      } else if (this.tab === "uncheck") {
        this.listQuery.status = "1";
      } else if (this.tab === "unrefund") {
        this.listQuery.status = "2";
      }
      this.getList();
    },
    handleRecept(row) {
      receptAftersale(row)
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: "审核通过操作成功",
          });
          this.getList();
        })
        .catch((response) => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg,
          });
        });
    },
    handleRead(row) {

      this.$refs.orderInfoRef.getDetail(row.orderId);
      // detailOrder(row.orderId).then((response) => {
      //   this.orderDetail = response.data.data;
      // });
      // this.orderDialogVisible = true;
    },
    handleAftersaleLog(row) {
      getAftersaleLog(row.id).then((response) => {
        this.afterSaleLogList = response.data.data;
      });
      this.afterSaleLogDialogVisible = true;
    },
    handleBatchReceptConfirm() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择至少一条记录");
        return;
      }
      const ids = [];
      _.forEach(this.multipleSelection, function (item) {
        ids.push(item.id);
      });

      this.$confirm(
        "确定批量接受售后订单吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.handleBatchRecept(ids);
      });
    },
    handleBatchRecept(ids) {
      batchReceptAftersale({ids: ids})
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: "批量通过操作成功",
          });
          this.getList();
        })
        .catch((response) => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg,
          });
        });
    },
    handleReject(row) {
      this.rejectType = 1;
      this.rejectFormDialogVisible = true;
      this.rejectForm = row;
      this.rejectForm.reason = '';
    },
    confirmReject() {
      this.$refs['rejectForm'].validate((valid) => {
        if (valid) {
          if (this.rejectType == 1) {
            this.rejectForm.refusalRemark = this.rejectForm.reason;
            rejectAftersale(this.rejectForm).then(res => {

              this.$notify.success({
                title: "成功",
                message: "审核拒绝操作成功",
              });
              this.getList();
              this.rejectFormDialogVisible = false;
            }).catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg,
              });
            });
          } else {

            batchRejectAftersale(this.rejectForm)
              .then((response) => {
                this.$notify.success({
                  title: "成功",
                  message: "批量拒绝操作成功",
                });
                this.rejectFormDialogVisible = false;
                this.getList();
              })
              .catch((response) => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.errmsg,
                });
              });

          }

        }
      })
    },
    handleBatchReject() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择至少一条记录");
        return;
      }
      this.rejectType = 2;
      const ids = [];
      _.forEach(this.multipleSelection, function (item) {
        ids.push(item.id);
      });
      this.rejectType = 2;
      this.rejectFormDialogVisible = true;
      this.rejectForm = {
        ids: ids,
        reason: ''
      }
    },
    handleRefund(row) {
      // console.log("row data:"+JSON.stringify(row));
      const loading = this.$loading({
        lock: true,
        text: "同步中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.5)",
      });
      refundAftersale({id: row.id, amount: row.amount})
        .then(response => {
          loading.close();
          this.refundDialogVisible = false;
          this.$notify.success({
            title: "成功",
            message: "退款操作成功"
          });
          this.getList();
        })
        .catch(response => {
          loading.close();
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },
    handleRefundCheck(row) {
      this.refundDialogVisible = true;
      this.refundForm.id = row.id;
      this.refundForm.orderId = row.orderId;
      this.refundForm.orderSn = row.orderSn;
      this.refundForm.refundMoney = row.amount;
      this.refundMoney = row.amount;
      this.refundRow = row;
    },
    confirmRefund() {
      if (Number(this.refundForm.refundMoney) === 0) {
        this.$message.warning("申请退款金额不能为零!");
      }
      this.refundRow.amount = this.refundForm.refundMoney;
      checkBookStatus(this.refundRow).then(res => {
        if (res.data.errno == 0) {
          let data = res.data.data;
          if (data.code == 0) {//允许退款
            this.refundDialogVisible = false;
            this.handleRecept(this.refundRow);
          } else if (data.code == 1) {
            this.$confirm(
              data.msg,
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            ).then(() => {
              this.refundDialogVisible = false;
              this.handleRecept(this.refundRow);
            });
          } else {
            this.$message.warning(data.msg);
          }
        }
      }).catch(res => {
        this.$notify.error({
          title: "失败",
          message: res.data.errmsg
        });
      })
    },
      isMoreThan10Days(date1, date2) {
    var diff = Math.abs((new Date(date2)) - (new Date(date1))); //计算两个日期之间的毫秒数差值
    return diff > 10 * 24 * 60 * 60 * 1000; //将毫秒转换为天数并与10进行比较
    },
    handleDownload() {
      if (this.timeArray && this.timeArray.length === 2) {
        this.listQuery.start = this.timeArray[0];
        this.listQuery.end = this.timeArray[1];
      } else {
        this.$message.warning('请选择申请时间，不可超过10天');
        return ;
      }
      if(this.listQuery.start==''|| this.listQuery.end==''){
        this.$message.warning('请选择申请时间，不可超过10天');
        return;
      }
      console.log(this.isMoreThan10Days(this.timeArray[0], this.timeArray[1]));
      if(this.isMoreThan10Days(this.timeArray[0], this.timeArray[1])){
        this.$message.warning('请选择申请时间，不可超过10天');
        return;
      }
      this.downloadLoading = true;
      aftersaleExport({
        start: this.listQuery.start,
        end: this.listQuery.end,
        orderChannel: this.listQuery.orderChannel,
        afterOrderStatus:this.listQuery.status
      })
        .then(res => {
          this.downloadLoading = false;
          let blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          //console.log(blob)
          let fileName = "售后数据.xlsx";
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName);
          } else {
            var link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
            //释放内存
            window.URL.revokeObjectURL(link.href);
          }
        })
        .catch(err => {
          this.downloadLoading = false;
          this.$message.warning(err.data.errmsg);
        });
      this.downloadLoading = false;
    },
  },
};
</script>

<style>
.detail-container {
  width: 80%;
  padding: 20px 20px 20px 20px;
  margin: 20px auto;
}

.operate-container {
  background: #f2f6fc;
  height: 80px;
  margin: -20px -20px 0;
  line-height: 80px;
}

.operate-button-container {
  float: right;
  margin-right: 20px;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
}

.table-cell {
  height: 60px;
  line-height: 40px;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  overflow: hidden;
}

.table-cell-title {
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  background: #f2f6fc;
  text-align: center;
  font-size: 14px;
  color: #303133;
}

.el-table th.gutter {
  display: table-cell !important;
}

.color-danger {
  color: #f56c6c;
  font-size: 18px;
}</style>
