<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">

      <el-select v-model="listQuery.cityIds" clearable style="width: 200px" class="filter-item" placeholder="请选择城市" multiple>
        <el-option v-for="item in city" :key="item.id" :label="item.cityName" :value="item.id" />
      </el-select>

      <el-select v-model="listQuery.goodsIds" clearable style="width: 200px" class="filter-item" placeholder="请选择商品" multiple>
        <el-option v-for="item in goodsList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>

      <el-date-picker v-model="listQuery.timeArray" type="datetimerange" class="filter-item" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" />

      <el-button v-permission="['GET /admin/stat/gmvlist']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="城市" prop="cityName" fixed="left" width="135" />
      <el-table-column align="center" label="月份" width="135" prop="months" />
      <el-table-column align="center" label="门店" prop="shopName" />

      <el-table-column align="center" label="订单状态" prop="orderStatus" />

      <el-table-column align="center" label="销售gmv" prop="gmv" />
      <el-table-column align="center" label="客户数量" prop="customerSum" />
      <el-table-column align="center" label="订单数量" prop="orderSum" />
      <el-table-column align="center" label="支付总金额" prop="sumActualPrice" />

      <!-- <el-table-column
        align="center"
        label="操作"
        class-name="small-padding fixed-width"
        fixed="right"
        width="140"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['GET /admin/orderbook/detail']"
            type="primary"
            size="mini"
            @click="handleDetail(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"
    /> -->

  </div>
</template>

<script>
import axios from "axios";
import { gmvlist, getAllGoods } from "@/api/stat";
import {
  orderBookList,
  orderBookDetail,
  orderBookReassign,
  cancelBook,
  getAssignmentPerson,
} from "@/api/order";
import { allChannel } from "@/api/channel";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { formatDate } from "@/utils/date";
import checkPermission from "@/utils/permission"; // 权限判断函数
import { getToken } from "@/utils/auth";
import { listAllCity } from "@/api/city";

let vm;

const statusMap = {
  0: "未预约",
  1: "已预约",
  2: "服务中",
  3: "服务已提供",
  4: "服务已完成",
  5: "取消", //取消-未付款
  6: "退款",
};

export default {
  name: "Order",
  components: { Pagination },
  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 {
      list: [],
      total: 0,
      listLoading: true,
      city: [],
      goodsList: [],
      listQuery: {
        timeArray: [],
        cityIds: [],
        goodsIds: [],
      },
      rules: {
        bookDate: [
          { required: true, message: "请选择改派日期", trigger: "blur" },
        ],
        bookTime: [
          { required: true, message: "请选择改派时间", trigger: "blur" },
        ],
        servantId: [
          { required: true, message: "请选择服务者", trigger: "blur" },
        ],
      },
      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]);
            },
          },
        ],
      },
      channels: [],
      statusMap,
      orderDialogVisible: false,
      reassignDialogVisible: false,
      orderDetail: [],
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined,
      },
      importForm: {
        channelId: 1,
        file: undefined,
        filename: undefined,
      },

      reassignForm: {
        id: "",
        bookDate: "",
        bookTime: "",
        servantId: "",
        orderId: "",
      },
      shipDialogVisible: false,
      refundForm: {
        orderId: undefined,
        refundMoney: undefined,
      },
      refundDialogVisible: false,
      importLoading: false,
      headers: { "Content-Type": "multipart/form-data" },
    };
  },
  computed: {},
  beforeCreate() {
    vm = this;
  },
  created() {
    this.getList();
    listAllCity().then((res) => {
      this.city = res.data.data;
    });
    getAllGoods().then((res) => {
      this.goodsList = res.data.data;
    });
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true;
      let createTime = null;
      let endTime = null;
      if (this.listQuery.timeArray && this.listQuery.timeArray.length === 2) {
        createTime = this.listQuery.timeArray[0];
        endTime = this.listQuery.timeArray[1];
      }
      let params = {
        createTime: createTime,
        endTime: endTime,
        goodsIds: this.listQuery.goodsIds.join(","),
        cityIds: this.listQuery.cityIds.join(","),
      };
      gmvlist(params)
        .then((response) => {
          this.list = response.data.data.list;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    cityFilter(address) {
      if (address) {
        if (address.indexOf("上海市") >= 0) return "上海市";
        if (address.indexOf("北京市") >= 0) return "北京市";
        if (address.indexOf("南京") >= 0) return "南京市";
        if (address.indexOf("深圳") >= 0) return "深圳市";
        if (address.indexOf("苏州") >= 0) return "苏州市";
        if (address.indexOf("无锡") >= 0) return "无锡市";
        if (address.indexOf("杭州") >= 0) return "杭州市";
        if (address.indexOf("宜昌") >= 0) return "宜昌市";
        if (address.indexOf("青岛") >= 0) return "青岛市";
        if (address.indexOf("成都") >= 0) return "成都市";
        if (address.indexOf("重庆") >= 0) return "重庆市";
        if (address.indexOf("广州") >= 0) return "广州市";
      }
      return "";
    },
    formatTime(time) {
      if (time == null || time === "") {
        return "";
      }
      const date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    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;
      }
    },
    handleDetail(row) {
      // orderBookDetail(row.orderId).then(response => {
      //   this.orderDetail = response.data.data
      // });
      this.orderBookDetail(row.orderId);
      this.orderDialogVisible = true;
    },
    orderBookDetail(orderId) {
      orderBookDetail(orderId).then((response) => {
        this.orderDetail = response.data.data;
      });
    },
    handleCancel(row) {
      this.$confirm("确定要取消吗！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.cancelBook(row.id, row.orderId);
      });
    },
    cancelBook(id, orderId) {
      cancelBook(id)
        .then((response) => {
          this.$message.success("取消成功");
          this.orderBookDetail(orderId);
        })
        .catch((response) => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg,
          });
        });
    },

    handleReassign(row) {
      this.reassignDialogVisible = true;
      this.timeList = this.getTimeList(row.serviceDuration);
      this.getServantList(row.id);
      this.reassignForm = {
        id: row.id,
        bookDate: "",
        bookTime: "",
        servantId: "",
        orderId: row.orderId,
      };
    },
    getServantList(id) {
      getAssignmentPerson(id).then((res) => {
        this.servantList = res.data.data;
      });
    },
    confirmReassign() {
      this.$refs["reassignForm"].validate((valid) => {
        if (valid) {
          let params = {
            id: this.reassignForm.id,
            bookDate: this.reassignForm.bookDate,
            bookStartTime: this.reassignForm.bookTime.split("-")[0],
            bookEndTime: this.reassignForm.bookTime.split("-")[1],
            servantId: this.reassignForm.servantId,
          };
          orderBookReassign(params)
            .then((response) => {
              this.$message.success("改派成功");
              console.log(response);
              this.reassignDialogVisible = false;
              this.orderBookDetail(this.reassignForm.orderId);
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg,
              });
            });
        }
      });
    },

    confirmShip() {
      this.$refs["shipForm"].validate((valid) => {
        if (valid) {
          shipOrder(this.shipForm)
            .then((response) => {
              this.shipDialogVisible = false;
              this.$notify.success({
                title: "成功",
                message: "确认发货成功",
              });
              this.getList();
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg,
              });
            });
        }
      });
    },
    handleDeleteConfirm(row) {
      this.$confirm("订单删除后无法恢复，确定继续删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.handleDelete(row);
      });
    },
    handleDelete(row) {
      deleteOrder({ orderId: row.id })
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: "订单删除成功",
          });
          this.getList();
        })
        .catch((response) => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg,
          });
        });
    },
    handleRefund(row) {
      this.refundForm.orderId = row.id;
      if (row.refundAmount) {
        this.refundForm.refundMoney = (
          row.actualPrice - row.refundAmount
        ).toFixed(2);
        this.refundAmount = row.refundAmount;
      } else {
        this.refundForm.refundMoney = row.actualPrice;
      }

      this.actualPrice = row.actualPrice;

      this.refundDialogVisible = true;
      this.$nextTick(() => {
        this.$refs["refundForm"].clearValidate();
      });
    },
    confirmRefund() {
      this.$refs["refundForm"].validate((valid) => {
        if (valid) {
          let balance = (this.actualPrice - this.refundAmount).toFixed(2);
          console.log(balance);
          if (Number(this.refundForm.refundMoney) == 0) {
            this.$message.warning("申请退款金额不能为零!");
          } else if (Number(this.refundForm.refundMoney) > balance) {
            this.$message.warning("申请退款金额不能大于未退款金额!");
          } else {
            refundOrder(this.refundForm)
              .then((response) => {
                this.refundDialogVisible = false;
                this.$notify.success({
                  title: "成功",
                  message: "确认退款成功",
                });
                this.getList();
              })
              .catch((response) => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.errmsg,
                });
              });
          }
        }
      });
    },
    handleImport() {
      this.importLoading = true;
      this.importForm.file = undefined;
    },
    beforeUpload(file) {
      // this.files = file;
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!extension && !extension2) {
        this.$message.warning("上传模板只能是 xls、xlsx格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.warning("上传模板大小不能超过 5MB!");
        return;
      }
      this.importForm.filename = file.name;
      this.importForm.file = file;
      return false; // 返回false不会自动上传
    },
    confirmImport() {
      // 确定上传
      console.info(this.importForm);
      var formData = new FormData();
      formData.append("file", this.importForm.file);
      formData.append("channelId", this.importForm.channelId);

      var config = {
        headers: { "Content-Type": "multipart/form-data" },
      };

      importOrder(formData, config).then((res) => {});
    },
    printOrder() {
      if (this.$print != undefined) {
        this.$print(this.$refs.print);
        this.orderDialogVisible = false;
      }
    },

    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "客户手机",
          "订单编号",
          "下单时间",
          "收货人联系方式",
          "上门地址",
          "城市",
          "上级合伙人",
          "订单状态",
          "支付金额",
          "支付时间",
        ];
        const filterVal = [
          "customer.tel",
          "orderSn",
          "createTime",
          "mobile",
          "address",
          "city",
          "rCustomer.customerName",
          "orderStatus",
          "actualPrice",
          "payTime",
        ];
        var lists = [];
        if (this.list && this.list.length > 0) {
          for (let i = 0; i < this.list.length; i++) {
            var order = this.list[i];
            order.city = this.cityFilter(order.address);
            order.orderStatus = statusMap[order.orderStatus];
            lists.push(order);
          }
          console.info(lists);
        }
        excel.export_json_to_excel2(tHeader, lists, filterVal, "订单");
        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: 20px;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  white-space: pre-wrap;
  /* 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>
