<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="searchTime"
              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="statProductionLineData"
            show-checkbox
            default-expand-all
            node-key="key"
          />
        </div>
        <div class="header" style="border-bottom: 0px">
          <div class="text">选择统计产品：</div>
          <el-input
            size="small"
            placeholder="请输入产品名称"
            @click="openProdtForm"
          />
          <el-tree
            ref="treeRef2"
            :data="treeData"
            default-expand-all
            node-key="productName"
            highlight-current
            style="margin-top: 20px"
          />
          <!-- <el-tree
            v-if="prodt.prodtName"
            ref="treeRef2"
            :data="statProductTypeData"
            show-checkbox
            default-expand-all
            :default-checked-keys="['productType1']"
            node-key="key"
            style="margin-top: 20px"
          /> -->
        </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/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="queryIndexs.includes('productLine')"
              prop="productLineName"
              label="产线名称"
            />
            <el-table-column
              v-if="queryIndexs.includes('prodict')"
              prop="materialName"
              label="产品名称"
            />
            <el-table-column
              v-if="queryIndexs.includes('operation')"
              prop="operationName"
              label="工序名称"
            /> -->
            <el-table-column prop="workshopName" label="车间名称" />
            <el-table-column prop="materialName" label="产品名称" />
            <el-table-column prop="materialCode" label="产品编码" />
              <el-table-column prop="materialModel" label="产品规格" />
            <el-table-column prop="workOrderCode" label="产品批次" />
            <el-table-column prop="qualified" label="良率" />
            <el-table-column prop="noQualified" label="不良率" />
            <el-table-column prop="updated" label="日期" />
          </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>

  <CrudTable
      ref="ctableRef"
      tableTitle="选择统计产品"
      :multipleRow="multipleRow"
      tableType="WORK_ORDER"
      @selected-sure="handleConfirm"
  />
</template>

<script setup>
import {getData, getStatLevel, getExport} from "@/api/statistic";
import { getMockData } from "@/api/statistic/firstPassYieldMockData";
import Pagination from "@/components/Pagination/index.vue";
import { downFile } from "@/utils/common";
import Search from "@/components/Search/index.vue";
import {getWorkOrderInfo, getWorkShop} from "@/api/statistic/firstPassYieldData";
import {useCrud} from "@/hooks/userCrud";
const checkList=ref(null);
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
    useCrud({
        src: "/api/v1/quality/stat",
    });
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});
const ctableRef=ref(null);
const treeRef1 = ref(null);
const treeRef2 = ref(null);
const currentOption = ref({
  total: 0,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 30, 40, 50, 100],
});

const maxHeight = ref(null);
const maxWidth = 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();

  // 获取当前月份的第一天4r
  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].label);
  }
  return resarray;
};
// const getTableData = async () => {
//   queryIndexs.value = getValue(treeRef1.value.getCheckedNodes());
//   const { data } = await getData({
//     endTime: value1.value ? value1.value[1] : "",
//     startTime: value1.value ? value1.value[0] : "",
//     pageNo: currentOption.value.page,
//     pageSize: currentOption.value.limit,
//     queryTypes: getValue(treeRef1.value.getCheckedNodes()),
//     queryIndex: getValue(treeRef2.value.getCheckedNodes()),
//     timeType: radio.value,
//   });
//   tableData.value = data.records;
//   currentOption.value.total = data.totalCount;
// };

// mock数据
const getTableData = async () => {
    search.value={};
  const { data } = await getWorkOrderInfo({
    pageNo: currentOption.value.page,
    pageSize: currentOption.value.limit,
    endTime: searchTime.value ? searchTime.value[1] : "",
    startTime: searchTime.value ? searchTime.value[0] : "",
    queryTypes: getValue(treeRef1.value.getCheckedNodes()),
    queryIndex: workOrderCodes.value,
  }); // 使用假数据函数
    search.value.startTime=searchTime.value ? searchTime.value[0] : "",
        search.value.endTime=searchTime.value ? searchTime.value[1] : "",
        search.value.queryTypes=getValue(treeRef1.value.getCheckedNodes()),
        search.value.queryIndex=workOrderCodes.value,
  tableData.value = data.records;
  currentOption.value.total = data.totalCount;
};
// -------

const reset = () => {searchTime.value = getCurrentMonthStartAndEndDates();
  //treeRef1.value.setCheckedKeys([statProductionLineData[0].key], true, true);
    //statProductionLineData.value=[];
    //treeRef1.value.setCheckedKeys([statProductionLineData[0].key], true, true);
    treeData.value=[];
    workOrderCodes.value=[];
  currentOption.value.page = 1;
  getTableData();
};

// mock数据
const statProductionLineData = ref([
]);

const tableProdtData = ref([]);
const dialogVisible = ref(false);
const searchRef = ref(null);
const searchTime =ref(null);
const openProdtForm = async () => {
  ctableRef.value.startSelect();
  ctableRef.value?.mergeOption({
    selection: true,
    reserveSelection: true,
  });
};
const multipleRow = ref(true);
const getProdtData = async () => {
  const { data } = await getMockData({
    page: currentProdtOption.value.page,
    limit: currentProdtOption.value.limit,
  }); // 使用假数据函数
  tableProdtData.value = data.records;
  currentProdtOption.value.total = data.totalCount;
};


const currentProdtOption = ref({
  total: 0,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 30, 40, 50, 100],
});
// --------------------------------------------

const selectedRows = ref([]); // 存储选中的行数据


const treeData = ref([]); // 存储转换后的 el-tree 数据

const workOrderCodes = ref([]);
const handleConfirm = (val) => {
  const map = {};
  const tree = [];
    workOrderCodes.value=[];
  val.forEach((row) => {
      workOrderCodes.value.push(row.workOrderCode);
    const { materialName, workOrderCode } = row;

    // 如果父级节点不存在，创建父级节点
    if (!map[materialName]) {
      const parentNode = {
        label: materialName, // 父级名称
        key: materialName, // 父级唯一标识
        children: [], // 子级数组
      };
      map[materialName] = parentNode;
      tree.push(parentNode);
    }

    // 添加子级节点
    map[materialName].children.push({
      label: workOrderCode, // 子级名称
      key: workOrderCode, // 子级唯一标识
    });
  });

  treeData.value = tree; // 更新 el-tree 数据源
};
//列表搜索体哦阿健
const searchPageForm = ref({});
const getTableDataSearch = () => {
 /* if (treeData.value.length === 0) {
    ElMessage.warning("请选择产品");
    return;
  }*/
  // 提取 treeData 中的 productName 和 batchNo
  const selectedProductMap = {};
  treeData.value.forEach((parent) => {
    selectedProductMap[parent.label] = parent.children.map(
      (child) => child.label
    );
  });

  // 筛选 tableProdtData 中符合条件的数据
  const filteredData = tableProdtData.value.filter((item) => {
    const productNameMatches = selectedProductMap[item.productName];
    return productNameMatches && productNameMatches.includes(item.batchNo);
  });

  // 更新表格数据
  tableData.value = filteredData;
};
//-------------------

const checkedKeys = computed(() => {
  let array = [];
  for (let i = 0; i < statProductionLineData.value.length; i++) {
    array.push(statProductionLineData.value[i].key);
  }
  return array;
});
const getWorkShopList=()=>{
    getWorkShop({}).then(
        (data)=>{
          statProductionLineData.value=data.data;

        }
    )
}
/*const handleCheckChange=(data, checked, indeterminate)=>{
    console.log("aaaaa",data); // 选中的节点数据
    console.log(checked); // 是否选中
    console.log(indeterminate); // 是否为半选状态
}*/
onMounted(async () => {

  window.addEventListener("resize", setHeight);
    searchTime.value = getCurrentMonthStartAndEndDates();
    search.value.startTime=searchTime.value[0];
    search.value.endTime=searchTime.value[1];
    setHeight();
  await  getWorkShopList();
  // await getStatLevelData();
  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;
    }
  }
  .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;
}

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