<template>
  <div class="MachineSchedulingTable">
    <!--    搜索框-->

    <div class="search">
      <div class="datepickBox" style="">
        <el-date-picker
          v-model="queryCriteria.business_date_start"
          type="date"
          placeholder="选择开始日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </div>
      <div class="datepickBox" style="">
        <el-date-picker
          v-model="queryCriteria.business_date_end"
          type="date"
          placeholder="选择结束时间"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </div>
      <div class="radio">
        <el-select v-model="queryCriteria.new_state" placeholder="请选择">
          <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="chunk">
        <el-input v-model="queryCriteria.spec_no" placeholder="商家编码"></el-input>
      </div>
      <div class="chunk">
        <el-input v-model="queryCriteria.warehouse_no" placeholder="仓库编码"></el-input>
      </div>
      <div class="chunk">
        <el-input v-model="queryCriteria.warehouse_name" placeholder="仓库名称"></el-input>
      </div>
      <div class="chunk">
        <el-input v-model="queryCriteria.new_system_number" placeholder="U8C单号"></el-input>
      </div>
      <div class="chunk">
        <el-input v-model="queryCriteria.shop_name" placeholder="店铺名称"></el-input>
      </div>
      <div class="chunk">
        <el-input v-model="queryCriteria.shop_no" placeholder="店铺编码"></el-input>
      </div>
      <div class="chunk">
        <el-input v-model="queryCriteria.order_no" placeholder="旺店通出库单编码"></el-input>
      </div>
      <el-button
        type="primary"
        @click="query"
        :loading="loading"
        size="small"
        style="width: 5%; margin: 10px 20px"
      >查询
      </el-button>
      <el-button
        type="primary"
        @click="downLoad"
        :loading="loading"
        size="small"
        style="width: 5%; margin: 10px 20px"
      >excel导出
      </el-button>
      <el-button
        type="warning"
        @click="reset"
        :loading="loading"
        size="small"
        style="width: 5%; margin: 10px 20px"
      >重置
      </el-button>
    </div>
    <!--    主体内容-->
    <div class="main">
      <baseNewTable
        :tableData="mainTableData"
        :tableColumn="mainTableColumn"
        :tableLoading="tableLoading"
        :tableDataMergeList="tableDataMergeList"
        :pageModel="pageModel"
        @pageSizeChange="(val) => pageSizeChange(val, pageModel)"
        @pageChange="(val) => pageChange(val, pageModel)"
        exportEventName="Toc正向流程表"
      >
      </baseNewTable>
    </div>
  </div>
</template>

<script>
import baseNewTable from "./baseNewTable2/index.vue";
import {authApi, downFilesBasedFileNameFileTypeAPI} from "@/api/apis/auth";
import {
  basePrintJS,
} from "@/utils/util.js";

export default {
  name: "MachineSchedulingTable",
  data() {
    return {
      stateOptions: [
        {label: "全部", value: ""},
        {label: "成功", value: "Y"},
        {label: "失败", value: "N"},
      ],
      //搜索框内容
      queryCriteria: {
        "reportDate": "",
        "business_date_start": "",
        "business_date_end": "",
        "new_state": "",
        "spec_no": "",
        "warehouse_no": "",
        "warehouse_name": "",
        "new_system_number": "",
        "shop_name": "",
        "shop_no": "",
        "order_no": ""
      },
      pageModel: {
        "pageSize": 100,
        "pageNum": 1,
        pageTotal: 0,
      },

      //搜索按钮loading
      loading: false,
      //表单loading
      tableLoading: false,
      workshop: [],
      //客户下拉
      queryCriteriaOption: [],
      //色号下拉
      colorNumOption: [],
      //批号下拉
      contractCodeOption: [],
      //机台下拉
      workBenchIDOption: [],
      //生产名称下拉
      cInvNameOption: [],
      // 产品类型下拉
      cInvCNameOption: [],
      //生产班组
      stateNameOption: [
        {
          label: "甲",
          value: "甲",
        },
        {
          label: "乙",
          value: "乙",
        },
        {
          label: "丙",
          value: "丙",
        },
      ],
      // 右侧按钮
      fixedButtonList: [
        {
          icon: "el-icon-printer",
          title: "打印",
        },
        {
          icon: "el-icon-folder",
          title: "导出",
        },
      ],
      //正常表单
      mainTableData: [],
      //缺少字段产品大类、本次生产重量
      mainTableColumn: [
        {
          label: "是否成功",
          prop: "new_state",
          tooltip: true,
          width: 150,
        },
        {
          label: "成功/失败原因",
          prop: "new_transmit_info",
          tooltip: true,
          width: 150,
        },
        {
          label: "U8C销售单号",
          prop: "new_system_number",
          tooltip: true,
          width: 150,
        },
        {
          label: "U8C销售主键",
          prop: "new_system_primary",
          tooltip: true,
          width: 150,
        },
        {
          label: "旺店通品牌名称",
          prop: "brand_name",
          tooltip: true,
          width: 150,
        },
        {
          label: "旺店通品牌编码",
          prop: "barcode",
          tooltip: true,
          width: 150,
        },
        {
          label: "商家编码sku",
          prop: "spec_no",
          tooltip: true,
          width: 150,
        },
        {
          label: "旺店通货品数量",
          prop: "goods_count",
          tooltip: true,
          width: 150,
        },
        {
          label: "出库明细主键",
          prop: "rec_id",
          tooltip: true,
          width: 150,
        },
        {
          label: "总货款",
          prop: "share_amount",
          tooltip: true,
          width: 150,
        },
        {
          label: "仓库编码",
          prop: "warehouse_no",
          tooltip: true,
          width: 150,
        },
        {
          label: "仓库名称",
          prop: "warehouse_name",
          tooltip: true,
          width: 150,
        },
        {
          label: "出库单编码",
          prop: "order_no",
          tooltip: true,
          width: 150,
        },
        {
          label: "旺店通店铺名称",
          prop: "shop_name",
          tooltip: true,
          width: 150,
        },
        {
          label: "旺店通店铺编码",
          prop: "shop_no",
          tooltip: true,
          width: 150,
        },
        {
          label: "发货日期(业务日期)",
          prop: "consign_time",
          tooltip: true,
          width: 200,
        },
      ],
      //正常合并
      tableDataMergeList: [],
    };
  },
  methods: {
    async downLoad() {
      if (this.queryCriteria.business_date_start && this.queryCriteria.business_date_end) {
        let startDate = new Date(this.queryCriteria.business_date_start);
        let endDate = new Date(this.queryCriteria.business_date_end);
        let differenceInMillis = endDate - startDate;
        let differenceInDays = differenceInMillis / (1000 * 60 * 60 * 24);
        // 判断差值是否在15天以内
        if (!isNaN(differenceInDays) && differenceInDays < 31) {
        } else {
          this.$vmNews("开始时间和结束时间范围请选择在30天内");
          return
        }
      } else {
        this.$vmNews("请选择开始时间和结束时间");
        return
      }
      let params = {
        ...this.queryCriteria,
        ...this.pageModel,
        pageSize: 9999,
        pageNum: 1
      };
      this.openLoading('detail')
      const res = await authApi("busidataTocsalesServiceImpl", "busidataTocsalesServiceImpl", "queryToCSalesReportExcel", "", params);

      if (res.status == 200) {
        const response = await downFilesBasedFileNameFileTypeAPI(res.attribute)
        // console.log(res)
        const url = window.URL.createObjectURL(new Blob([response]), {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'toc正向流程报表.xlsx'); // 设置下载的文件名
        document.body.appendChild(link);
        link.click();
      }
      return

    },
    reset() {
      this.pageModel.pageNum = 1;
      this.queryCriteria = {
        "reportDate": "",
        "business_date_start": "",
        "business_date_end": "",
        "new_state": "",
        "spec_no": "",
        "warehouse_no": "",
        "warehouse_name": "",
        "new_system_number": "",
        "shop_name": "",
        "shop_no": "",
        "order_no": ""
      };
    },
    //limit改变
    pageSizeChange(val, obj) {
      obj.pageSize = val;
      this.init();
    },
    //页码变更
    pageChange(val, obj) {
      obj.page = val;
      this.init();
    },
    //搜索联想
    async remoteMethod(val, row, options) {
      //   客户
      if (row == "cusCode") {
        const res = await GetCustomerListAPI(val);
        this[options] = [];
        if (res.code == 1) {
          res.data[1].forEach((item) => {
            this[options].push({label: item.cCusName, value: item.cCusCode});
          });
        }
      } else if (row === "workBenchID") {
        //这个不需要动态搜索
        if (this[options].length) return;
        const res = await WorkbenchGetBillListAPI({
          page: 1,
          limit: 999,
          Sequence: "",
          SequenceName: "",
          CodeOrName: "",
          areaID: "",
          workShopID: "",
        });
        this[options] = [];
        if (res.code == 1) {
          res.data[1].forEach((item) => {
            this[options].push({
              label: item.workName,
              value: item.workID,
            });
          });
        }
      } else if (row === "cInvCode") {
        const res = await U8BaseGetInvenListAPI({
          page: 1,
          limit: 200,
          codeOrName: val,
        });
        this[options] = [];
        if (res.code == 1) {
          res.data[1].forEach((item) => {
            this[options].push({label: item.cInvName, value: item.cInvCode});
          });
        }
      } else if (row === "cInvCCode") {
        const res = await U8BaseGetInvClassListAPI({
          page: 1,
          limit: 200,
          codeOrName: val,
        });
        this[options] = [];
        if (res.code == 1) {
          res.data[1].forEach((item) => {
            this[options].push({
              label: item.cInvCName,
              value: item.cInvCCode,
            });
          });
        }
      }
    },
    // 点击查询
    query() {
      this.pageModel.pageNum = 1;
      if (this.queryCriteria.business_date_start && this.queryCriteria.business_date_end) {
        let startDate = new Date(this.queryCriteria.business_date_start);
        let endDate = new Date(this.queryCriteria.business_date_end);
        let differenceInMillis = endDate - startDate;
        let differenceInDays = differenceInMillis / (1000 * 60 * 60 * 24);
        // 判断差值是否在15天以内
        if (!isNaN(differenceInDays) && differenceInDays < 11) {
        } else {
          this.$vmNews("开始时间和结束时间范围请选择在10天内");
          return
        }
      } else {
        this.$vmNews("请选择开始时间和结束时间");
        return
      }
      this.init();
    },
    /*
     * 导出、打印功能
     * item:当前按钮信息
     * boxId:打印表单id(仅导出）
     * name:导出后文件名（仅导出）
     * tableData:传打印表格当前tableData（仅打印）
     * tableColumn:传打印表格当前tableColumn（仅打印）
     * */
    fixedClick(item, boxId, name, tableData, tableColumn) {
      if (item.title == "导出") {
        this.exportEvent(name, boxId);
      } else if (item.title == "打印") {
        this.duplicate(tableData, tableColumn);
      }
    },
    //导出功能
    exportEvent(excelName, boxId) {
      console.log(document.querySelector(boxId), "123", boxId);
      let gatherData = {
        raw: true,
      };
      let grid = XLSX.utils.table_to_book(
        document.querySelector(boxId),
        gatherData
      );
      let workbook = XLSX.write(grid, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([workbook], {
            type: "application/octet-stream",
          }),
          excelName + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, workbook);
      }
      return workbook;
    },
    //打印
    duplicate(tableData, tableColumn) {
      basePrintJS(tableData, tableColumn);
    },
    //初始化表单
    async init() {
      this.tableLoading = true;
      let params = {
        ...this.queryCriteria,
        ...this.pageModel,
      };
      //初始化表单
      const res = await authApi("busidataTocsalesServiceImpl", "busidataTocsalesServiceImpl", "queryToCSalesReport", "", params);
      console.log(res, '初始化res')
      this.pageModel.pageTotal = res.attribute.total;
      this.mainTableData = this.dataDispose(
        res.attribute.list,
        this.tableDataMergeList
      );
      this.tableLoading = false;
    },
    //data处理
    dataDispose(data, arr) {
      if (!arr.length) return data;
      //分类存放分组
      let tempObj = {};
      //结果
      let result = [];
      //将层级转变为 [[1],[1,2],[1,2,3]]
      const transformedArray = arr.reduce((acc, currentValue) => {
        acc.push([...(acc.length ? acc[acc.length - 1] : []), currentValue]);
        return acc;
      }, []);
      //开始对表单进行排序
      //排序后的arr
      let newArr = [];
      let sortObj = {};
      data.forEach((item) => {
        let keyValue = "";
        arr.forEach((key2, index) => {
          keyValue += item[key2];
        });
        if (!sortObj[keyValue]) {
          sortObj[keyValue] = data.filter((item01) => {
            return arr.every((prop) => item01[prop] === item[prop]);
          });
        }
      });
      Object.keys(sortObj)
        .sort()
        .forEach((key) => {
          newArr = [...newArr, ...sortObj[key]];
        });
      // 开始循环
      newArr.forEach((item) => {
        transformedArray.forEach((key) => {
          //keyValue:当前key下的value加一起，用于tempObj的key
          let keyValue = "";
          key.forEach((keyItem, index) => {
            keyValue += item[keyItem];
            if (index < key.length - 1) {
              keyValue += "|";
            }
          });
          if (!tempObj[keyValue]) {
            //拿到所有当前key下相同数据
            tempObj[keyValue] = newArr.filter((item01) => {
              return key.every((prop) => item01[prop] === item[prop]);
            });
            // 计算总数
            tempObj[keyValue][0][`${key[key.length - 1]}Length`] =
              tempObj[keyValue].length;

            if (key.length === 1) {
              result = [...tempObj[keyValue], ...result];
            }
          }
        });
      });
      return result;
    },
  },
  mounted() {
    // this.init();
  },
  components: {
    baseNewTable,
  },
};
</script>

<style scoped lang="scss">
.MachineSchedulingTable {
  padding: 15px;
  border-radius: 20px;
  background-color: #fff;
  overflow: auto;

  .div_title {
    color: #696969;
    background-color: #f1efef;
    line-height: 35px;
    height: 35px;
    margin: 20px 0 10px;
    text-align: center;

    > span {
      width: 23%;
      display: inline-block;
      margin-left: 15px;
    }
  }

  > .search {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: flex-start;

    > div {
      margin-left: 10px !important;
      width: 200px !important;
    }

  }

  > .main {
    > .tableBox {
    }
  }
}
</style>
