<template>
  <div class="h-full flex flex-col gap-y-3">
    <n-page-header @back="$router.back">
      <template #title> 数据编辑 </template>
    </n-page-header>
    <div class="flex-1 grid grid-cols-4 gap-x-3">
      <n-card>
        <n-tabs display-directive="show">
          <n-tab-pane name="1" tab="设备">
            <n-list>
              <template #header>
                <div style="display: flex;justify-content: space-between;align-items: center;">
                  <n-checkbox v-model:checked="checked" @update:checked="handleSelectAll">
                  全选
                </n-checkbox>
                <n-button type="primary" @click="renderFun()">渲染</n-button>
                </div>
              </template>
              <n-scrollbar :style="{ maxHeight: `${height - 310}px` }" trigger="none">
                <n-checkbox-group v-model:value="checkValues" @update:value="handleCheckValues">
                  <template v-for="item of classList" :key="item.T_id">
                    <n-list-item class="mr-5">
                      <template #prefix>
                        <n-checkbox :value="item" />
                      </template>
                      <template #suffix>
                        <n-space :wrap="false">
                          <EditClass :task="task" :taskClass="item" :getClassList="getClassList" />
                          <DeleteClass :task="task" :taskClass="item" :getClassList="getClassList" />
                        </n-space>
                      </template>
                      <n-thing>
                        <template #header> {{ item.T_id }} </template>
                        <template #description> {{ item.T_sn }} </template>
                      </n-thing>
                    </n-list-item>
                  </template>
                </n-checkbox-group>
              </n-scrollbar>
              <template #footer>
                <n-gradient-text type="info">
                  传感器总数：{{ classList.length }}
                </n-gradient-text>
              </template>
            </n-list>
          </n-tab-pane>
          <n-tab-pane name="2" tab="表单">
            <FormList :task="task" :class-list="classList" :time="time" :temporal-interval="temporalInterval" />
          </n-tab-pane>
        </n-tabs>
      </n-card>
      <n-card class="h-full col-span-3">
        <div class="h-full flex flex-col gap-y-3">
          <n-space justify="space-between">
            <n-input-group>
              <n-date-picker format="yyyy-MM-dd HH:mm" :time-picker-props="{ format: 'HH:mm' }" @update:formatted-value="(value) => {
                  queryData.Time_start = value[0];
                  queryData.Time_end = value[1];
                }
                " type="datetimerange" clearable />
              <n-button type="primary" @click="getDataList">搜索</n-button>
            </n-input-group>
            <n-space>
              <ExportVue :task="task" :class-list="classList" />
              <ImportVue :task="task" />
              <ImportPlatform :task="task" />
              <AddVue :class-list="classList" :task="task" />
              <SetVue @submit="handleSet" />
              <n-button type="primary" @click="goDataEd">数据编辑</n-button>
            </n-space>
          </n-space>
          <n-tabs type="segment" animated v-model:value="tabChart" @update:value="handleTabChange">
            <n-tab-pane name="温度" tab="温度">
              <!-- <Chart :style="{ minHeight: `${height - 300}px` }" ref="chart1" constructor-type="stockChart"
                :options="chartOptions1"></Chart> -->
                <highchartsT></highchartsT> 
            </n-tab-pane>
            <n-tab-pane name="湿度" tab="湿度">
              <Chart :style="{ minHeight: `${height - 300}px` }" ref="chart2" constructor-type="stockChart"
                :options="chartOptions2"></Chart>
            </n-tab-pane>
          </n-tabs>
        </div>
      </n-card>
    </div>
  </div>
  <n-modal v-model:show="modal.showModal" :title="modal.title" :show-icon="false" preset="dialog">
    <template v-if="modal.title === '温度'">
      <n-form-item show-require-mark>
        <n-input v-model:value="formValue.T_t" />
      </n-form-item>
    </template>
    <template v-else>
      <n-form-item show-require-mark>
        <n-input v-model:value="formValue.T_rh" />
      </n-form-item>
    </template>
    <n-space justify="end">
      <n-popconfirm @positive-click="deleteTask">
        <template #trigger>
          <n-button type="error">删除该点</n-button>
        </template>
        是否确认删除？
      </n-popconfirm>
      <n-button type="primary" @click="editTask">确定</n-button>
      
    </n-space>
  </n-modal>
</template>

<script setup>
import { Chart } from 'highcharts-vue';
import highchartsT from '@/components/highcharts-t.vue'
import {
  deleteTaskData,
  editTaskData,
  getTaskDataClassList,
  getTaskDataList,
} from '@/api';
import AddVue from './AddVue.vue';
import ImportVue from './ImportVue.vue';
import ImportPlatform from './ImportPlatform.vue';
import SetVue from './SetVue.vue';
import ExportVue from './ExportVue.vue';
import FormList from './FormList.vue';
// import ForData from './formData.vue';

import { useWindowSize } from '@vueuse/core';
import { useNow, useDateFormat } from '@vueuse/core';
import EditClass from './EditTaskClass.vue';
import DeleteClass from './DeleteTaskClass.vue';
import { dateFormat } from 'highcharts';
import { TimeData } from '@/plugin/timeFun';


const formatted = useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss');

const notification = useNotification();

const { height } = useWindowSize();

const message = useMessage();

const task = window.sessionStorage.getItem('task')
  ? JSON.parse(window.sessionStorage.getItem('task'))
  : {};

const chart1 = ref(null);
const chart2 = ref(null);

// Modal 数据源
const modal = reactive({
  showModal: false,
  title: '',
});


const renderFun = async ()=>{
  for (let i = 0; i < checkValues.value.length; i++) {
    queryData.T_id = checkValues.value[i].T_id;
    queryData.T_sn = checkValues.value[i].T_sn;
    console.log('循环',queryData)
    await getDataList();
  }
}

// 查询数据
const queryData = reactive({
  T_task_id: task.T_task_id,
  T_sn: '',
  T_id: '',
  // Time_start: '2023-02-06 21:00',
  // Time_end: '2023-02-06 21:10',
  Time_start: '',
  Time_end: '',
  page: 1,
  page_z: 9999,
});
const goDataEd = ()=>{
  
  // window.open(`http://coldverifylocal.coldbaozhida.com/data_edit/?taskId=${queryData.T_task_id}`, '_blank')
  window.open(`http://coldverifylocal.coldbaozhida.com/data_edit/?taskId=${queryData.T_task_id}`, '_blank')

}
// 表单数据
const formValue = reactive({
  T_t: null,
  T_rh: null,
});

// 数据源对象
// const state = reactive({});

// 设备列表
const classList = ref([]);

// 列表
const dataList = ref([]);

//
const dataInfo = ref({});

// 选项组受控模式下的值
const checkValues = ref(null);

// tab
const tabChart = ref('温度');

const handleTabChange = (value) => {
  console.log(value);
  checkValues.value = [];
  checked.value = false;
};

//
const handleSet = (data) => {
  if (tabChart.value === '温度') {
    chart1.value.chart.yAxis[0].addPlotLine({
      color: 'red',
      width: 2,
      value: data.tTop,
      label: {
        text: `上限（${data.tTop}）`,
      },
    });
    chart1.value.chart.yAxis[0].addPlotLine({
      color: 'red',
      width: 2,
      value: data.tBottom,
      label: {
        text: `下限（${data.tBottom}）`,
      },
    });
  } else {
    chart2.value.chart.yAxis[0].addPlotLine({
      color: 'red',
      width: 2,
      value: data.hTop,
      label: {
        text: `上限（${data.hTop}）`,
      },
    });
    chart2.value.chart.yAxis[0].addPlotLine({
      color: 'red',
      width: 2,
      value: data.hBottom,
      label: {
        text: `下限（${data.hBottom}）`,
      },
    });
  }
};

const checked = ref(false);

// 全选
const handleSelectAll = async (value) => {
  if (value) {
    checkValues.value = classList.value.map((item) => item.T_id);
    const arr = classList.value.filter(
      (item) => !selectedValue.value.includes(item.T_id)
    );
    for (let item of arr) {
      queryData.T_id = item.T_id;
      queryData.T_sn = item.T_sn;
      await getDataList();
      if (tabChart.value === '温度') {
        const data1 = dataList.value
          .map((item) => [new Date(item.T_time).getTime(), item.T_t])
          .sort((a, b) => a[0] - b[0]);
        chart1.value.chart.addSeries({
          id: item.T_id,
          name: item.T_id,
          data: data1,
          lineWidth: 1,
          cursor: 'pointer',
          events: {
            click(e) {
              
              modal.title = '温度';
              modal.showModal = true;
              time.value = dateFormat('%Y-%m-%d %H:%M:%S', e.point.x);
              formValue.T_t = e.point.y;
              queryData.T_id = e.point.series.name;
              getDataList();
              dataInfo.value = dataList.value[e.point.index];
            },
          },
        });
      } else {
        const data2 = dataList.value
          .map((item) => [new Date(item.T_time).getTime(), item.T_rh])
          .sort((a, b) => a[0] - b[0]);
        chart2.value.chart.addSeries({
          id: item.T_id,
          name: item.T_id,
          data: data2,
          lineWidth: 1,
          cursor: 'pointer',
          events: {
            click(e) {
              console.log('////',e)
              modal.title = '湿度';
              modal.showModal = true;
              time.value = dateFormat('%Y-%m-%d %H:%M:%S', e.point.x);
              formValue.T_rh = e.point.y;
              queryData.T_id = e.point.series.name;
              getDataList();
              dataInfo.value = dataList.value[e.point.index];
            },
          },
        });
      }
    }
  } else {
    if (tabChart.value === '温度') {
      classList.value.forEach((item) => {
        chart1.value.chart.get(item.T_id).remove();
      });
    } else {
      classList.value.forEach((item) => {
        chart2.value.chart.get(item.T_id).remove();
      });
    }
    checkValues.value = [];
  }
};

const time = ref('');
const selectedValue = ref([]);
// 选项组的值改变时的回调
const handleCheckValues = async (values, meta) => {
  console.log('单选',values, meta)
  return
  selectedValue.value = values;
  const classInfo = classList.value.find((item) => item.T_id === meta.value);
  queryData.T_id = classInfo.T_id;
  queryData.T_sn = classInfo.T_sn;
  await getDataList();
  const data1 = dataList.value
    .map((item) => [new Date(item.T_time).getTime(), item.T_t])
    .sort((a, b) => a[0] - b[0]);
  const data2 = dataList.value
    .map((item) => [new Date(item.T_time).getTime(), item.T_rh])
    .sort((a, b) => a[0] - b[0]);
  if (meta.actionType === 'check') {
    if (tabChart.value === '温度') {
      chart1.value.chart.addSeries({
        id: meta.value,
        name: meta.value,
        data: data1,
        cursor: 'pointer',
        events: {
          click(e) {
            console.log('/=======================///',e,TimeData(e.point.x))
            
            modal.title = '温度';
            modal.showModal = true;
            time.value = TimeData(e.point.x);
            formValue.T_t = e.point.y;
            queryData.T_id = e.point.series.name;
            getDataList();
            dataInfo.value = dataList.value[e.point.index];
          },
        },
      });
    } else {
      chart2.value.chart.addSeries({
        id: meta.value,
        name: meta.value,
        data: data2,
        events: {
          click(e) {
            console.log('点击11119',e)
            modal.title = '湿度';
            modal.showModal = true;
            time.value = dateFormat('%Y-%m-%d %H:%M:%S', e.point.x);
            formValue.T_rh = e.point.y;
            queryData.T_id = e.point.series.name;
            getDataList();
            dataInfo.value = dataList.value[e.point.index];
          },
        },
      });
    }
  } else {
    if (tabChart.value === '温度') {
      chart1.value.chart.get(meta.value).remove();
    } else {
      chart2.value.chart.get(meta.value).remove();
    }
  }
};

const temporalInterval = ref('');

// 图表配置
const chartOptions1 = {
  xAxis: {
    labels: {
      format: '{value:%Y-%m-%d %H:%M:%S}',
    },
  },
  time: {
    useUTC: false
  },
  boost: {
    useGPUTranslations: true
  },

  tooltip: {
    xDateFormat: '%Y-%m-%d %H:%M:%S',
    // headerFormat: '<small class="headerFormat">{.key}:{point.stackTotal}</small><table>',
    // valueDecimals: 0  //会导致提示框内容显示错误
    
  },
  yAxis: {
    labels: {
      format: '{text}℃',
    },
    plotLines: [],
  },

  legend: {
    enabled: true,
  },

  accessibility: {
    enabled: false,
  },

  boost: {
    useGPUTranslations: true,
    seriesThreshold: 5,
  },

  scrollbar: {
    enabled: false,
  },

  // tooltip: {
  //   formatter() {
  //     return `${this.y} ${dateFormat('%Y-%m-%d %H:%M:%S', this.x)}`;
  //   },
  // },

  chart: {
    zooming: {
      singleTouch: true,
      resetButton: {},
      type: 'xy',
    },
    events: {
      selection(event) {
        // console.log(
        //   dateFormat('%Y-%m-%d %H:%M', event.xAxis[0].min),
        //   dateFormat('%Y-%m-%d %H:%M', event.xAxis[0].max)
        // );
        if (event.xAxis) {
          console.log('时间区间选择', event.xAxis)
          temporalInterval.value = [
            dateFormat('%Y-%m-%d %H:%M', event.xAxis[0].min),
            dateFormat('%Y-%m-%d %H:%M', event.xAxis[0].max),
          ];
        }
      },
    },
  },

  series: [],
};
const chartOptions2 = {
  xAxis: {
    labels: {
      format: '{value:%Y-%m-%d %H:%M:%S}',
    },
  },

  yAxis: {
    labels: {
      format: '{text}%',
    },
  },

  legend: {
    enabled: true,
  },

  accessibility: {
    enabled: false,
  },

  boost: {
    useGPUTranslations: true,
    seriesThreshold: 5,
  },

  scrollbar: {
    enabled: false,
  },

  chart: {
    zoomType: 'xy',
  },

  series: [],
};



// 删除
const deleteTask = async () => {
  const { data: res } = await deleteTaskData({
    T_task_id: queryData.T_task_id,
    Id: dataInfo.value.ID,
  });
  if (res.Code === 200) {
    modal.showModal = false;
    message.success(res.Msg);
  }
};

// 编辑
const editTask = async () => {
  console.log('提交',dataInfo,time.value)
  
  const { data: res } = await editTaskData({
    T_task_id: queryData.T_task_id,
    Id: dataInfo.value.ID,
    T_t: formValue.T_t ? formValue.T_t : dataInfo.value.T_t,
    T_rh: formValue.T_rh ? formValue.T_rh : dataInfo.value.T_rh,
    T_time: time.value,
  });
  if (res.Code === 200) {
    modal.showModal = false;
    message.success(res.Msg);
  }
};

// 获取设备列表
const getClassList = async () => {
  const { data: res } = await getTaskDataClassList({
    T_task_id: queryData.T_task_id,
  });
  classList.value = res.Data || [];
};

// 获取任务数据列表
const getDataList = async () => {
  const { data: res } = await getTaskDataList(queryData);
  if (queryData.page_z <= res.Data.Page_size) {
    const arr = classList.value.filter((item) =>
      checkValues.value.includes(item.T_sn)
    );
    arr.forEach((item) => {
      item.T_sn = queryData.T_sn;
      item.T_id = queryData.T_id;
      getDataList();
    });
  }
  dataList.value = res.Data.List || [];
};

getClassList();

onMounted(() => {
  if (task.T_collection_state === 0) {
    notification.info({
      closable: false,
      title: '未完成',
      meta: `当前时间：${formatted.value}`,
      duration: 2500,
      keepAliveOnHover: true,
    });
  } else if (task.T_collection_state === 1) {
    notification.info({
      closable: false,
      title: '已完成',
      meta: `当前时间：${formatted.value}`,
      duration: 2500,
      keepAliveOnHover: true,
    });
  } else if (task.T_collection_state === 2) {
    notification.info({
      closable: false,
      title: '处理中',
      meta: `当前时间：${formatted.value}`,
      duration: 2500,
      keepAliveOnHover: true,
    });
  } else if (task.T_collection_state === 3) {
    notification.info({
      closable: false,
      title: '已采集-无数据',
      meta: `当前时间：${formatted.value}`,
      duration: 2500,
      keepAliveOnHover: true,
    });
  }
});
</script>

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