<template>
  <el-card class="box-card">
    <byTable
      :hideTable="true"
      :hidePagination="true"
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      :searchConfig="searchConfig"
      highlight-current-row
      :action-list="[
        {
          text: '导出Excel',
          action: () => clickExcel(),
        },
        {
          text: 'Excel文件',
          action: () => clickExcelFile(),
        },
      ]"
      @get-list="getList"
      @clickReset="clickReset"
      @changeRadioGroup="changeRadioGroup">
    </byTable>
    <el-table
      :data="sourceList.data"
      border
      :row-style="{ height: '35px' }"
      header-row-class-name="tableHeader"
      :span-method="objectSpanMethod"
      max-height="calc(100vh - 344px)">
      <el-table-column label="发货时间" prop="statementOfAccountTime" align="center" width="160" />
      <el-table-column label="事业部" prop="departmentName" width="120" />
      <el-table-column label="店铺" prop="shopName" width="160" />
      <el-table-column label="MES系统单号" prop="mesCode" width="180" />
      <el-table-column label="万里牛销售单号" prop="sellCode" width="180" />
      <el-table-column label="万里牛单号" prop="wlnCode" width="140" />
      <el-table-column label="SKU单号" prop="skuSpecCode" width="140" />
      <el-table-column label="SKU品号" prop="skuSpecName" width="180" />
      <el-table-column label="SKU数量" prop="quantitySKU" align="center" width="90" />
      <el-table-column label="BOM品号" prop="bomSpecCode" width="140" />
      <el-table-column label="BOM品名" prop="bomSpecName" width="300" />
      <el-table-column label="定制加工类型" prop="customProcessingType" width="140" />
      <el-table-column label="存货会计分类" prop="classifyName" width="120" />
      <el-table-column label="单位" prop="unit" width="80" />
      <el-table-column label="BOM数量" prop="quantityBOM" align="center" width="90" />
      <el-table-column label="单价" prop="unitPriceBOM" align="center" width="80" />
      <el-table-column label="激光LOGO" prop="laserLogoSummary" align="center" width="100" />
      <el-table-column label="激光体位线" prop="laserMitochondrialSummary" align="center" width="100" />
      <el-table-column label="代发费" prop="lssueFeeSummary" align="center" width="90" />
      <el-table-column label="快递包材费" prop="deliveryMaterialsFeeSummary" align="center" width="100" />
      <el-table-column label="包装人工费" prop="packingLaborSummary" align="center" width="100" />
      <el-table-column label="管理费" prop="managementFeeSummary" align="center" width="90" />
      <el-table-column label="SKU单价" prop="unitPriceSKU" align="center" width="90" />
      <el-table-column label="小计" align="center" width="120">
        <template #default="{ row }">
          {{ moneyFormat(row.subtotal) }}
        </template>
      </el-table-column>
      <el-table-column label="外箱包装费" prop="outerBoxPackingFee" align="center" width="100" />
      <el-table-column label="合计" align="center" width="120">
        <template #default="{ row }">
          {{ moneyFormat(row.total) }}
        </template>
      </el-table-column>
    </el-table>

    <el-row style="padding: 10px 0" justify="end" type="flex">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="sourceList.pagination.pageNum"
        :page-size="sourceList.pagination.pageSize"
        :total="sourceList.pagination.total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange" />
    </el-row>

    <el-dialog title="Excel文件" v-if="openFileList" v-model="openFileList" width="60%">
      <ExcelFile></ExcelFile>
      <template #footer>
        <el-button @click="openFileList = false" size="large">关 闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import byTable from "/src/components/byTable/index";
import * as date from "/src/utils/date";
import { ElMessage } from "element-plus";
import ExcelFile from "/src/views/group/finance/check-bill/ExcelFile.vue";

const { proxy } = getCurrentInstance();
const departmentList = ref([{ dictKey: "0", dictValue: "胜德体育" }]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    code: "",
    departmentId: "",
    skuSpecCode: "",
    skuSpecName: "",
    beginTime: "",
    endTime: "",
    type: 1,
  },
});
const loading = ref(false);
const searchConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "code",
      label: "订单号",
    },
    {
      type: "select",
      prop: "departmentId",
      data: departmentList.value,
      label: "事业部",
    },
    {
      type: "input",
      prop: "skuSpecCode",
      label: "SKU品号",
    },
    {
      type: "input",
      prop: "skuSpecName",
      label: "SKU品名",
    },
    {
      type: "radio-group",
      prop: "type",
      label: "维度",
      data: [
        {
          dictKey: 1,
          dictValue: "本年度",
        },
        {
          dictKey: 2,
          dictValue: "近365天",
        },
        {
          dictKey: 3,
          dictValue: "近180天",
        },
        {
          dictKey: 4,
          dictValue: "近90天",
        },
      ],
    },
    {
      type: "date",
      propList: ["beginTime", "endTime"],
      label: "日期",
    },
  ];
});
const config = computed(() => {
  return [];
});
const getDemandData = () => {
  proxy.post("/department/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      departmentList.value = departmentList.value.concat(
        res.rows.map((item) => {
          return {
            dictKey: item.id,
            dictValue: item.name,
          };
        })
      );
    }
  });
};
getDemandData();
const mergeRow = (list) => {
  for (let field in list[0]) {
    let k = 0;
    let i = 0;
    while (k < list.length) {
      list[k][field + "Span"] = 1;
      list[k][field + "Dis"] = false;
      for (i = k + 1; i <= list.length - 1; i++) {
        if (["statementOfAccountTime", "departmentName", "shopName", "mesCode", "sellCode", "wlnCode", "outerBoxPackingFee", "total"].includes(field)) {
          if (list[k][field] === list[i][field] && list[k].orderId === list[i].orderId) {
            list[k][field + "Span"]++;
            list[k][field + "Dis"] = false;
            list[i][field + "Span"] = 1;
            list[i][field + "Dis"] = true;
          } else {
            break;
          }
        } else {
          if (list[k][field] === list[i][field] && list[k].orderId === list[i].orderId && list[k].skuSpecCode === list[i].skuSpecCode) {
            list[k][field + "Span"]++;
            list[k][field + "Dis"] = false;
            list[i][field + "Span"] = 1;
            list[i][field + "Dis"] = true;
          } else {
            break;
          }
        }
      }
      k = i;
    }
  }
  return list;
};
const getList = async (req, status) => {
  if (status) {
    sourceList.value.pagination = {
      pageNum: sourceList.value.pagination.pageNum,
      pageSize: sourceList.value.pagination.pageSize,
    };
  } else {
    sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  }
  loading.value = true;
  proxy.post("/statementOfAccountMerge/salesOutWarehouseDetails", sourceList.value.pagination).then((res) => {
    let list = [];
    if (res.rows && res.rows.length > 0) {
      for (let i = 0; i < res.rows.length; i++) {
        let mesCode = "";
        let sellCode = "";
        if (res.rows[i].wlnCode) {
          sellCode = res.rows[i].code;
        } else {
          mesCode = res.rows[i].code;
        }
        if (res.rows[i].skuSpecList && res.rows[i].skuSpecList.length > 0) {
          for (let j = 0; j < res.rows[i].skuSpecList.length; j++) {
            if (res.rows[i].skuSpecList[j].bomSpecList && res.rows[i].skuSpecList[j].bomSpecList.length > 0) {
              for (let y = 0; y < res.rows[i].skuSpecList[j].bomSpecList.length; y++) {
                list.push({
                  orderId: res.rows[i].orderId,
                  statementOfAccountTime: res.rows[i].statementOfAccountTime,
                  departmentName: res.rows[i].departmentName,
                  shopName: res.rows[i].shopName,
                  mesCode: mesCode,
                  sellCode: sellCode,
                  wlnCode: res.rows[i].wlnCode,
                  skuSpecCode: res.rows[i].skuSpecList[j].skuSpecCode,
                  skuSpecName: res.rows[i].skuSpecList[j].skuSpecName,
                  quantitySKU: res.rows[i].skuSpecList[j].quantity,
                  bomSpecCode: res.rows[i].skuSpecList[j].bomSpecList[y].bomSpecCode,
                  bomSpecName: res.rows[i].skuSpecList[j].bomSpecList[y].bomSpecName,
                  customProcessingType: res.rows[i].skuSpecList[j].bomSpecList[y].customProcessingType,
                  classifyName: res.rows[i].skuSpecList[j].bomSpecList[y].classifyName,
                  unit: res.rows[i].skuSpecList[j].bomSpecList[y].unit,
                  quantityBOM: res.rows[i].skuSpecList[j].bomSpecList[y].quantity,
                  unitPriceBOM: res.rows[i].skuSpecList[j].bomSpecList[y].unitPrice,
                  laserLogoSummary: res.rows[i].skuSpecList[j].bomSpecList[y].laserLogoSummary,
                  laserMitochondrialSummary: res.rows[i].skuSpecList[j].bomSpecList[y].laserMitochondrialSummary,
                  lssueFeeSummary: res.rows[i].skuSpecList[j].bomSpecList[y].lssueFeeSummary,
                  deliveryMaterialsFeeSummary: res.rows[i].skuSpecList[j].bomSpecList[y].deliveryMaterialsFeeSummary,
                  packingLaborSummary: res.rows[i].skuSpecList[j].bomSpecList[y].packingLaborSummary,
                  managementFeeSummary: res.rows[i].skuSpecList[j].bomSpecList[y].managementFeeSummary,
                  unitPriceSKU: res.rows[i].skuSpecList[j].unitPrice,
                  subtotal: res.rows[i].skuSpecList[j].subtotal,
                  outerBoxPackingFee: res.rows[i].outerBoxPackingFee,
                  total: res.rows[i].total,
                });
              }
            }
          }
        }
      }
    }
    sourceList.value.data = Object.freeze(mergeRow(list));
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
const clickReset = () => {
  sourceList.value.pagination.type = 1;
  changeRadioGroup();
};
const changeRadioGroup = (item) => {
  let beginTime = "";
  let endTime = "";
  if (sourceList.value.pagination.type == 1) {
    beginTime = date.getYearFirstDay();
    endTime = date.getYearLastDay();
  } else if (sourceList.value.pagination.type == 2) {
    let days = date.getDaysNoTime(365);
    beginTime = days.startTime;
    endTime = days.endTime;
  } else if (sourceList.value.pagination.type == 3) {
    let days = date.getDaysNoTime(180);
    beginTime = days.startTime;
    endTime = days.endTime;
  } else if (sourceList.value.pagination.type == 4) {
    let days = date.getDaysNoTime(90);
    beginTime = days.startTime;
    endTime = days.endTime;
  }
  getList({ beginTime: beginTime, endTime: endTime, ...item });
};
changeRadioGroup();
const handlePageChange = (val) => {
  changeRadioGroup({ pageNum: val });
};
const handleSizeChange = (val) => {
  changeRadioGroup({ pageNum: 1, pageSize: val });
};
const openFileList = ref(false);
const clickExcel = () => {
  proxy.postFile("/statementOfAccountMerge/exportSalesOutWarehouseDetails", sourceList.value.pagination).then(() => {
    ElMessage({ message: "导出成功", type: "success" });
    openFileList.value = true;
  });
};
const clickExcelFile = () => {
  openFileList.value = true;
};
const objectSpanMethod = ({ rowIndex, columnIndex }) => {
  if ([0, 1, 2, 3, 4, 5, 6, 7, 8, 22, 23, 24, 25, 26].includes(columnIndex)) {
    let spanName = [
      "statementOfAccountTime",
      "departmentName",
      "shopName",
      "mesCode",
      "sellCode",
      "wlnCode",
      "skuSpecCode",
      "skuSpecName",
      "quantitySKU",
      "",
      "",
      "",
      "",
      "",
      "",
      "",
      "",
      "",
      "",
      "",
      "",
      "",
      "unitPriceSKU",
      "subtotal",
      "outerBoxPackingFee",
      "total",
    ];
    // 第一列的合并方法
    const row1 = sourceList.value.data[rowIndex][spanName[columnIndex] + "Span"];
    const colspan = sourceList.value.data[rowIndex][spanName[columnIndex] + "Dis"] ? 0 : 1;
    const rowspan = colspan === 1 ? row1 : 0;
    return {
      rowspan: rowspan,
      colspan: colspan,
    };
  }
};
</script>

<style lang="scss" scoped></style>
