<template>
  <div class="container1" id="shijian">
    <div class="infobox">
      <el-scrollbar>
        <div class="header">
          <div class="text">选择统计时间段：</div>
          <div style="display: flex">
            <el-date-picker
              v-model="searTime"
              type="daterange"
              range-separator="-"
              start-placeholder="起始时间"
              end-placeholder="截止时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              size="small"
            />
          </div>
        </div>
        <!--        <div class="header">
          <div class="text">选择统计维度：</div>
          <div>
            <el-radio-group v-model="radio" style="display: flex">
              <el-radio size="small" :value="1">天</el-radio>
              <el-radio size="small" :value="2">周</el-radio>
              <el-radio size="small" :value="3">月</el-radio>
              <el-radio size="small" :value="4">年</el-radio>
            </el-radio-group>
          </div>
        </div>-->
        <div class="header">
          <div class="text">选择统计维度：</div>
          <el-tree
            ref="treeRef1"
            :data="statLevelData"
            show-checkbox
            default-expand-all
            :default-checked-keys="checkedKeys"
            node-key="key"
          />
        </div>
        <div class="header" style="border-bottom: 0px">
          <div class="text">选择统计指标：</div>
          <el-tree
            ref="treeRef2"
            :data="data1"
            show-checkbox
            default-expand-all
            :default-checked-keys="['合格率']"
            node-key="key"
            highlight-current
          />
        </div>
      </el-scrollbar>
    </div>
    <div class="databox">
      <div class="box">
        <div class="boxheader">
          <div>
            <el-button type="primary" class="btn" @click="getTableData"
              >统计查询</el-button
            >
            <el-button class="btn" @click="reset">重置</el-button>
          </div>
          <el-button
            class="ml-3"
            @click="exportData('/api/v1/quality/stat/quality/export')"
          >
            <template #icon> <i-ep-download /> </template>导出
          </el-button>
        </div>
        <div class="info">
          <el-table
            :data="tableData"
            border
            :style="{ height: maxHeight + 'px' }"
            style="width: calc(100% - 50)"
          >
            <el-table-column
              v-if="queryTypes.includes('productLine')"
              prop="productLineName"
              label="产线名称"
            />
            <el-table-column
              v-if="queryTypes.includes('workSection')"
              prop="workSection"
              label="工段名称"
            />
            <el-table-column
              v-if="queryTypes.includes('operation')"
              prop="operationName"
              label="工序名称"
            />
            <el-table-column prop="materialName" label="产品名称" />
            <el-table-column prop="materialCode" label="产品编号" />
            <el-table-column prop="materialModel" label="产品规格" />
            <el-table-column prop="produceNum" label="生产数量" />
            <el-table-column
              v-if="queryIndexs.includes('pass')"
              prop="qualified"
              label="合格率"
            />
            <el-table-column
              v-if="queryIndexs.includes('oneTimePassRate')"
              prop="oneTimePassRate"
              label="一次性合格率"
            />
            <el-table-column
              v-if="queryIndexs.includes('PPM')"
              prop="ppm"
              label="PPM"
            />
          </el-table>
        </div>
        <div class="footer">
          <Pagination
            :total="currentOption.total"
            :page="currentOption.page"
            :limit="currentOption.limit"
            :pageSizes="currentOption.pageSizes"
            v-model:page="currentOption.page"
            v-model:limit="currentOption.limit"
            @pagination="getTableData"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getData, getStatLevel, getExport } from "@/api/statistic";
import Pagination from "@/components/Pagination/index.vue";
import { downFile } from "@/utils/common";
import {
  getWorkInfoRate,
  getWorkOrderInfo,
} from "@/api/statistic/firstPassYieldData";
import { useCrud } from "@/hooks/userCrud";
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/quality/stat",
  });
const { checkBtnPerm, downloadTemplate, exportData } = Utils;
const exportFnc = async () => {
  await getExport({
    endTime: searTime.value ? searTime.value[1] : "",
    startTime: searTime.value ? searTime.value[0] : "",
    queryTypes: getValue(treeRef1.value.getCheckedNodes()),
    queryIndex: getValue(treeRef2.value.getCheckedNodes()),
    timeType: radio.value,
  }).then((res) => downFile(res));
};
const treeRef1 = ref(null);
const treeRef2 = ref(null);
const currentOption = ref({
  total: 0,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 50, 100],
});

const maxHeight = ref(null);
const maxWidth = ref(null);

const searTime = ref(null);
const radio = ref("1");
const tableData = ref([]);

const setHeight = () => {
  maxHeight.value = document.querySelector(".info").clientHeight - 30;
  maxWidth.value = document.querySelector(".info").clientWidth - 120;
};
const getCurrentMonthStartAndEndDates = () => {
  // 获取当前日期
  let now = new Date();

  // 获取当前月份的第一天
  let startDate = new Date(now.getFullYear(), now.getMonth(), 1);

  // 获取当前月份的最后一天
  let endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);

  // 格式化日期为'YYYY-MM-DD'格式
  function formatDate(date) {
    let year = date.getFullYear();
    let month = String(date.getMonth() + 1).padStart(2, "0");
    let day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  }

  // 返回包含开始和结束日期的数组
  return [formatDate(startDate), formatDate(endDate)];
};
const getValue = (array) => {
  let resarray = [];
  for (let i = 0; i < array.length; i++) {
    resarray.push(array[i].value);
  }
  return resarray;
};
const queryIndexs = ref([]);
const queryTypes = ref([]);
const getTableData = async () => {
  queryTypes.value = getValue(treeRef1.value.getCheckedNodes());
  queryIndexs.value = getValue(treeRef2.value.getCheckedNodes());
  const { data } = await getWorkInfoRate({
    endTime: searTime.value ? searTime.value[1] : "",
    startTime: searTime.value ? searTime.value[0] : "",
    pageNo: currentOption.value.page,
    pageSize: currentOption.value.limit,
    queryTypes: getValue(treeRef1.value.getCheckedNodes()),
    queryIndex: getValue(treeRef2.value.getCheckedNodes()),
  });
  search.value.startTime = searTime.value[0];
  search.value.endTime = searTime.value[1];
  search.value.queryTypes = getValue(treeRef1.value.getCheckedNodes());
  search.value.queryIndex = getValue(treeRef2.value.getCheckedNodes());
  tableData.value = data.records;
  currentOption.value.total = data.totalCount;
};

const reset = () => {
  console.log();
  searTime.value = getCurrentMonthStartAndEndDates();
  treeRef1.value.setCheckedKeys(checkedKeys.value, true, true);
  treeRef2.value.setCheckedKeys([data1[0].key], true, true);
  radio.value = "1";
  currentOption.value.page = 1;
  getTableData();
};
const data1 = [
  {
    value: "pass",
    key: "合格率",
    label: "合格率",
  },
  {
    value: "oneTimePassRate",
    key: "一次性送检合格率",
    label: "一次性送检合格率",
  },
  {
    value: "PPM",
    key: "PPM",
    label: "PPM",
  },
];
const statLevelData = ref([]);
const getStatLevelData = async () => {
  const { data } = await getStatLevel();
  data.forEach((element) => {
    element.label = element.key;
  });
  statLevelData.value = data;
};
const checkedKeys = computed(() => {
  let array = [];
  for (let i = 0; i < statLevelData.value.length; i++) {
    array.push(statLevelData.value[i].key);
  }
  return array;
});

onMounted(async () => {
  window.addEventListener("resize", setHeight);
  searTime.value = getCurrentMonthStartAndEndDates();
  setHeight();
  await getStatLevelData();
  search.value.startTime = searTime.value[0];
  search.value.endTime = searTime.value[1];
  search.value.queryTypes = getValue(treeRef1.value.getCheckedNodes());
  search.value.queryIndex = getValue(treeRef2.value.getCheckedNodes());
  getTableData();
});
</script>

<style lang="scss" scoped>
.btn {
  margin-left: 10px;
  height: 25px;
}
.container1 {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: white;
  .infobox {
    width: 260px;
    .header {
      border-bottom: 2px solid #00000010;
      padding: 20px;
    }
    .body {
      padding: 20px;
    }
  }
  .el-radio {
    display: block;
  }
  .databox {
    width: calc(100% - 260px);
    border-left: 2px solid #00000010;
    .box {
      height: 100%;
      padding: 5px 20px;
      display: flex;
      flex-direction: column;
      .boxheader {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 10px 0px 10px -10px;
      }
      .info {
        flex: 1;
      }
    }
  }
}
.el-radio {
  margin-right: 8px;
}
</style>

<style lang="scss">
#shijian {
  .is-active {
    background-color: #f5f7fa;
  }
}
</style>
