<template>
  <div class="app-main-height">
    <div v-show="isShow">
      <el-row>
        <el-col :span="24">
          <div class="left-panel">
            <el-form
              :inline="true"
              :model="formInline"
              class="demo-form-inline"
            >
              <el-form-item label="" class="number">
                <span>订单列表总数：{{ count }}个</span>
              </el-form-item>
              <el-form-item label="">
                <el-select
                  v-model="formInline.orderState"
                  placeholder="请选择订单状态"
                  size="small"
                  @change="orderStateChange"
                >
                  <el-option label="全部" value="-2" />
                  <el-option label="待退款" value="1" />
                  <el-option label="待付款" value="0" />
                  <el-option label="待发货" value="2" />
                  <el-option label="已发货" value="3" />
                  <el-option label="退款中" value="4" />
                  <el-option label="已退款" value="5" />
                  <el-option label="已取消" value="6" />
                  <el-option label="已完成" value="7" />
                </el-select>
              </el-form-item>
              <el-form-item label="">
                <el-date-picker
                  v-model="formInline.startTime"
                  type="daterange"
                  start-placeholder="开始日期"
                  range-separator="至"
                  end-placeholder="结束日期"
                  size="small"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                />
              </el-form-item>
              <el-form-item label="">
                <el-input
                  v-model.trim="formInline.findText"
                  placeholder="订单编号/收货人/手机号/商品名称"
                  size="small"
                  :clearable="false"
                />
              </el-form-item>

              <el-form-item>
                <el-button-group>
                  <el-button
                    icon="el-icon-search"
                    type="primary"
                    size="small"
                    @click="handSearch"
                  >
                    搜索
                  </el-button>
                </el-button-group>
              </el-form-item>
              <el-form-item>
                <el-button-group>
                  <el-button type="primary" size="small" @click="handleEmpty">
                    清空
                  </el-button>
                </el-button-group>
              </el-form-item>
              <el-form-item>
                <el-button-group>
                  <el-button type="primary" size="small" @click="gotoError">
                    物流错误信息
                  </el-button>
                </el-button-group>
              </el-form-item>
              <el-form-item>
                <el-button-group>
                  <el-button
                    :loading="downloadLoading"
                    icon="el-icon-download"
                    type="primary"
                    size="small"
                    @click="handleDownload"
                  >
                    导出
                  </el-button>
                </el-button-group>
              </el-form-item>
              <el-form-item>
                <el-button-group>
                  <el-upload
                    class="upload-demo"
                    action="#"
                    :before-upload="beforeUpload"
                    id="items"
                  >
                    <el-button
                      icon="el-icon-upload2"
                      size="small"
                      type="primary"
                    >
                      导入
                    </el-button>
                  </el-upload>
                </el-button-group>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
      <el-table
        v-loading="listLoading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <template slot="empty">
          <p>{{ dataText }}</p>
        </template>
        <el-table-column
          prop="orderNum"
          label="订单编号"
          fixed
          show-overflow-tooltip
          width="180"
        />
        <el-table-column
          show-overflow-tooltip
          prop="goodsName"
          label="商品名称/套餐名称"
          width="350"
        >
          <template slot-scope="scope">
            {{ scope.row.goodsName }}/{{ scope.row.comboName }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="consignee"
          label="收货人/手机号"
          width="180"
        >
          <template slot-scope="scope">
            {{ scope.row.consignee }}/{{ scope.row.phone }}
          </template>
        </el-table-column>
        <el-table-column
          prop="payAmount"
          label="实付金额 (元)"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          prop="providerName"
          label="供应商名称"
          show-overflow-tooltip
          width="280"
        />
        <el-table-column
          prop="orderState"
          label="订单状态"
          show-overflow-tooltip
          width="120"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.orderState | statusFilter">
              {{ scope.row.orderState | toState(scope.row.orderState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="订单生成时间"
          show-overflow-tooltip
          width="180"
        />
        <el-table-column label="操作" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="text" @click="handleEdit(row)">查看详情</el-button>
            <el-button
              v-if="row.orderState == 1"
              type="text"
              @click="handleRefund(row, 'aprefund')"
              >操作退款</el-button
            >
            <el-button
              v-if="row.orderState == 2"
              type="text"
              @click="handleRefund(row, 'refund')"
              >商家退款</el-button
            >
            <el-button
              v-if="row.orderState == 2"
              type="text"
              @click="handleRefund(row, 'fill')"
              >填写物流信息</el-button
            >
            <el-button
              v-if="row.orderState == 2"
              type="text"
              @click="handleRefund(row, 'adresse')"
            >
              修改收货地址</el-button
            >
            <el-button
              v-if="row.orderState == 3"
              type="text"
              @click="handleRefund(row, 'modify')"
              >修改物流信息</el-button
            >
            <el-button
              v-if="row.orderState == 3"
              type="text"
              @click="gotoLogistics(row)"
              >查看物流信息</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="queryForm.pageNo"
        :page-size="queryForm.pageSize"
        :layout="layout"
        :total="count"
        @current-change="handleCurrentChange"
      />
    </div>
    <Refund ref="refund" @getList="getList()" />
    <el-dialog
      title="导入完成"
      width="500px"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <div>{{ uploadInfo.msg }}</div>
      <el-button
        v-if="uploadInfo.failNum <= 0"
        @click="dialogFormVisible = false"
        style="margin-left:40%；margin-top:50px;"
        type="primary"
        round
        >确认</el-button
      >
      <el-button
        v-if="uploadInfo.failNum > 0"
        style="margin-left: 35%; margin-top: 50px"
        type="primary"
        @click="dwonError"
        round
        >下载失败记录</el-button
      >
    </el-dialog>
  </div>
</template>
<script>
import Edit from "./components/details";
import Refund from "./components/refund";
import { mapGetters } from "vuex";
import { json2excel } from "@/utils/setMethods.js";
import { excelUpload } from "@/utils/request.js";
import { fs } from "@/utils/request.js";
import { HTTP_URL } from "@/api/api-type.js";
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: "danger",
        1: "primary",
        2: "primary",
        3: "primary",
        4: "danger",
        5: "info",
        6: "info",
        7: "success",
      };
      return statusMap[status];
    },
  },
  components: { Edit, Refund },
  data() {
    return {
      params: {},
      frame: {},
      dialogFormVisible: false,
      count: 0, // 商品总计
      listLoading: false,
      downloadLoading: false,
      isShow: true,
      dataText: "暂无数据",
      layout: "total, prev, pager, next, jumper",
      total: 100,
      queryForm: {
        pageNo: 1,
        pageSize: 10,
      },
      formInline: {
        orderState: "",
        findText: "",
        startTime: [],
      },
      tableData: [],
      updataUrl: "",
      xlsxFile: "",
      limit: 1, // 上传excell时，同时允许上传的最大数
      fileList: [], // excel文件列表
      merchantsId: "", //商户ID
      uploadInfo: {}, //导入完成的回调信息
    };
  },
  computed: {
    ...mapGetters({
      // merchantsId: "merchantsId",
    }),
  },
  created() {
    this.merchantsId = sessionStorage.getItem("merchantsId");
    let params = localStorage.getItem("params")
      ? JSON.parse(localStorage.getItem("params"))
      : "";
    if (params) {
      this.formInline.orderState = params.data.orderState;
      this.formInline.findText = params.data.findText;
      let startTime = params.data.startTime ? params.data.startTime : "",
        endTime = params.data.endTime ? params.data.endTime : "";
      this.formInline.startTime.push(startTime);
      this.formInline.startTime.push(endTime);
      this.queryForm.pageNo = params.data.pageNum;
    }
    // console.log("this.formInline", this.formInline);
    this.$nextTick(() => {
      this.getList(); // 获取数据
    });
  },

  methods: {
    // 下载导入失败记录
    dwonError() {
      let that = this;
      const params = {
        type: "exportErrorData",
        data: {
          id: this.uploadInfo.id,
          merchantId: sessionStorage.getItem("merchantsId"),
        },
      };
      this.$http.post(this.$api.exportErrorData, params).then((res) => {
        this.downloadLoading = false;
        var downloadFileUrl = res.excelUrl;
        var elemIF = document.createElement("iframe");
        elemIF.src = downloadFileUrl;
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
        elemIF.click();
        setTimeout(() => {
          document.body.removeChild(elemIF);
          that.dialogFormVisible = false;
        }, 1000);
      });
    },
    // 导入完成
    open(event) {
      this.$alert(`${event.msg}`, {
        dangerouslyUseHTMLString: true,
      });
    },
    //导入
    beforeUpload(e) {
      const fd = new FormData();
      fd.append("avatar_file", e);
      fd.append("merchantsId", this.merchantsId);
      this.$http.post(this.$api.importOrderExcel, fd).then((res) => {
        this.uploadInfo = res;
        this.dialogFormVisible = true;
      });
    },

    gotoError() {
      this.$router.push({
        name: "errorList",
      });
    },
    // 跳转查看物流页面
    gotoLogistics(event) {
      this.$router.push({
        name: "logistics",
        query: {
          orderID: event.orderID,
        },
      });
    },
    //获取订单列表
    getList() {
      this.listLoading = true;
      let params = {
        type: "getOrders",
        data: {
          orderState: this.formInline.orderState,
          startTime: this.formInline.startTime
            ? this.formInline.startTime[0]
            : "",
          endTime: this.formInline.startTime
            ? this.formInline.startTime[1]
            : "",
          findText: this.formInline.findText,
          merchantsId: this.merchantsId,
          pageNum: this.queryForm.pageNo,
        },
      };

      // let params=localStorage.getItem("params")?JSON.parse(localStorage.getItem("params")):p
      this.params = params;
      this.$http.post(this.$api.getOrders, params).then(
        (res) => {
          setInterval(() => {
            this.listLoading = false;
          }, 1000);

          if (res) {
            this.count = res.count;
            this.tableData = res.orderList;
          } else {
            this.count = "";
            this.tableData = [];
          }
        },
        (error) => {
          // console.log(error);
          this.listLoading = false;
          this.dataText = "网络异常！";
          this.tableData = [];
        }
      );
    },

    // 查看详情
    handleEdit(row, md) {
      localStorage.setItem("params", JSON.stringify(this.params));
      this.$router.push({
        name: "details",
        query: {
          orderID: row.orderID,
        },
      });
    },
    // 切换页码
    handleCurrentChange(e) {
      this.queryForm.pageNo = e;
      this.getList();
    },
    // 搜索
    handSearch() {
      this.queryForm.pageNo = 1;
      this.getList();
    },
    // 清空
    handleEmpty() {
      const formInline = this.formInline;
      for (const key in formInline) {
        formInline[key] = "";
      }
      this.formInline = formInline;
      sessionStorage.removeItem("orderCode");
      localStorage.removeItem("params");
      this.getList();
    },
    // 商家退款
    handleRefund(row, md) {
      // console.log("收货地址", row);
      if (row.orderID) {
        this.$refs["refund"].showEdit(row, md);
      } else {
        this.$refs["refund"].showEdit(md);
      }
    },
    // 下拉状态变化
    orderStateChange(e) {
      // console.log(e);
      console.log(this.formInline.orderState);
    },
    //导出
    handleDownload() {
      // console.log("状态", this.formInline.orderState);
      this.getList();
      this.downloadLoading = true;
      if (!this.formInline.orderState) {
        this.downloadLoading = false;
        this.$baseMessage("请选择订单状态", "error");
        return false;
      }
      if (!this.formInline.startTime[0]) {
        this.downloadLoading = false;
        this.$baseMessage("请选择时间", "error");
        return false;
      }

      const params = {
        type: "exportOrdersExcel",
        data: {
          orderState: this.formInline.orderState,
          startTime: this.formInline.startTime[0]
            ? this.formInline.startTime[0]
            : "",
          endTime: this.formInline.startTime[1]
            ? this.formInline.startTime[1]
            : "",
          findText: this.formInline.findText,
          merchantsId: this.merchantsId,
        },
      };
      this.$http.post(this.$api.exportOrdersExcel, params).then((res) => {
        this.downloadLoading = false;
        var downloadFileUrl = res.excelUrl;
        var elemIF = document.createElement("iframe");
        elemIF.src = downloadFileUrl;
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
        elemIF.click();
        setTimeout(() => {
          document.body.removeChild(elemIF);
        }, 1000);
      });
    },
  },
  destroyed() {
    sessionStorage.removeItem("orderCode");
  },
};
</script>
<style lang="scss" scoped>
.el-button {
  margin: 0;
  margin-right: 10px;
}
</style>

