<template>
  <div class="data-container">
    <div class="table-container">
      <div class="data-header">
        <div class="title">{{ is_formal ? '正式' : '校准' }}试验报表</div>
        <vxe-input
          v-disableKeybord="disabledComponents"
          :disabled-method="handleDisabledMouth"
          v-model="selectMouth"
          class="date-input"
          type="month"
          size="medium"
          :editable="false"
          ref="inputElement"
          @change="handleMouthChange" />
      </div>
      <div class="input-container">
        <vxe-input v-model="searchVal" className="search-input">
          <template #prefix>
            <i class="vxe-icon-search"></i>
          </template>
        </vxe-input>
        <CommonButton size="default" class="searchBtn" msg="搜索" @click="handleSearch" />
      </div>
      <div class="content-container">
        <!-- <CommonTable :tableData="tableData" :headers="columsList">
          <template #actions="{ row, index }">
            <div class="operate-container">
              <span @click="openDia(row)">修改{{ is_formal ? '包装下热损失' : '物质比热' }}</span>
              <span @click="goDetail(row)">详情</span>
            </div>
          </template>
        </CommonTable> -->
        <vxe-table :data="tableData" stripe ref="tableRef" min-height="350px">
          <vxe-column type="checkbox" width="60">
            <template #header="{ checked, indeterminate }">
              <span class="custom-checkbox" @click.stop="selectAllChangeEvent">
                <i v-if="indeterminate" class="vxe-icon-square-minus-fill"></i>
                <i v-else-if="checked" class="vxe-icon-square-checked-fill"></i>
                <i v-else class="vxe-icon-checkbox-unchecked"></i>
              </span>
            </template>
            <template #checkbox="{ row, checked, indeterminate }">
              <span class="custom-checkbox" @click.stop="selectChangeEvent(row)">
                <i v-if="indeterminate" class="vxe-icon-square-minus-fill"></i>
                <i v-else-if="checked" class="vxe-icon-square-checked-fill"></i>
                <i v-else class="vxe-icon-checkbox-unchecked"></i>
              </span>
            </template>
          </vxe-column>
          <vxe-column type="seq" width="60" title="序号"></vxe-column>
          <vxe-column
            v-for="col of computedColums"
            :field="col.field"
            :title="col.title"
            :width="col.width || 150">
            <template #default="{ row }" v-if="col.field === 'is_self_acceleration'">
              <div>
                {{ row.is_self_acceleration ? '是' : '否' }}
              </div>
            </template>
            <template #default="{ row }" v-if="col.field === 'is_all_finish'">
              <div>
                {{ row.is_all_finish ? '是' : '否' }}
              </div>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="400">
            <template #default="{ row }">
              <div class="operate-container">
                <span @click="openDia(row)">修改{{ is_formal ? '包装下热损失' : '物质比热' }}</span>
                <span @click="goDetail(row)">详情</span>
                <span @click="handleDel(row)">删除</span>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="footer-part">
        <CommonButton size="default" type="info" msg="返回" @click="router.push('/datamanage')" />
        <Page
          :maxNum="pageInfo.maxPage"
          @changePage="handleCurpageChange"
          :page_no="pageInfo.page_no" />
        <CommonButton size="default" type="danger" msg="导出" @click="exprotTableDataUsb" />
      </div>
    </div>
  </div>
  <FixDia
    :type="is_formal"
    :visibile="dia_visibile"
    @cancel="dia_visibile = false"
    @confirm="handleFixData" />
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import Page from './components/Page.vue';
import { useRouter, useRoute } from 'vue-router';
import FixDia from './components/FixDia.vue';
import { exportExcel } from '@/utils/index.js';
import {
  updateLossRate,
  updateHeatLoss,
  getExpData,
  exportDataApi,
  exportDataBrowserApi,
  delExperimentApi
} from '@/api/experiment.js';
import { exportExcel as exportExcelFn } from '@/utils/index.js';
import { notify, message } from "@/utils/message";

import CommonTable from '../../components/CommonTable.vue';
const disabledComponents = computed(() => {
  return ['disableKeyboard'];
});
const router = useRouter();
const route = useRoute();
const { path } = route;
const is_formal = ref(path == '/formal_expData' ? true : false);
const getCurMouth = (date) => {
  date = new Date(date);
  let year = date.getFullYear();
  let mounth = date.getMonth() + 1;
  return `${year}-${mounth > 10 ? '' : 0}${mounth}`;
};
const selectMouth = ref(new Date());
const searchVal = ref('');

//获取列表数据
const pageInfo = ref({
  page_no: 1,
  page_size: 5,
  maxPage: 1
});
const getTableData = async () => {
  let date = getCurMouth(selectMouth.value);
  let data = {
    types: is_formal.value ? 2 : 1,
    date,
    name: searchVal.value,
    ...pageInfo.value
  };
  //console.log(data);
  let res = await getExpData(data);
  tableData.value = res.data.data;
  let total_count = res.data.pagination.total_count;
  pageInfo.value.maxPage = Math.ceil(total_count / pageInfo.value.page_size) || 1;
};
getTableData();
const computedColums = computed(() => {
  return columsList.filter((item) => {
    return is_formal.value ? item.show !== 'not_formal' : item.show !== 'is_formal';
  });
});
//执行搜索操作
const handleMouthChange = (val) => {
  pageInfo.value.page_no = 1;
  getTableData();
};
const handleDisabledMouth = ({ date, viewType }) => {
  return date > new Date();
};
const columsList = [
  {
    title: '待测物质名称',
    field: 'name',
    width: 150,
    show: 'normal'
  },
  {
    title: '检测人',
    field: 'user_name',
    width: 100,
    show: 'normal'
  },
  {
    title: '检测时间',
    field: 'created_time',
    width: 195,
    show: 'normal'
  },
  {
    title: '是否发生自加速反应',
    field: 'is_self_acceleration',
    width: 200,
    show: 'is_formal'
  },
  {
    title: '结果数据是否完整',
    field: 'is_all_finish',
    width: 200,
    show: 'not_formal'
  }
];
const tableData = ref([]);
const goDetail = (row) => {
  let path = is_formal.value ? '/formal_expDataDetail' : '/cal_expDataDetail';
  let id = is_formal.value ? row.experiment_id : row.experimentjz_id;
  router.push({ path, query: { id } });
};
const dia_visibile = ref(false);
const select_experiment_id = ref('');
const openDia = (row) => {
  if (!is_formal.value) {
    select_experiment_id.value = row.experimentjz_id;
  } else {
    select_experiment_id.value = row.experiment_id;
  }
  dia_visibile.value = true;
};
//修改比热
const handleFixData = async (val) => {
  if (!val) return message('请输入数值再提交');
  let data;
  if (!is_formal.value) {
    data = {
      experimentjz_id: select_experiment_id.value,
      specific_heat: val
    };
    let res = await updateLossRate(data);
    message(res.data.desc);
  } else {
    data = {
      experiment_id: select_experiment_id.value,
      loss_rate: val
    };
    let res = await updateHeatLoss(data);
    message(res.data.desc);
  }
  select_experiment_id.value = '';
  dia_visibile.value = false;
};

//分页
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 == pageInfo.value.maxPage) return;
    if (pageInfo.value.page_no < pageInfo.value.maxPage) {
      pageInfo.value.page_no = pageInfo.value.page_no + 1;
    }
  } else {
    pageInfo.value.page_no = type;
  }
  getTableData();
};
//处理table复选的
const tableRef = ref();
const selectRows = ref([]); //选中的数据

const selectAllChangeEvent = () => {
  console.log('111');
  const table = tableRef.value;
  if (table) {
    table.toggleAllCheckboxRow();
    const selectRecords = table.getCheckboxRecords();
    selectRows.value = selectRecords.map((item) =>
      is_formal.value ? item.experiment_id : item.experimentjz_id
    );
  }
};
const selectChangeEvent = (row) => {
  console.log(row, '222');
  const table = tableRef.value;
  if (table) {
    table.toggleCheckboxRow(row);
    const selectRecords = table.getCheckboxRecords();
    selectRows.value = selectRecords.map((item) =>
      is_formal.value ? item.experiment_id : item.experimentjz_id
    );
  }
};
//usb
const exprotTableDataUsb = async () => {
  if (selectRows.value.length == 0) return message('请选择要导出的数据');
  let data = {
    experiment_type: is_formal.value ? '2' : '1',
    ids: selectRows.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(' ', '')+'--粉尘云最低着火温度报表报表') 
  // let code = res.data.code;
  // if (code == 200) {
  //   message(res.data.desc);
  // }
  const table = tableRef.value;
  //执行导出逻辑
  //清空选中
  table.clearCheckboxRow();
  selectRows.value = [];
};
//浏览器
const exprotTableData = async () => {
  if (selectRows.value.length == 0) return message('请选择要导出的数据');
  let data = {
    experiment_type: is_formal.value ? '2' : '1',
    ids: selectRows.value,
    download_type: ''
  };
  let res = await exportDataBrowserApi(data);
  exportExcel(res);
};

const handleSearch = () => {
  pageInfo.value.page_no = 1;
  getTableData();
};

const handleDel = async (row) => {
  let data = {
    experiment_type: is_formal.value ? '2' : '1',
    id: is_formal.value ? row.experiment_id : row.experimentjz_id
  };
  let res = await delExperimentApi(data);
  if (res.code == 200) {
    message(res.data.desc);
  }
  getTableData();
};
</script>
<style lang="less" scoped>
@commonSize: 40px;
.data-container {
  width: 100%;
  height: 100%;
  padding: @commonSize;
  padding-bottom: 21px;
  .table-container {
    padding: 52px @commonSize;
    padding-bottom: 36px;
    background: #f6f6f6;
    box-shadow: 0px 3px 9px 1px rgba(0, 0, 0, 0.16);
    border-radius: 12px 12px 12px 12px;
    border: 1px solid #cccccc;
    .data-header {
      font-size: 48px;
      font-weight: bold;
      color: #3a3a3a;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 30px;
      .date-input {
        margin-right: 60px;
        width: 200px;
        height: 50px;
        font-size: 32px;
      }
    }
    .input-container {
      width: 100%;
      height: 100px;
      display: flex;
      justify-content: space-between;
      .search-input {
        width: 60%;
        height: 100%;
        font-size: 40px;
      }
      .searchBtn {
        margin-right: 50px;
      }
    }
  }

  .content-container {
    margin-top: 30px;
  }
  .operate-container {
    color: #208be9;
    display: flex;
    justify-content: space-evenly;
  }
  .footer-part {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
  }
}
.vxe-icon-square-minus-fill {
  color: #208be9;
}
.vxe-icon-square-checked-fill {
  color: #208be9;
}
</style>
