<template>
  <div>
    <div style="width: 100%">
      <el-row style="width: 100%;margin-top: 10px;">
        <el-col :span="6" style="width: 443px;">
          <periodDatePickerActive
            :start="parmValue.start_day"
            :end="parmValue.end_day"
            picker-type="month"
            :width="'205px'"
            :size="searchSize"
            @timeReturned="time"
          />
        </el-col>

        <el-col :span="4" style="width: 350px">
          <search-supplier
            :size="'mini'"
            :value="parmValue.supplierNo"
            :disabled="false"
            :placeholder="'供应商名称'"
            :names="parmValue.supplierName"
            :is-detail="true"
            :no-disabled="true"
            @searchChange="supplierChange"
          />
        </el-col>

        <el-col :span="4" style="width: 66px; float: right">
          <el-button
            type="primary"
            style="margin-left: 30px"
            :size="searchSize"
            class="fr"
            @click="download"
          >导出</el-button>
        </el-col>
        <el-col :span="3" style="width: 66px; float: right">
          <el-button
            :size="searchSize"
            type="primary"
            style="float: right; margin-left: 5px"
            @click="searchList"
          >刷新</el-button>
        </el-col>
        <el-col :span="4" style="width: 66px; float: right">
          <el-button type="warning" class="fr" :size="searchSize" @click="restSearch">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table v-loading="loading" size="mini" :data="tableData" border style="margin-top:10px">
      <el-table-column prop="supplier_name" label="供应商名称" width="180px" show-overflow-tooltip />
      <el-table-column prop="is_supplier" label="是否开通供应商端" width="120px" />
      <el-table-column prop="person" label="供应商负责人" width="95px" />
      <el-table-column prop="total_fee" label="采购订单总金额" width="110px" />
      <el-table-column prop="total_cgd" label="采购订单总量" width="95px" />

      <el-table-column label="待与供应商确认" align="center">
        <el-table-column label="采购订单总金额" prop="dtotal_fee" min-width="105px" />
        <el-table-column label="采购单数量" prop="dtotal_cgd" min-width="85px" />
      </el-table-column>

      <el-table-column label="待入库" align="center">
        <el-table-column label="采购订单总金额" prop="wtotal_fee" min-width="105px" />
        <el-table-column label="采购单数量" prop="wtotal_cgd" min-width="85px" />
      </el-table-column>

      <el-table-column label="按商品类型统计订单数量" align="center">
        <el-table-column label="备库商品" prop="tag_1" min-width="85px" />
        <el-table-column label="非库存商品" prop="tag_2" min-width="105px" />
        <el-table-column label="采返商品" prop="tag_zx" min-width="85px" />
      </el-table-column>

      <el-table-column label="平台类型" align="center">
        <el-table-column label="ToC平台" prop="tag_c" />
        <el-table-column label="ToB平台" prop="tag_b" />
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import urlConfig from "@/apis/url-config";
import asyncRequest from "@/apis/service/reportQuery/newReport";
import periodDatePickerActive from "../period-date-picker/main.vue";
import { mapGetters } from "vuex";
import { xs_order_type_options } from "@/assets/js/statusList";
import * as dayjs from "dayjs";

export default {
  name: "PurchaseOrder",
  components: {
    periodDatePickerActive
  },
  mixins: [mixinPage, resToken],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"])
  },
  data() {
    return {
      // 选中数组
      changeList: [],
      // 全局url
      fileUrl: urlConfig.baseURL,
      // loading
      loading: false,
      // 请求参数集合
      parmValue: {
        supplierNo: [],
        supplier_name: "",
        start_day: dayjs(this.getStartDate()).format("YYYY-MM-DD"), // 起始时间
        end_day: dayjs(new Date()).format("YYYY-MM-DD") // 结束时间
      },
      // 表格 - 数据集合
      tableData: [],
      xs_order_type_options,
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"]
      }
    };
  },
  mounted() {
    this.parmValue.start_day = dayjs()
      .subtract(0, "day")
      .format("YYYY-MM-DD");
    this.parmValue.end_day = dayjs()
      .subtract(-1, "day")
      .format("YYYY-MM-DD");
    this.searchList();
  },

  methods: {
    async supplierChange(e) {
      const { code, label } = e;
      this.parmValue.supplierNo = code ? [code] : [];
      this.searchList();
    },
    // 初始化http请求
    async searchList() {
      if (!this.parmValue.start_day || !this.parmValue.end_day) {
        this.$message.warning("请选择时间区间");
        this.tableData = [];
        return;
      }
      if (!this.diffDays(31)) {
        this.$message.warning("时间区间不能超过31天");
        return;
      }

      this.loading = true;
      const { code, data, message } = await asyncRequest.pom({
        ...this.parmValue,
        supplierNo: Array.isArray(this.parmValue.supplierNo)
          ? this.parmValue.supplierNo[0]
          : this.parmValue.supplierNo
      });
      if (code === 0) {
        // const { list, count } = data;
        this.tableData = data;
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
      }
      this.loading = false;
    },
    getStartDate() {
      const myDate = new Date();
      myDate.setDate(myDate.getDate() - 29);
      return myDate;
    },
    diffDays(days) {
      const step = 24 * 3600 * 1000;
      const sDay = new Date(this.parmValue.start_day).valueOf();
      const eDay = new Date(this.parmValue.end_day).valueOf();
      let isok = true;

      if (eDay - sDay > step * days) {
        isok = false;
      }

      return isok;
    },

    // 重置
    restSearch() {
      this.parmValue = {
        supplier_name: "",
        supplierNo: [],
        start_day: dayjs()
          .subtract(0, "day")
          .format("YYYY-MM-DD"),
        end_day: dayjs()
          .subtract(-1, "day")
          .format("YYYY-MM-DD"),
        page: 1, // 页码
        size: 15 // 每页显示条数
      };

      this.searchList();
    },
    // 选中触发函数
    selection_change(e) {
      const { list } = e;
      // 选中的数组集合
      this.changeList = list.length > 0 ? JSON.parse(JSON.stringify(list)) : [];
    },
    // 时间函数
    async time(e) {
      this.parmValue.start_day = e.startTime || "";
      this.parmValue.end_day = e.endTime || "";
      if (
        (this.parmValue.start_day !== "" && this.parmValue.end_day === "") ||
        (this.parmValue.start_day === "" && this.parmValue.end_day !== "")
      ) {
        this.$message.warning("时间区间不完整！");
        return;
      }

      if (!this.diffDays(31)) {
        this.$message.warning("时间区间不能超过31天");
        return;
      }

      await this.searchList();
    },
    // getTimeParam() {
    //   const { start_day: start, end_day: end } = this.parmValue;

    //   if (!start || !end) {
    //     return {
    //       start_day: "",
    //       end_day: ""
    //     };
    //   }

    //   const start_date_chunks = start.split("-");
    //   const end_date_chunks = end.split("-");

    //   start_date_chunks[2] = "01";

    //   const [year, month] = end_date_chunks;
    //   const end_last_day = new Date(year, month, 0).getDate();
    //   end_date_chunks[2] = end_last_day;

    //   return {
    //     start_day: start_date_chunks.join("-"),
    //     end_day: end_date_chunks.join("-")
    //   };
    // },
    // 导出文件
    async download() {
      if (
        (this.parmValue.start_day !== "" && this.parmValue.end_day === "") ||
        (this.parmValue.start_day === "" && this.parmValue.end_day !== "")
      ) {
        this.$message.warning("时间区间不完整！");
        return;
      }

      if (!this.diffDays(31)) {
        this.$message.warning("时间区间不能超过31天");
        return;
      }

      const model = JSON.parse(JSON.stringify(this.parmValue));

      if (!this.loading) {
        this.loading = true;
        const httpType = `aplication/zip`;
        axios({
          method: "post",
          url: this.fileUrl + "admin/pome",
          responseType: "blob",
          data: {
            ...this.parmValue,
            supplierNo: Array.isArray(this.parmValue.supplierNo)
              ? this.parmValue.supplierNo[0]
              : this.parmValue.supplierNo
          },
          headers: {
            Accept: httpType
          }
        })
          .then(res => {
            if (res && res.status == 200 && res.data) {
              const url = window.URL.createObjectURL(
                new Blob([res.data], {
                  type: httpType
                })
              );
              const link = document.createElement("a");
              link.style.display = "none";
              link.href = url;
              const excelName = "本月供应商采购订单情况.zip";
              link.setAttribute("download", excelName);
              document.body.appendChild(link);
              link.click();
              link.remove();
              window.URL.revokeObjectURL(url); // 释放掉blob对象
              this.$message.success(`导出成功！`);
              setTimeout(() => {
                this.loading = false;
              }, 500);
            } else {
              this.$message.error(res.data.message);
              setTimeout(() => {
                this.loading = false;
              }, 500);
            }
          })
          .catch(error => {
            console.log(error);
            this.loading = false;
          });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.purchaseOrder {
  // text-align: right;
}
</style>
