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

const { proxy } = getCurrentInstance();

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

const tableLoading = ref(false);
const loading = ref(false);

const datePickerValue = ref(new Date());
const tempDataValue = ref({timeBegin: dayjs(new Date()).startOf('week').format('YYYY') + '年'});

const tableData = ref([]);
const columns = ref([]);
const options = ref([]);

const format = computed(() => {
  return queryParams.value.activeRadioName === 'week' ? tempDataValue.value.timeBegin + ' 第 ww 周'  : 'YYYY-MM'
})

const label = computed(() => {
  return queryParams.value.activeRadioName === 'week' ? '选择周' : '选择月'
})

const onChangeDatePicker = (value) => {
  const timeBegin = dayjs(value).startOf('week').format('YYYY') + '年';
  const timeEnd = dayjs(value).endOf('week').format('MM-DD');
  
  tempDataValue.value = { timeBegin, timeEnd };
}

const onRadioChange = () => {
  datePickerValue.value = new Date();
}

const getStartTimeAndEndTime = () => {
  const { activeRadioName } = queryParams.value;
  const timeBegin = dayjs(datePickerValue.value).startOf(activeRadioName).format('YYYY-MM-DD');
  const timeEnd = dayjs(datePickerValue.value).endOf(activeRadioName).format('YYYY-MM-DD');

  return {
    timeBegin,
    timeEnd
  }
}

const initPageData = async() => {
  tableLoading.value = true;
  loading.value = true;
  const dateResult = getStartTimeAndEndTime();
  const { data } = await getContinuousAssayList({...dateResult, deviceNo: queryParams.value.deviceNo});

  const whiteTableList = [
    // { title: '检测指标', key: 'assayName' },
    { title: '实际检测数量', key: 'assayCounts' },
    { title: '最小值', key: 'minVal' },
    { title: '最大值', key: 'maxVal' },
    { title: '合格率（%）', key: 'passedRates' }, 
    { title: '标线（%）', key: 'bx' },
    { title: '合格率偏差', key: 'ratesDeviation' }
  ]

  const tempBodyObject = {};
  const middleData = Object.entries(data).map(([key, value]) => {
    const children = Object.entries(value).map(([k, v]) => {
      const [child] = v;
      tempBodyObject[key + '-' + k] = child;
      return {
        label: k, 
        prop: key + '-' + k, 
        width: 160
      }
    });
    
    return {
      label: key === 'total' ? '' : key,
      children
    }
  });
  
  if ( middleData.length ) {
    columns.value = [{ label: '检测点位', fixed: "left", children: [{ label: '检测指标', prop: 'title', width: 150 }]}].concat(middleData);
    tableData.value = whiteTableList.map(item => {
      const { key } = item;
      Object.entries(tempBodyObject).map(([k, v]) => {
        item = {
          ...item,
          [k]: v[key]
        }
      })
      return item;
    });
  } else {
    columns.value = [];
    tableData.value = []
  }
  tableLoading.value = false;
  loading.value = false;
}

const handlerQuery = () => {
  initPageData();
}

const handlerReset = () => {
  datePickerValue.value = new Date();
  queryParams.value.activeRadioName = 'week';
  initPageData();
}

const handleExport = () => {
  const dateResult = getStartTimeAndEndTime();
  proxy.getDownload("/business/exportContinuousAssayCountByDates", {
    ...dateResult,
  }, `${new Date().getTime()}.xlsx`);
}

onMounted(async() => {
  getDeviceList().then(({ data }) => {
    // const [ item ] = data;
    // queryParams.value.deviceNo = item?.deviceNo;
    options.value = data
  });
  
  initPageData();
})
</script>

<template>
  
  <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>
        </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>
              <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="12">
          <div class="flex items-center space-x-[20px]">
            <el-form-item label="统计时段">
              <el-radio-group v-model="queryParams.activeRadioName" @change="onRadioChange">
                <el-radio-button label="按周" value="week" />
                <el-radio-button label="按月" value="month" />
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="label">
              <el-date-picker
                v-model="datePickerValue"
                :editable="false"
                :clearable="false"
                :type="queryParams.activeRadioName"
                :format=format
                :placeholder="'请' + label"
                @change="onChangeDatePicker"
              />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="flex justify-end">
            <el-button type="primary" @click="handlerQuery" :loading="loading">查询</el-button>
            <el-button @click="handlerReset" :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="tableLoading">
        <!-- <el-table-column prop="title" label="检测点位" width="160" fixed="left" header-align="center" /> -->
        <el-table-column  :label="col.label" :width="col.width || 200" :fixed="col.fixed" align="center" v-for="col, index in columns">
          <el-table-column :prop="child.prop" :label="child.label" :width="child.width" v-for="child in col.children"/>
        </el-table-column>
        <!-- <el-table-column prop="totalDeviationRate" label="总质控合格率" width="120" header-align="center" fixed="right" align="center"/> -->
      </el-table>
    </el-card>

  </div>
  
</template>

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