<script setup>
import { RecordDrawer } from '@/views/report/components';
import { getHomeCounts, getDailyTable, getDeviceList } from '@/api/report/lab';
import { dayjs } from 'element-plus';

const drawerVisible = ref(false);
const tableLoading = ref(false);
const total = ref(0);
const selectOptions = ref({});
const tableData = ref([]);
const drawerData = ref({});
const currentDateTime = ref('');

const categoryOptions = [
  { label: '全部', value: '' },
  { label: '化验室设备', value: 1 },
  { label: '连续检测设备', value: 2 },
]
const deviceNameEnum = {
  "0": "待机中",
  "1": "离线中",
  "2": "化验中"
}

const pageCountNums = ref({
  deviceTotals: 0,
  onDeviceCounts: 0,
  standbyDeviceCounts: 0,
  offDeviceCounts: 0,
  passAssayRates: 0,
  assayTotals: 0,
  passAssayTotals: 0
});

const queryParams = ref({ 
  assayStatus: '',
  assayDate: dayjs().format("YYYY-MM-DD"),
  deviceNo: '',
  type: '',
  pageNum: 1,
  pageSize: 10
 });

const getDeviceClass = ({ assayStatus: key }) => {
  const colorEnum = {
    "0": "bg-[#FADB14]",
    "1": "bg-[#F5222D]",
    "2": "bg-[#52c41a]"
  }
  const color = colorEnum[key]
  return 'block w-[8px] h-[8px] rounded-full ' + color;
}

const initPageData = async () => {
  tableLoading.value = true;
  
  const { total: pageTotal, rows } = await getDailyTable(queryParams.value);
  
  total.value = pageTotal;
  tableData.value = rows.map(item => ({
    ...item,
    currentTemperature: item.currentTemperature ? item.currentTemperature + '°' : '',
    wasteLiquidAmounts: item.wasteLiquidAmounts ? item.wasteLiquidAmounts + 'L' : '',
  }));
  
  tableLoading.value = false;
}

const handleDatePickerChange = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  initPageData();
}

const handleSelectChange = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  initPageData();
}

const handleRadioChange = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  initPageData();
}

// table btn 化验记录
const handleTableBtnClick = async (row) => {
  const { deviceNo, deviceName, worksName, type } = row;
  const currentDate = queryParams.value.assayDate;

  drawerData.value = {
    deviceName, deviceNo, worksName, currentDate, type
  }

  drawerVisible.value = true;
}

// 设备类型变化
const reloadPageData = async (type) => {
  queryParams.value.type = type || '';
  queryParams.value.deviceNo = '';
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  const { data } = await getHomeCounts({type: queryParams.value.type});
  pageCountNums.value = {
    ...data,
    passAssayRates: data.passAssayRates ? Number(data.passAssayRates?.slice(0, -1)) : 0
  };
  initPageData();
}

onMounted( async () => {
  const { data: deviceData } = await getDeviceList({ type: queryParams.value.type });
  selectOptions.value = deviceData;
  
  reloadPageData();
  currentDateTime.value = dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss');
})

</script>

<template>
  <main>
    <div class="lab-day-viewport space-y-[10px]">
      <el-card shadow="never" :body-style="{ border: '0px' }">
        <template #header>
          <p class="space-x-[10px]">
            <span class="font-bold">今日数据概览</span>
            <span class="text-[#999]">统计时间 {{ currentDateTime }}</span>
          </p>
        </template>
        <el-row class="pt-[5px]" justify="space-between" :gutter="20">
          <el-col :span="4">
            <el-statistic :value="pageCountNums.deviceTotals">
              <template #title>
                <p class="flex items-center space-x-[4px]">
                  <el-icon :size="14" color="#2454ff"><Management /></el-icon>
                  <span>全国设备总数（台）</span>
                </p>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="4">
            <el-statistic :value="pageCountNums.onDeviceCounts">
              <template #title>
                <p class="flex items-center space-x-[4px]">
                  <el-icon :size="14" color="#00bd28"><Checked /></el-icon>
                  <span>今日化验中设备（台）</span>
                </p>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="4">
            <el-statistic title="今日待机设备（台）" :value="pageCountNums.standbyDeviceCounts">
              <template #title>
                <p class="flex items-center space-x-[4px]">
                  <el-icon :size="14" color="#e5a528"><List /></el-icon>
                  <span>今日待机设备（台）</span>
                </p>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="4">
            <el-statistic title="今日离线设备（台）" :value="pageCountNums.offDeviceCounts">
              <template #title>
                <p class="flex items-center space-x-[4px]">
                  <el-icon :size="14" color="#e31518"><TrendCharts /></el-icon>
                  <span>今日离线设备（台）</span>
                </p>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="4">
            <el-statistic title="今日质控样合格率" :value="pageCountNums.passAssayRates">
              <template #title>
                <p class="flex items-center space-x-[4px]">
                  <el-icon :size="14" color="#8C40FF"><Histogram /></el-icon>
                  <span>今日质控样合格率</span>
                </p>
              </template>
              <template #suffix>
                <el-popover
                  effect="dark"
                  placement="top-start"
                  :width="200"
                  trigger="hover"
                >
                  <template #reference>
                    <p>
                      <span class="text-[14px]">%</span>
                      <el-icon style="margin-left: 4px" :size="14">
                        <Warning />
                      </el-icon>
                    </p>
                  </template>
                  <ul>
                    <li class="space-x-[4px]">
                      <span class="text-[12px]">今日质控样检测总数</span>
                      <span class="font-bold text-[14px]"> {{ pageCountNums.assayTotals || 0 }} </span>
                      <span class="text-[12px]">次</span>
                    </li>
                    <li class="space-x-[4px]">
                      <span class="text-[12px]">今日质控样合格总数</span>
                      <span class="font-bold text-[14px]"> {{ pageCountNums.passAssayTotals || 0 }} </span>
                      <span class="text-[12px]">次</span>
                    </li>
                  </ul>
                </el-popover>
              </template>
            </el-statistic>
          </el-col>
        </el-row>
      </el-card>
      
      <el-card shadow="never" :body-style="{ padding: '20px' }">
        <div class="flex justify-between items-center mb-[10px]">
          <el-radio-group v-model="queryParams.assayStatus" @change="handleRadioChange">
            <el-radio-button label="全部设备" value="" />
            <el-radio-button label="待机中" value="0" />
            <el-radio-button label="离线中" value="1" />
            <el-radio-button label="化验中" value="2" />
          </el-radio-group>
          <div class="flex space-x-[20px]">
            <el-select
              placeholder="选择设备类型"
              v-model="queryParams.type"
              @change="reloadPageData"
              :empty-values="[null, undefined]"
              :value-on-clear="null"
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              placeholder="选择设备"
              clearable
              filterable
              v-model="queryParams.deviceNo"
              @change="handleSelectChange"
            >
              <el-option
                v-for="item in selectOptions"
                :key="item.deviceNo"
                :label="item.deviceName"
                :value="item.deviceNo"
              />
            </el-select>
            <el-date-picker
              type="date"
              :clearable="false"
              v-model="queryParams.assayDate"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              @change="handleDatePickerChange"
              style="width: 400px;"
            />
          </div>
        </div>
        <el-table :data="tableData" style="width: 100%" v-loading="tableLoading">
          <el-table-column prop="deviceName" label="设备名称" width="180" fixed/>
          <el-table-column prop="deviceNo" label="设备编号" width="180" />
          <el-table-column prop="worksName" label="所属水厂" width="180"/>
          <el-table-column prop="assayStatus" label="当前设备状态" width="180">
            <template #default="{ row }">
              <p class="flex items-center space-x-[8px]">
                <span :class="getDeviceClass(row)"></span>
                <span>{{ deviceNameEnum[row.assayStatus] }}</span>
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="lastAssayTime" label="最近一次化验时间" width="180"/>
          <el-table-column prop="beginAssayTime" label="化验开始时间" width="180"/>
          <el-table-column prop="assayProgress" label="化验进度" width="180">
            <template #default="{ row }">
              <el-progress :percentage="row.assayProgress || 0" />
            </template>
          </el-table-column>
          <el-table-column prop="assayCounts" label="检测轮次" width="180"/>
          <el-table-column prop="assayTotals" label="检测总次数" width="180"/>
          <el-table-column prop="passAssayRates" label="合格率（质控样）" width="180" />
          <el-table-column prop="currentTemperature" label="当前温度" width="180"/>
          <el-table-column prop="currentHumidity" label="当前湿度" width="180"/>
          <el-table-column prop="wasteLiquidAmounts" label="废液产生总量" width="180"/>
          <el-table-column prop="address" label="操作" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="handleTableBtnClick(row)">化验记录</el-button>
            </template>
            
          </el-table-column>
        </el-table>
        <div class="">
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="initPageData"
          />
        </div>
      </el-card>
    </div>
    <RecordDrawer v-model:show="drawerVisible" :data="drawerData"></RecordDrawer>
  </main>
</template>

<style lang="scss">
.lab-day-viewport {
  font-size: 14px;

  .el-statistic__number {
    font-size: 22px;
    font-family: D-DIN-PRO-700-Bold;
  }
}
</style>