<script setup>
import { getDeviceList, getDrawerData } from '@/api/report/lab';
import { dayjs } from 'element-plus';

const { proxy } = getCurrentInstance();
const route = useRoute();

const queryParams = ref({ 
  deviceNo: '',
  pageNum: 1,
  pageSize: 10
 });

const datePieckerValue = ref([dayjs(new Date()).format('YYYY-MM-DD'), dayjs(new Date()).format('YYYY-MM-DD')]);

let firstDeviceNo = '';

const total = ref(0);
const tableData = ref([]);
const loading = ref(false);
const options = ref([]);
const columns = [
  {
    label: '基本资料',
    children: [
      { label: "化验开始时间", prop: 'assayTime', width: 180 },
      // { label: "设备名称", prop: 'deviceName', width: 180 },
      // { label: "设备名称", prop: 'deviceNo', width: 180 },
      { label: "所属水厂", prop: 'worksName', width: 180 },
      // { label: "样品名称", prop: 'assayTypeName', width: 180 }
    ]
  },
  {
    label: '高COD',
    children: [
      { label: "标称值", prop: 'highCodStandardVal', width: 100 },
      { label: "化验值", prop: 'highCodResultConcentration', width: 100 },
      { label: "偏差度", prop: 'highCodDeviationRate', width: 100 }
    ]
  },
  {
    label: '低COD',
    children: [
      { label: "标称值", prop: 'lowCodStandardVal', width: 100 },
      { label: "化验值", prop: 'lowCodResultConcentration', width: 100 },
      { label: "偏差度", prop: 'lowCodDeviationRate', width: 100 }
    ]
  },
  {
    label: '氨氮',
    children: [
      { label: "标称值", prop: 'anDanStandardVal', width: 100 },
      { label: "化验值", prop: 'anDanResultConcentration', width: 100 },
      { label: "偏差度", prop: 'anDanDeviationRate', width: 100 }
    ]
  },
  {
    label: '总氮',
    children: [
      { label: "标称值", prop: 'tnStandardVal', width: 100 },
      { label: "化验值", prop: 'tnResultConcentration', width: 100 },
      { label: "偏差度", prop: 'tnDeviationRate', width: 100 }
    ]
  },
  {
    label: '总磷',
    children: [
      { label: "标称值", prop: 'tpStandardVal', width: 100 },
      { label: "化验值", prop: 'tpResultConcentration', width: 100 },
      { label: "偏差度", prop: 'tpDeviationRate', width: 100 }
    ]
  },
  {
    label: '硝酸盐',
    children: [
      { label: "标称值", prop: 'xsydStandardVal', width: 100 },
      { label: "化验值", prop: 'xsydResultConcentration', width: 100 },
      { label: "偏差度", prop: 'xsydDeviationRate', width: 100 }
    ]
  },
  {
    label: '亚硝酸盐',
    children: [
      { label: "标称值", prop: 'yxsyStandardVal', width: 100 },
      { label: "化验值", prop: 'yxsyResultConcentration', width: 100 },
      { label: "偏差度", prop: 'yxsyDeviationRate', width: 100 }
    ]
  },
  {
    label: '正磷酸盐',
    children: [
      { label: "标称值", prop: 'zlsyStandardVal', width: 100 },
      { label: "化验值", prop: 'zlsyResultConcentration', width: 100 },
      { label: "偏差度", prop: 'zlsyDeviationRate', width: 100 }
    ]
  }
]

const finalyColumns = ref([]);

const initPageData = async () => {

  loading.value = true;

  const [ timeBegin, timeEnd ] = datePieckerValue.value;
  const { total: tableTotal, rows } = await getDrawerData({ ...queryParams.value, timeBegin, timeEnd, type: route.query.t });
  
  const arr = [];

  for (let index = 1; index < columns.length; index++) {
    const children = columns[index].children;
    const tempArr = [];
    for (let i = 1; i < children.length; i++) {
      const item = children[i];
      tempArr.push(item.prop);
    }
    arr.push( tempArr );
  }
  
  const tempColumns = [];

  arr.forEach((item, index) => {
    const [k1] = item;
    
    const isExits = rows.some((val) => val[k1]);
    if ( isExits ) {
      tempColumns.push(columns[index + 1]);
    }
  })

  finalyColumns.value = rows.length ? [columns[0]].concat(tempColumns) : [];

  tableData.value = rows;
  total.value = tableTotal;
  loading.value = false;

}

// 查询
const handleQuery = async() => {
  initPageData();
}

// 重置
const handleReset = () => {
  datePieckerValue.value = [dayjs(new Date()).format('YYYY-MM-DD'), dayjs(new Date()).format('YYYY-MM-DD')];
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  queryParams.value.deviceNo = firstDeviceNo;
  initPageData();
}

// 导出
const handleExport = () => {
  const [ timeBegin, timeEnd ] = datePieckerValue.value;
  
  proxy.getDownload("/business/exportAssayPageListByDeviceNoAndDate", {
    timeBegin, timeEnd, deviceNo: queryParams.value.deviceNo, type: route.query.t
  }, `${new Date().getTime()}.xlsx`);
}

const test = (key, item) => {
  let color = '#606266';
  
  const whitelist = [
    'highCodDeviationRate',
    'lowCodDeviationRate',
    'anDanDeviationRate',
    'tnDeviationRate',
    'tpDeviationRate',
    'xsydDeviationRate',
    'yxsyDeviationRate',
    'zlsyDeviationRate',
  ]

  if ( whitelist.includes(key) ) {
    const n = item[key + 'Number'];
    if ( (n || n == 0) && Math.abs( n ) > 0.1 ) {
      color = 'red'
    }
  }

  return {color};
}

onMounted(async () => {
  await getDeviceList({ type: route.query.t }).then(({ data }) => {
    const [ item ] = data;
    queryParams.value.deviceNo = item?.deviceNo;
    firstDeviceNo = item?.deviceNo;
    options.value = data
  });
  await initPageData();
})
</script>

<template>
  <div class="space-y-[10px]">
    <el-card shadow="never" :body-style="{ border: '0px' }">
      <template #header>
        <p class="space-x-[10px]">
          <span class="font-bold">数据筛选</span>
        </p>
      </template>
      <el-row class="pt-[5px]" justify="space-between" :gutter="20">
        <el-col :span="6">
          <el-form-item label="设备名称">
            <el-select v-model="queryParams.deviceNo" placeholder="请选择" filterable clearable>
              <el-option v-for="item in options" :key="item.deviceNo" :label="item.deviceName" :value="item.deviceNo" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <template #label>
              <span class="font-bold">化验日期</span>
            </template>
            <el-date-picker
              :clearable="false"
              v-model="datePieckerValue"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :editable="false"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
            <el-button @click="handleReset" :loading="loading">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '20px' }">
      <div class="flex justify-between items-center mb-[10px]">
        <h4 class="font-bold">化验记录</h4>
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column :label="col.label" :min-width="col.width" :fixed="col.fixed" align="center" v-for="col in finalyColumns">
          <el-table-column :prop="child.prop" :label="child.label" :min-width="child.width" v-for="child in col.children">
            <template #default="scope">
              <span :style="test(child.prop, scope.row)">{{ scope.row[child.prop] }}</span>
            </template>
          </el-table-column>
        </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>
</template>

<style lang="less" scoped></style>