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

const { proxy } = getCurrentInstance();

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

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

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

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

const dateBeforeSevenDays = computed(() => new Date(dayjs().subtract(7, 'day').format('YYYY-MM-DD')))

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 time = datePickerValue.value;
  let timeBegin = '';
  let timeEnd = '';
  
  if ( activeRadioName === 'daterange' ) {
    if (time.length) {
      const [ startTime, endTime ] = time;
      timeBegin = dayjs(startTime).format('YYYY-MM-DD')
      timeEnd = dayjs(endTime).format('YYYY-MM-DD')
    }
  } else {
    timeBegin = dayjs(time).startOf('month').format('YYYY-MM-DD');
    timeEnd = dayjs(time).endOf('month').format('YYYY-MM-DD');
  }
 
  return {
    timeBegin,
    timeEnd
  }
}

const formatter = (row, column) => {
    const { title, ratesDeviationNumber }= row;
    const { no } = column;
 
    if (  title === '合格率偏差' && no != 0 && no != columns.value.length - 1 ) {
      const val = row[column.property];
  
      if (!ratesDeviationNumber && ratesDeviationNumber != 0) return '';
  
      return h('span', {
        style: { color: ratesDeviationNumber != 0 ? 'red' : '#606266' },
      }, row[column.property])
    }

    return row[column.property]
}

const initPageData = async() => {
  tableLoading.value = true;
  loading.value = true;

  const dateResult = getStartTimeAndEndTime();
  const { data } = await getContinuousAssayListNew({...dateResult, deviceNo: queryParams.value.deviceNo});

  const whiteTableList = [
    { title: '实际检测数量', key: 'assayCounts' },
    { title: '质控样检测数量', key: 'zkCounts' },
    { title: '质控样合格率(%)', key: 'passedRates' },
    { title: '合格率偏差', key: 'ratesDeviation' },
  ]
  
  let assayTotal = 0;
  let zkTotal = 0;
  
  const middleData = Object.entries(data).map(([key, value]) => {
    assayTotal += value['assayCounts']
    zkTotal += value['zkCounts']
    return {
      label: key,
      prop: key,
      minWidth: 160
    }
  });
  
  const tableResultData = whiteTableList.map(item => {
    const { key } = item;
    
    Object.entries(data).forEach(([k, v]) => {
      let total = '';
      
      if ( key === 'assayCounts' ) total = assayTotal;
      
      if ( key === 'zkCounts' ) total = zkTotal;

      item = {
        total: total === '' ? '' : total,
        ...item,
        ratesDeviationNumber: v['ratesDeviationNumber'],
        [k]: v[key]
      }
    });
    return item;
  })
  console.log(tableResultData)
  if ( middleData.length ) {
    columns.value = [
      { label: '检测指标', width: 200, prop: 'title' },
      ...middleData,
      { label: '合计', width: 200, prop: 'total' }
    ];

    tableData.value = tableResultData;
  } else {
    columns.value = [];
    tableData.value = [];
  }


  // 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 = () => {
  const [ item ] = options.value;
  datePickerValue.value = [dateBeforeSevenDays.value, new Date()];
  queryParams.value.activeRadioName = 'daterange';
  queryParams.value.deviceNo = item?.deviceNo || '';
  initPageData();
}

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

onMounted(async() => {

  datePickerValue.value = [dateBeforeSevenDays.value, new Date()];

  await getDeviceList({ type: 2 }).then(({ data }) => {
    const [ item ] = data;
    queryParams.value.deviceNo = item?.deviceNo || '';
    options.value = data
  });
  
  await 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 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="14">
          <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="daterange" />
                <el-radio-button label="按月" value="month" />
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="datePickerValue"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="请选择月份"
                :type="queryParams.activeRadioName"
                :editable="false"
                :clearable="false"
                style="max-width: 280px;"
                @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"
          :loading="loading"
        >导出</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" v-loading="tableLoading">
        <el-table-column
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          :min-width="col.minWidth || 200"
          :fixed="col.fixed"
          align="center"
          v-for="col, index in columns"
          :formatter="formatter"
        >
          <!-- <template #default="scope">
            {{ scope.row }}
            {{ scope.row[col.prop] }}
          </template> -->
        </el-table-column>
      </el-table>
    </el-card>

  </div>
  
</template>

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