<template>
  <div class="m-4 mr-0 overflow-hidden bg-white" style="width: 60%; padding: 10px">
    <!-- <a-tabs v-model:activeKey="activeKey" @change="tabChange"  class="m-4 mr-0 overflow-hidden bg-white">
      <a-tab-pane key="tableList" tab="列表方式" style="width:100%"> -->
    <BasicTable @register="registerTable" @edit-end="handleEditEnd" @edit-cancel="handleEditCancel" :beforeEditSubmit="beforeEditSubmit">
      <template #tableTitle>
        <a-button type="primary" @click="handleAddBatch" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-tag v-if="metricObj && metricObj.unit" color="red" style="padding: 5px">单位:{{ metricObj.unit }}</a-tag>
        <a-tag v-if="metricObj && metricObj.des" style="padding: 5px; margin-left: 3px">
          <JEllipsis :value="metricObj.des" :length="40" />
        </a-tag>
        <a-tag style="padding: 5px">低风险:[{{metricObj?.stTolVal}},{{metricObj?.tolVal}}]</a-tag>
        <a-tag style="padding: 5px">中风险:[{{metricObj?.tolVal}},{{metricObj?.warnVal}}]</a-tag>
        <a-tag style="padding: 5px">高风险:[{{metricObj?.warnVal}},{{metricObj?.intvVal}}]</a-tag>
        
      </template>
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)" />
      </template>
      <template #bodyCell="{ column, record }">
        <!-- <template v-if="column.key == 'fillVals' && !record.editable" >
                   {{record.fillVals}}
                </template> -->
        <template v-if="column.key == 'riskLevel'">
          <a-badge color="#A9A9A9" status="default" v-if="!record.riskLevel" text="其他 " />
          <a-badge status="success" v-else-if="record.riskLevel == 1" text="低风险" />
          <a-badge status="processing" v-else-if="record.riskLevel == 2" text="中风险" />
          <a-badge status="error" v-else text="高风险" />
        </template>
      </template>
    </BasicTable>
    <!-- </a-tab-pane> -->
    <!-- <a-tab-pane key="calendarObj" tab="日历方式" force-render>
          <a-calendar v-model:value="value" @panelChange="onPanelChange"  @select="handleDateSelect" :fullscreen="false">
            <template #dateCellRender="{ current: value }">
              <a-badge :number-style="{ backgroundColor: '#52c41a' }" :overflowCount="99999" :count="getDateData(value)?.['fillVals']"> 
                
              </a-badge>
            </template>
          </a-calendar>
        </a-tab-pane>  -->
    <!-- </a-tabs> -->
    <MetricReportModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { defineComponent, ref, onMounted, watch, defineProps } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { queryList, saveOrUpdate, deleteOne, saveAddBatch } from './MetricReport.api';
  import { columns } from './MetricReport.data';
  import { BasicTable, useTable, TableAction, BasicColumn, ActionItem, EditRecordRow } from '/@/components/Table';
  import { cloneDeep } from 'lodash-es';
  import { Moment } from 'moment';
  import MetricReportModal from './components/MetricReportModal.vue';
  import { JEllipsis } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import { message } from 'ant-design-vue';
  const activeKey = ref('tableList');
  const [registerModal, { openModal }] = useModal();
  const { createMessage } = useMessage();
  const dataList = ref([]);
  const props = defineProps({
    data: { require: true, type: Object },
  });
  let metricObj = ref();

  async function setData() {
    currentEditKeyRef.value = '';
    dataList.value = [];
    metricObj.value = props.data;
    if (metricObj.value && metricObj.value.mtrcNo) {
      let list = await queryList({ mtrcNo: metricObj.value.mtrcNo });
      list.forEach((item) => {
        item['unit'] = metricObj.value.unit;
      });
      dataList.value = list;
    }
  }

  watch(
    () => props.data,
    () => setData()
  );

  const currentEditKeyRef = ref('');
  const [registerTable, { reload }] = useTable({
    title: '度量指标列表',
    dataSource: dataList,
    columns: columns,
    showTableSetting: true,
    pagination: true,
    canResize: true,
    scroll: { y: 460 },
    bordered: true,
    actionColumn: {
      width: 100,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
    if (!record.editable) {
      return [
        {
          label: '编辑',
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
          onClick: handleEdit.bind(null, record),
        },
        {
          label: '删除',
          popConfirm: {
            title: '删除后不能恢复，是否删除？',
            confirm: handleDelete.bind(null, record),
          },
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
        },
      ];
    }
    return [
      {
        label: '保存',
        onClick: handleSave.bind(null, record, column),
      },
      {
        label: '取消',
        popConfirm: {
          title: '是否取消编辑',
          confirm: handleCancel.bind(null, record, column),
        },
      },
    ];
  }

  function handleEdit(record: EditRecordRow) {
    currentEditKeyRef.value = record.key;
    record.onEdit?.(true);
  }

  function handleCancel(record: EditRecordRow) {
    currentEditKeyRef.value = '';
    record.onEdit?.(false, false);
  }

  function handleDelete(record: EditRecordRow) {
    currentEditKeyRef.value = '';
    record.onEdit?.(false, false);
    deleteOne({ id: record.id }, handleSuccess);
  }

  function handleSuccess() {
    setData();
  }

  // function handleAdd() {
  //   let currentDate = new Date();
  //   let dateString = currentDate.toISOString().slice(0, 10);
  //   let newRowData = {
  //     fillTime: dateString,
  //     fillVals: '',
  //     mtrcNo: metricObj.value.mtrcNo,
  //   };
  //   saveOrUpdate(newRowData, false, handleSuccess);
  // }

  function handleAddBatch() {
    let newRowData = {
      mtrcNo: metricObj.value.mtrcNo,
      freq: metricObj.value.collFreq * 1,
    };
    saveAddBatch(newRowData, handleSuccess);
  }

  async function handleSave(record: EditRecordRow) {
    const valid = await record.onValid?.();
    if (valid) {
      let data = cloneDeep(record.editValueRefs);
      data['id'] = record.id;
      if (checkIsExist(data)) {
        message.error('当前周期已填，请勿重复填写');
        return false;
      }
      if (!Number.isNaN(data['fillVals'])) {
        //data['riskLevel'] = computeRiskLevel(data['fillVals']);
        data['mtrcNo'] = metricObj.value.mtrcNo;
        let flag = data['id'] ? true : false;
        saveOrUpdate(data, flag, handleSuccess);
        const pass = await record.onEdit?.(false, true);
        if (pass) {
          currentEditKeyRef.value = '';
        }
      }
    }
  }

  const value = ref<Moment>();
  const onPanelChange = (value: Moment, mode: string) => {};

  const handleDateSelect = (value: Moment, mode: string) => {
    const tmp = getDateData(value);
    openModal(true, {
      record: {
        mtrcNo: metricObj.value.mtrcNo,
        mtrcName: metricObj.value.mtrcName,
        fillTime: value.toDate(),
        fillVals: tmp ? tmp.fillVals : '',
        id: tmp ? tmp.id : '',
        mtrcDes: metricObj.value.des,
        unit: metricObj.value.unit,
      },
      isUpdate: !!tmp,
    });
  };

  // function tabChange(key) {
  //   activeKey.value = key;
  // }

  const getDateData = (value: Moment) => {
    let curDate = value.toDate();
    for (let item of dataList.value) {
      if (item.fillTime) {
        let curYear = curDate.getFullYear();
        let curMonth = curDate.getMonth();
        let curDay = curDate.getDate();
        let tDate = new Date(item.fillTime);
        let tYear = tDate.getFullYear();
        let tMonth = tDate.getMonth();
        let tDay = tDate.getDate();
        if (curYear == tYear && curMonth == tMonth && curDay == tDay) {
          return item;
        }
      }
    }
  };

  async function beforeEditSubmit({ record, index, key, value }) {
    if (value || value === 0) {
      record[key] = value;
      record['mtrcNo'] = metricObj.value.mtrcNo;
      // if (key == 'fillVals') {
      //   record['riskLevel'] = computeRiskLevel(value);
      // }
      await saveOrUpdate(record, true, handleSuccess);
    } else {
      return false;
    }
  }

  function handleEditCancel() {
    console.log('cancel');
  }

  function handleEditEnd(record: Recordable) {
    handleSuccess();
  }

  // function computeRiskLevel(fillVal) {
  //   const { stTolVal, tolVal, warnVal, intvVal } = metricObj.value;
  //   let flag = tolVal < warnVal ? true : false;
  //   if (stTolVal !== undefined) {
  //     if (flag) {
  //       if (fillVal < stTolVal) return 0;
  //     } else {
  //       if (fillVal > stTolVal) return 0;
  //     }
  //   }
  //   if (intvVal !== undefined) {
  //     if (flag) {
  //       if (fillVal > intvVal) return 0;
  //     } else {
  //       if (fillVal < intvVal) return 0;
  //     }
  //   }
  //   if (flag) {
  //     if (fillVal <= tolVal) {
  //       return 1;
  //     }
  //     if (fillVal < warnVal) {
  //       return 2;
  //     }
  //     return 3;
  //   } else {
  //     if (fillVal >= tolVal) {
  //       return 1;
  //     }
  //     if (fillVal > warnVal) {
  //       return 2;
  //     }
  //     return 3;
  //   }
  //   return 0;
  // }

  function checkIsExist(data) {
    if (dataList.value.length == 0) {
      return false;
    }
    const fillTime = new Date(data.fillTime)
    let startAndEndDate: { startDate: Date; endDate: Date };
    const freq = metricObj.value.collFreq * 1;
    const curid = data['id'] * 1;
 
    switch (freq) {
      case 1:
        return foundObject(data) ? true : false;
      case 2:
        startAndEndDate = getWeekStartAndEndDate(fillTime);
        return isDateBetween(startAndEndDate.startDate, startAndEndDate.endDate, curid);
      case 3:
        startAndEndDate = getMonthStartAndEndDate(fillTime);
        return isDateBetween(startAndEndDate.startDate, startAndEndDate.endDate, curid);
      case 4:
        startAndEndDate = getQuarterStartAndEndDate(fillTime);
        return isDateBetween(startAndEndDate.startDate, startAndEndDate.endDate, curid);
      case 5:
        startAndEndDate = getHalfYearStartAndEndDate(fillTime);
        return isDateBetween(startAndEndDate.startDate, startAndEndDate.endDate, curid);
      case 6:
        startAndEndDate = getYearStartAndEndDate(fillTime);
        return isDateBetween(startAndEndDate.startDate, startAndEndDate.endDate, curid);
      default:
    }
  }

  function foundObject(target) {
    let exist = dataList.value.find(function (obj) {
      return obj.id * 1 !== target.id * 1 && obj.fillTime === target.fillTime;
    });
    return exist;
  }

  function getWeekStartAndEndDate(inputDate: Date): { startDate: Date; endDate: Date } {
    const firstDayOfWeek = 0;
    const dayOfWeek = inputDate.getDay();
    const timeDiff = dayOfWeek - firstDayOfWeek;
    const weekStartDate = new Date(inputDate);
    weekStartDate.setDate(inputDate.getDate() - timeDiff);
    const weekEndDate = new Date(weekStartDate);
    weekEndDate.setDate(weekStartDate.getDate() + 6);
    return { startDate: weekStartDate, endDate: weekEndDate };
  }

  function getMonthStartAndEndDate(inputDate: Date): { startDate: Date; endDate: Date } {
    const year = inputDate.getFullYear();
    const month = inputDate.getMonth();
    const monthStartDate = new Date(year, month, 1);
    const nextMonthStartDate = new Date(year, month + 1, 1);
    const monthEndDate = new Date(nextMonthStartDate.getTime() - 1);
    return { startDate: monthStartDate, endDate: monthEndDate };
  }
  function getQuarterStartAndEndDate(inputDate: Date): { startDate: Date; endDate: Date } {
    const quarterStartMonth = Math.floor(inputDate.getMonth() / 3) * 3;
    const quarterStartDate = new Date(inputDate.getFullYear(), quarterStartMonth, 1);
    const quarterEndDate = new Date(quarterStartDate.getFullYear(), quarterStartDate.getMonth() + 3, 0);
    return { startDate: quarterStartDate, endDate: quarterEndDate };
  }

  function getHalfYearStartAndEndDate(inputDate: Date): { startDate: Date; endDate: Date } {
    const year = inputDate.getFullYear();
    const month = inputDate.getMonth();
    const isSecondHalf = month >= 6;
    const halfYearStartDate = new Date(year, isSecondHalf ? 6 : 0, 1);
    const nextHalfYearStartDate = new Date(year, isSecondHalf ? 12 : 6, 1);
    const halfYearEndDate = new Date(nextHalfYearStartDate.getTime() - 1);
    return { startDate: halfYearStartDate, endDate: halfYearEndDate };
  }

  function getYearStartAndEndDate(inputDate: Date): { startDate: Date; endDate: Date } {
    const year = inputDate.getFullYear();
    const yearStartDate = new Date(year, 0, 1);
    const yearEndDate = new Date(year, 11, 31);
    return { startDate: yearStartDate, endDate: yearEndDate };
  }

  function isDateBetween(startDate: Date, endDate: Date, id: number): boolean {
    let foundObject = dataList.value.find(function (obj) {
      let tmpDate = new Date(obj.fillTime);
      return obj['id'] * 1 != id && startDate <= tmpDate && endDate >= tmpDate;
    });
    if (foundObject) return true;
    return false;
  }
</script>
