<template>
  <div class="page_container">
    <div class="report_container">
      <div class="table_title">报表数据</div>
      <div class="search_part">
        <!-- <vxe-select
          keyField="id"
          v-disableKeybord="disabledComponents"
          v-model="pageInfo.experiment_type"
          class="select_class"
          @change="queryTableList"
        >
          <vxe-option
            v-for="op of exp_options"
            :key="op.label"
            :label="op.label"
            :value="op.value"
          ></vxe-option>
        </vxe-select> -->
        <vxe-input
          class="search-input"
          v-model="search_val"
          prefix-icon="vxe-icon-search"
          placeholder="搜索"
          style="width: 60%;"
        ></vxe-input>
        <CommonButton
            class="operate-container"
            size="default"
            paddingLeft="35"
            paddingRight="35"
            height="60"
            type="blue"
            msg="搜索"
            @click="search"
        />
      </div>
      <div class="table_container">
        <vxe-table
          ref="tableRef"
          :data="tableData"
          :row-config="{ isCurrent: true, keyField: 'experiment_id' }"
          stripe
          height="360px"
          @checkbox-change="changeBox"
          @checkbox-all="changeBoxAll"
          :checkbox-config="{
            labelField: '',
            highlight: true,
            trigger: 'row',
            reserve: true,
            range: true,
          }"
        >
          <vxe-column type="checkbox" width="120"></vxe-column>
          <vxe-column field="name" title="样品名称" width="180"></vxe-column>
          <vxe-column field="natural_temp" title="样品熔点" width="160">
            <template #default="{ row }">
              {{row.melting_point ? row.melting_point +'℃' :''}}
            </template>
          </vxe-column>
          <vxe-column field="lower_temp" title="自燃温度" width="160">
            <template #default="{ row }">
              {{ row.natural_temp && row.natural_temp != '-50.0' ? row.natural_temp+'℃' : '-'}}
            </template>
          </vxe-column>

          <vxe-column field="created_time" title="试验时间" width="300"></vxe-column>

          <vxe-column title="操作" min-width="240">
            <template #default="{ row }">
              <div class="operate-container">
                <span @click="goDetail(row)">查看详情</span>
                <span
                  style="color: #cf4a4a; margin-left: 8px"
                  @click="deleteExperiment(row)"
                >
                  删除
                </span>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="foot_btn">
        <CommonButton
          class="back_btn"
          size="default"
          paddingLeft="45"
          height="60"
          paddingRight="45"
          type="info"
          msg="返回"
          @click="router.push('/home')"
        />

        <CommonPage
          :maxNum="maxPage"
          @changePage="handleCurpageChange"
          :page_no="pageInfo.page_no"
        />
        <CommonButton
          size="default"
          paddingLeft="45"
          height="60"
          paddingRight="45"
          type="info"
          msg="导出"
          @click="exportExcel"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { getExpData, deleteExperimentApi, exportDataApi } from "@/api/experiment";
import { notify, message } from "@/utils/message";
import CommonPage from "@/components/CommonPage.vue";
import { exportExcel as exportExcelFn } from "@/utils/index.js";
const disabledComponents = computed(() => {
  return ["disableKeyboard"];
});
const router = useRouter();
let tableData = ref([]);
// let columns = [
//   { field: 'created_time', title: '创建时间', width: 150 },
//   { field: 'user_name', title: '创建人', width: 120 },
//   { field: 'name', title: '样品名称', width: 100 },
//   { field: 'material_type', title: '样品类型', width: 100 },
//   { field: 'experiment_user_name', title: '操作', width: 120 }
// ];
const exp_options = [
  {
    value: "1",
    label: "O.1正式试验流程",
  },
  {
    value: "2",
    label: "O.1参考试验流程",
  },
  {
    value: "3",
    label: "O.3正式试验流程",
  },
  {
    value: "4",
    label: "O.3参考试验流程",
  },
];
const getTypeName = (type) => {
  let name = "";
  switch (type) {
    case "1-1":
      name = "样品与纤维素重量1:1";
      break;
    case "4-1":
      name = "样品与纤维素重量4:1";
      break;
    case "3-2":
      name = "溴酸钾与纤维素重量3:2";
      break;
    case "2-3":
      name = "溴酸钾与纤维素重量2:3";
      break;
    case "3-7":
      name = "溴酸钾与纤维素重量3:7";
      break;
    case "3-1":
      name = "过氧化钙与纤维素重量3:1";
      break;
    case "5-5":
      name = "过氧化钙与纤维素重量1:1";
      break;
    case "1-2":
      name = "过氧化钙与纤维素重量1:2";
      break;
    default:
      name = "未知";
      break;
  }
  return name;
};
const maxPage = ref(1);
const pageInfo = ref({
  page_no: 1,
  page_size: 5,
  name: "",
  experiment_id: "",
  experiment_type: "1",
  date: "",
});
let selectedRowKeys = ref([]);
/*table选中records*/
let selectionRows = ref([]);
const changeBox = ({ checked, records, reserves, row }) => {
  // console.log(checked ? '勾选事件' : '取消事件')
  // console.log('当前选中的数据：' + records)
  // console.log('翻页时其他页的数据：' + reserves)
  // console.log('当前选中的数据行：' + row )
  //勾选选中时
  if (checked) {
    //第一次选数据，还未进行翻页时
    if (reserves.length == 0) {
      selectedRowKeys.value = records.map((v) => v.experiment_id);
      selectionRows.value = records;
    } else {
      //id集合，翻页存在已选中的数据时,拼接新选中的数据
      selectedRowKeys.value = [
        ...reserves.map((v) => v.experiment_id),
        ...records.map((v) => v.experiment_id),
      ];
      //数据集合，翻页存在已选中的数据时,拼接新选中的数据
      selectionRows.value = [...reserves, ...records];
    }
  } else {
    //取消选中时
    let idIndex = selectedRowKeys.value.indexOf(row.experiment_id);
    if (idIndex > -1) {
      //删除取消选中删除指定元素id
      selectedRowKeys.value.splice(idIndex, 1);
    }

    let dataIndex = null;
    for (let i = 0; i < selectionRows.value.length; i++) {
      if (selectionRows.value[i].experiment_id == row.experiment_id) {
        dataIndex = i;
        break;
      }
    }
    //删除取消选中的元素整个对象
    selectionRows.value.splice(dataIndex, 1);
  }
};
// 全选
const changeBoxAll = ({ checked, records, reserves }) => {
  // console.log(checked ? '勾选事件' : '取消事件')
  // console.log('当前选中的数据：' + records)
  // console.log('翻页时其他页的数据：' + reserves)
  //全选中时
  if (checked) {
    //第一次选数据，还未进行翻页时
    if (reserves.length == 0) {
      selectedRowKeys.value = records.map((v) => v.experiment_id);
      selectionRows.value = records;
    } else {
      //id集合，翻页存在已选中的数据时,拼接新选中的数据
      selectedRowKeys.value = [
        ...reserves.map((v) => v.experiment_id),
        ...records.map((v) => v.experiment_id),
      ];
      //数据集合，翻页存在已选中的数据时,拼接新选中的数据
      selectionRows.value = [...reserves, ...records];
    }
  } else {
    //取消全选时,直接将翻页数据赋值，当前页数据不用加上
    selectionRows.value = reserves;
    selectedRowKeys.value = reserves.map((v) => v.experiment_id);
  }
};

// 分页
const handleCurpageChange = (type) => {
  if (type === "pre") {
    if (pageInfo.value.page_no == 1) return;
    if (pageInfo.value.page_no > 1) {
      pageInfo.value.page_no--;
    }
  } else if (type === "next") {
    if (pageInfo.value.page_no == maxPage.value) return;
    if (pageInfo.value.page_no < maxPage.value) {
      pageInfo.value.page_no = pageInfo.value.page_no + 1;
    }
  } else {
    pageInfo.value.page_no = type;
  }
  queryTableList();
};
const queryTableList = async () => {
  let res = await getExpData(pageInfo.value);
  let { code, data, desc, pagination } = res.data;

  if (code == 200) {
    tableData.value = data;
    let total_count = pagination.total_count;
    console.log(total_count);
    maxPage.value = Math.ceil(total_count / pageInfo.value.page_size) || 1;
    console.log(maxPage.value);
    // tableData.value.forEach((item) => {
    //   let num = item['control_temp_list'].split(',')[3];
    //   num == 1 ? (item.type = '正式试验') : (item.type = '自定义试验');
    // });
  } else {
    return notify(desc, "danger");
  }
};
queryTableList();
const selectRows = ref([]); //选中的数据
const tableRef = ref(null);
const exportExcel = async () => {
  // selectedRowKeys();
  const table = tableRef.value;
  if (table) {
    // table.toggleAllCheckboxRow();
    const selectRecords = table.getCheckboxRecords();
    selectRows.value = selectRecords.map((item) => item.experiment_id);
  }
  if (selectRows.value.length == 0)
    // return message("请选择要导出的数据");
    return notify("请选择要导出的数据");
  if(selectRows.value.length > 1)
    // return message("一次只能导出一个数据");
    return notify("一次只能导出一个数据");
  let data = {
    ids: selectedRowKeys.value,
    download_type: "usb",
  };
  let res = await exportDataApi(data);
  if (res?.data?.type == "application/json") {
    // U盘
    notify("导出成功", "success");
    return;
  }
  // 浏览器
  exportExcelFn(
    res,
    new Date()
      .toLocaleString()
      .replaceAll("/", "")
      .replaceAll(":", "")
      .replaceAll(" ", "") + "--固体相对自燃点报表"
  ); // notify("导出成功", "success");
  // let code = res.data.code;
  // if (code == 200) {
  //   message(res.data.desc);
  // }
  //执行导出逻辑
  //清空选中
  // table.clearCheckboxRow();
  // selectRows.value = [];
};
const search_val = ref("");
const search = () => {
  pageInfo.value.page_no = 1;
  pageInfo.value.name = search_val.value;
  queryTableList();
};

let queryData = ref("1");
const goDetail = (row) => {
  // if (row.experiment_type == "1" || row.experiment_type == "2") {
  //   queryData.value = "1";
  // } else if (row.experiment_type == "3" || row.experiment_type == "4") {
  //   queryData.value = "3";
  // }

  router.push({
    path: "/report/detail",
    query: {
      experiment_id: row.experiment_id,
      data: queryData.value,
    },
  });
};

const deleteExperiment = async (row) => {
  let res = await deleteExperimentApi(row.experiment_id);
  if (res.data.code == 200) {
    notify(res.data.desc, "success");
    queryTableList();
  } else {
    notify(res.data.desc, "danger");
  }
};
</script>
<style lang="less" scoped>
@SIZE: 16px;
.page_container {
  overflow: auto;
  width: 100%;
}
:deep(.vxe-table) {
  .vxe-body--row,
  .vxe-header--row {
    height: .04rem!important;
    .vxe-body--column,
    .vxe-header--column {
      padding: .1rem 0;
    }
  }
}
.report_container {
  width: 100%;
  background: #f6f6f6;
  box-shadow: 0px 3px 9px 1px rgba(0, 0, 0, 0.16);
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #cccc;
  padding: @SIZE;
  .table_title {
    font-weight: bold;
    font-size: @SIZE;
    color: #3a3a3a;
    margin-bottom: @SIZE;
  }
  .search_part {
    margin-bottom: 12px;
    display: flex;
    //justify-content: space-between;
    align-items: center;
  }
  .operate-container {
    color: #208be9;
  }
  .foot_btn {
    position: fixed;
    display: flex;
    height: 60px;
    width: 100vw;
    bottom: 0;
    left: 0;
    background: #ffffff;
    align-items: center;
    padding: 12px;
    box-sizing: border-box;
    justify-content: space-between;
    .back_btn {
      margin-right: 180px;
    }
  }
}
</style>
