<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" style="display: flex;">
      <n-card style="width: 250px;flex-shrink: 0;">
        <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">
                          <DeleteClass :task="task" :taskClass="item" :getClassList="getClassList" />
                        </n-space>
                      </template>
                      <n-thing>
                        <template #header>
                          <div @dblclick="dblclickFun(item)">{{ item.T_id }} </div>
                        </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 style="flex: 1;">
        <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" />
              <n-button type="primary" @click="renderFun">搜索</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/>
              <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="温度">
              <highchartsT :dataList="dataList"></highchartsT>
            </n-tab-pane>
            <n-tab-pane name="湿度" tab="湿度">
              <highchartsH :dataList="dataList"></highchartsH>
            </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>
  <!-- 编辑 -->
  <n-modal v-model:show="showModal" preset="dialog" positive-text="确认" negative-text="取消" :show-icon="false"
    @positive-click="handleEdit">
    <n-form :model="formDatas" label-width="auto" show-require-mark>
      <n-form-item label="ID" path="T_id">
        <n-input v-model:value="formDatas.T_id" />
      </n-form-item>
      <n-form-item label="SN" path="T_sn">
        <n-input v-model:value="formDatas.T_sn" disabled="false" />
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<script setup>

import { Chart } from 'highcharts-vue';
import highchartsT from '@/components/highcharts-t.vue'
import highchartsH from '@/components/highcharts-h.vue'

import {
  deleteTaskData,
  editTaskData,
  getTaskDataClassList,
  getTaskDataList,
  editTaskDataClass
} 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 DeleteClass from './DeleteTaskClass.vue';
import { dateFormat } from 'highcharts';
import { TimeDate } from '@/plugin/timeFun';
import { useMessage } from "naive-ui";
import { ref,watch} from 'vue';

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'))
  : {};


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

/**
 * --------最新写法开始-----------------------------------------------------------------------------------
 */
// 列表
const dataList = ref([]);



 const formDatas = reactive({
  T_sn: '',
  T_id: '',
});
const showModal = ref(false);
const dblclickFun = (e) => {
  console.log('双击',e)
  formDatas.T_sn = e.T_sn
  formDatas.T_id = e.T_id
  showModal.value = true;
}
const handleEdit = async () => {
  try {
    const { data: res } = await editTaskDataClass({
      T_task_id: queryData.T_task_id,
      T_sn: formDatas.T_sn,
      T_id: formDatas.T_id,
    });
    if (res.Code === 200) {
      message.success(res.Msg);
      getClassList()
    }
  } catch (e) {
    console.log(e);
  }
};


// 表单数据
const formValue = reactive({
  T_t: null,
  T_rh: null,
});
// 查询数据
const queryData = reactive({
  T_task_id: task.T_task_id,
  T_sn: '',
  T_id: '',
  // Time_start: '2023-04-18 07:14:00',
  // Time_end: '2023-04-18 07:25:00',
  // Time_start: '2023-04-06 23:50:00',
  // Time_end: '2023-04-07 00:00:00',
  
  Time_start: '',
  Time_end: '',
  page: 1,
  page_z: 9999,
});
// 获取导航栏设备列表
const getClassList = async () => {
  const { data: res } = await getTaskDataClassList({
    T_task_id: queryData.T_task_id,
  });
  classList.value = res.Data || [];
};
getClassList();

const resData = ref()
//渲染按钮
const renderFun = async () => {
  if(checkValues.value==null){
    message.error("哎呀，请选择设备在查询哟");
    return
  }
  // dataList.value = []
  let arr = []
  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;
    const resIt = await getDataList();
    resData.value = resIt
    arr.push(convertDataFun(resIt.data.Data.List))
  }
  dataList.value = arr
}

const tabValue = ref('温度')

const time = ref('');
const dataInfo = ref({});
// 删除
const deleteTask = async () => {
  const { data: res } = await deleteTaskData({
    T_task_id: queryData.T_task_id,
    Id: dataInfo.value[5],
  });
  if (res.Code === 200) {
    modal.showModal = false;
    message.success(`${res.Msg},点击渲染或搜索更新数据`);
  }
};

// 编辑
const editTask = async () => {
  console.log('88',tabValue.value, dataInfo.value,formValue.T_t,formValue.T_rh)
  // return
  const { data: res } = await editTaskData({
    T_task_id: queryData.T_task_id,
    Id: dataInfo.value[5],
    T_t: tabValue.value == '温度' ? formValue.T_t : dataInfo.value[2],
    T_rh: tabValue.value == '湿度' ? formValue.T_rh : dataInfo.value[2],
    T_time: TimeDate(dataInfo.value[0]),
  });
  if (res.Code === 200) {
    modal.showModal = false;
    message.success(`${res.Msg},点击渲染或搜索更新数据`);
  }
};

//转换图表所需数据
const convertDataFun = (array) => {
  let objData = {
    name: '',
    data: [],
    events: {
      click(e) {
        console.log('点击',e.point.x)
        time.value = e.point.x
        if(tabChart.value == '温度'){
          formValue.T_t = e.point.y
        }else{
          formValue.T_rh = e.point.y
        }
        // formValue.T_t = e.point.y
        modal.showModal = true
        queryData.T_id = e.point.series.name;
        modal.title = tabChart.value == '温度'?'温度':'湿度';
        let serName = e.point.series.name
        const b = dataList.value.find(item => item.name == serName)
        dataInfo.value = b.data[e.point.index];
      }
    }
  }
  if (array != null) {
    let arr = array.reverse()
    objData.name = arr[0].T_sn
    arr.forEach(item => {
      objData.data.push([new Date(item.T_time).getTime(), tabChart.value=='温度'?item.T_t:item.T_rh, tabChart.value=='温度'?item.T_rh:item.T_t, item.T_sn, item.T_id, item.ID])
    });
  } else {
    objData.data = []
  }
  return objData

}
// 获取任务数据列表
const getDataList = () => {
  return new Promise((resolve) => {
    const resIt = getTaskDataList(queryData);
    // console.log('返回',resIt)
    setTimeout(() => {
      resolve(resIt)
    }, 500)
  })
};


const checked = ref(false);

// 全选
const handleSelectAll = async () => {
  checked.value ? checkValues.value = classList.value : checkValues.value = []
};
//单选
const handleCheckValues = () => {
  checkValues.value.length != classList.value.length ? checked.value = false : checked.value = true
}

/**
 * --------最新写法结束-----------------------------------------------------------------------------------
 */


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 state = reactive({});

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




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

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

const handleTabChange = (e) => {
  tabValue.value = e
  // console.log('切换',resData.value,tabValue.value,e)
  renderFun()
 
};




const temporalInterval = ref('');






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>
