<template>
  <div class="h-full flex flex-col gap-y-3">
    <n-page-header @back="$router.back">
      <template #title> 数据编辑 </template>
      <template #extra>
        <n-button type="primary" @click="CompleteFun">完成编辑</n-button>
      </template>
    </n-page-header>
    <div class="flex-1 grid grid-cols-4 gap-x-3" style="display: flex;">
      <n-card style="width: 370px;flex-shrink: 0;">
        <n-tabs display-directive="show">
          <n-tab-pane name="1" tab="设备">
            <n-list>
              <template #header>
                <div style="">
                  <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
                    <n-date-picker format="yyyy-MM-dd HH:mm" v-model:value="pickTimes.picktmSta"
                      :time-picker-props="{ format: 'HH:mm' }" @update:formatted-value="setTimeFuns" @focus="focusFun(1)"
                      @blur="blurFun" type="datetimerange" clearable />
                    <n-button type="primary" @click="renderFun(1)" style="margin-left: 10px;">渲染</n-button>
                  </div>
                  <div style="display: flex;align-items: center;justify-content: space-between;">
                    <n-checkbox v-model:checked="checked" @update:checked="handleSelectAll" style="flex-shrink: 0;">
                      全选
                    </n-checkbox>
                    <div @click="alldeleteFun" style="text-decoration: underline;color: #2d8cf0;cursor: pointer;">批量删除
                    </div>
                  </div>

                </div>
              </template>
              <!-- <n-scrollbar :style="{ maxHeight: `${height - 310}px` }" trigger="none"> -->
              <div :style="{ height: (height - 400) + 'px' }" style="overflow-y: auto">
                <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="delFun" />
                        </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>
              </div>
              <!-- </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" ref="formRef" :class-list="classList" :time="time"
              :temporal-interval="temporalInterval" />
          </n-tab-pane>
          <n-tab-pane name="3" tab="存档">
            <div :style="{ height: (height - 300) + 'px' }">
              <OnFile :task="task"></OnFile>
            </div>
          </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" v-model:value="pickTimes.pickleveTime"
                :time-picker-props="{ format: 'HH:mm' }" @focus="focusFun(2)" @blur="blurFun"
                @update:formatted-value="setTimeFuns" type="datetimerange" clearable />
              <n-button type="primary" @click=" renderFun(2)" style="margin-right: 20px;">渲染</n-button>
              <n-popconfirm @positive-click="handlePositiveClick" :show-icon="false">
                <template #trigger>
                  <n-button type="primary">概况图</n-button>
                </template>
                <div style="padding-top:20px">
                  <n-form :model="stateJpg" label-width="auto" label-placement="left">
                    <n-form-item label="下限" path="value">
                      <n-input v-model:value="stateJpg.TemperatureMin" />
                    </n-form-item>
                    <n-form-item label="上限" path="value">
                      <n-input v-model:value="stateJpg.TemperatureMax" />
                    </n-form-item>
                  </n-form>
                </div>
              </n-popconfirm>
            </n-input-group>
            <n-space>
              <ExportVue :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues" />
              <ImportVue @importFiles="importFile" :task="task" />
              <ImportPlatform :task="task" />
              <AddVue :class-list="classList" @addFuns="addFuns" :task="task" />
              <SetVue />

              <ratioZoom @ratioZoomFun="renderFun(1)" :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime"
                :checkData="checkValues"></ratioZoom>

              <editCopy :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues"
                :classList="classList" />
              <AverageCopy :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues"
                :classList="classList"></AverageCopy>
              <editLeak :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues" />
              <editTendency :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues" />

              <editMath :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues" />
              <editFixation :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues" />
              <skewSection :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues" />


              <editSmooth :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues" />
              <BesselCurve :queryObj="queryData" :pickleveTime="pickTimes.pickleveTime" :checkData="checkValues">
              </BesselCurve>
            </n-space>
          </n-space>
          <n-tabs type="segment" animated v-model:value="tabChart" @update:value="handleTabChange">
            <n-tab-pane name="温度" tab="温度">
              <highchartsT :dataList="dataList" @setTimeFun="setTimeFun"></highchartsT>

            </n-tab-pane>
            <n-tab-pane name="湿度" tab="湿度">
              <highchartsH :dataList="dataList" @setTimeFun="setTimeFun"></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="editTaskFun">确定</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="编号" 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>

  <n-modal v-model:show="showModalChaer" title="概况图" preset="card" style="min-width: 500px;max-width: 600px;min-height: 300px;">
    <n-spin :show="showLoad">
        <template #description>
          加载中，请稍后...
        </template>
        <n-image
          width="500"
          :src="srcUrl"
          style="border: 1px solid #ccc;min-height: 200px;"
        />
      </n-spin>
  </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,
  deleteTaskDataClass,
  TaskDatajpg,
  TaskDatajpgSta,
  editTask
} 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 ratioZoom from './ratioZoom.vue';
import OnFile from './OnFile.vue';


//数据编辑移动的功能
import editCopy from './editCopy.vue';
import AverageCopy from './AverageCopy.vue';


import editLeak from './editLeak.vue';
import editTendency from './editTendency.vue';
import editMath from './editMath.vue';
import editFixation from './editFixation.vue';
import skewSection from './skewSection.vue';


import editSmooth from './editSmooth.vue';
import BesselCurve from './BesselCurve.vue';



import { useWindowSize } from '@vueuse/core';
import { useNow, useDateFormat } from '@vueuse/core';
import DeleteClass from './DeleteTaskClass.vue';
import { dateFormat } from 'highcharts';
import { TimeDate, TimeData } from '@/plugin/timeFun';
import { useMessage, useDialog } from "naive-ui";
import { reactive, ref, watch } from 'vue';
import { useStore } from "vuex"
const store = useStore()

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

const notification = useNotification();

const { height } = useWindowSize();
const formRef = ref(null)
const message = useMessage();
const stateJpg = ref({
  T_task_id: null,
  SN_List: null,
  StartTime: null,
  EndTime: null,
  TemperatureMin: '2',
  TemperatureMax: '8',
})
const showModalChaer = ref(false)
const showLoad = ref(true)
const srcUrl = ref('')



const handlePositiveClick = () => {
  srcUrl.value = ''
  stateJpg.value.T_task_id = queryData.T_task_id
  if (checkValues.value == null) {
    message.error('请选择设备');
    return
  } else if (checkValues.value.length == 0) {
    message.error('请选择设备');
    return
  } else {
    const arr = []
    checkValues.value.forEach(item => {
      arr.push(item.T_sn + ',' + item.T_id)
    })
    stateJpg.value.SN_List = arr.join('|') + '|'
  }
  if (pickTimes.pickleveTime == null) {
    message.error('请选择查询时间');
    return
  } else {
    stateJpg.value.StartTime = TimeData(pickTimes.pickleveTime[0])
    stateJpg.value.EndTime = TimeData(pickTimes.pickleveTime[1])
  }
  TaskDatajpgApi()
}

const TaskDatajpgApi = async () => {
  showModalChaer.value = true
  showLoad.value = true
  const resIt = await TaskDatajpg(stateJpg.value)
  if (resIt.data.Code == 200) TaskDatajpgStaApi()
}
const TaskDatajpgStaApi = async () => {
  const resIt = await TaskDatajpgSta({ T_task_id: stateJpg.value.T_task_id })
  if (resIt.data.Data.state == 1) {
    setTimeout(() => {
      TaskDatajpgStaApi()
    }, 500);
  } else if(resIt.data.Data.state == 2) {
    showLoad.value = false
    srcUrl.value = resIt.data.Data.url
  }else{
    message.error(resIt.data.Data.msg)
    return
  }
}

const importFile = () => {
  checkValues.value = []
  dataList.value = []

  getClassList()
}
const task = window.sessionStorage.getItem('task')
  ? JSON.parse(window.sessionStorage.getItem('task'))
  : {};
//获得焦点的赋值
const blueData = ref(null)
//做时间选择清除
const setTimeFuns = (e) => {
  if (e == null) {
    queryData.Time_start = '';
    queryData.Time_end = '';
  } else {
    queryData.Time_start = e[0];
    queryData.Time_end = e[1];
  }
}

const delFun = () => {
  checkValues.value = []
  dataList.value = []
  getClassList()
}

const addFuns = (e) => {
  console.log('父亲', e)
  getClassList();
}

const blurFun = () => {
  console.log('失去焦点')
  blueData.value = null
}
const focusFun = (e) => {
  console.log('获取焦点', e)
  blueData.value = e
}
// Modal 数据源
const modal = reactive({
  showModal: false,
  title: '',
});

/**
 * --------最新写法开始-----------------------------------------------------------------------------------
 */
// 列表


const dialogs = useDialog();
const alldeleteFun = () => {
  console.log('checkValues.value', checkValues.value)

  // return
  if (!checkValues.value) {
    message.error('请选择至少一项在进行批量操作')
    return
  } else {
    if (checkValues.value.length) {
      dialogs.warning({
        title: '提示',
        content: `批量删除操作，是否继续？`,
        positiveText: '确认',
        negativeText: '取消',
        onPositiveClick: () => {
          alldeleteApi()
        },
        onNegativeClick: () => {
          message.warning('已取消批量删除')
        }
      })
    } else {
      message.error('请选择至少一项在进行批量操作')
      return
    }

  }

}
const alldeleteApi = async () => {
  var num = 0
  for (const key of checkValues.value) {
    const { data: res } = await deleteTaskDataClass({
      T_task_id: queryData.T_task_id,
      T_sn: key.T_sn,
    });
    num += 1
    if (num == checkValues.value.length) {
      getClassList();
      message.success('批量删除完成')
    }
  }

}

const dataList = ref([]);

//完成编辑
const CompleteFun = async ()=>{
  const {data:resIt} = await editTask({
    T_task_id: queryData.T_task_id,
    T_collection_state:4
  })
  if(resIt.Code==200 && resIt.Msg=='ok!'){
    message.success('完成编辑')
  }else{
    message.error('编辑失败')
  }
}

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 {
    checkValues.value = []
    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);
      dataList.value = []
      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: '',
  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();

//两个pick的value

const pickTimes = reactive({
  picktmSta: null,
  pickleveTime: null,
})
//图表框选时间修改
const setTimeFun = (e) => {
  if (blueData.value == 1) {//等于1左边使用时间
    pickTimes.picktmSta = [parseInt(e[0].min), parseInt(e[0].max)]
  } else if (blueData.value == 2) {
    pickTimes.pickleveTime = [parseInt(e[0].min), parseInt(e[0].max)]
  } else {
    queryData.Time_start = ''
    queryData.Time_end = ''
  }
}


const resData = ref()
//渲染按钮
const renderFun = async (j) => {
  if (checkValues.value == null) {
    message.error("哎呀，请选择设备在查询哟");
    return
  }
  console.log('ee', pickTimes.picktmSta, pickTimes.pickleveTime)
  if (j == 1 && pickTimes.picktmSta != null) {
    queryData.Time_start = TimeDate(parseInt(pickTimes.picktmSta[0]))
    queryData.Time_end = TimeDate(parseInt(pickTimes.picktmSta[1]))
  } else if (j == 2 && pickTimes.pickleveTime != null) {
    queryData.Time_start = TimeDate(parseInt(pickTimes.pickleveTime[0]))
    queryData.Time_end = TimeDate(parseInt(pickTimes.pickleveTime[1]))
  } else {
    queryData.Time_start = ''
    queryData.Time_end = ''
  }
  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 editTaskFun = 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) {

        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
        if (store.state.focuDatas == null) {
          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)
        console.log('点击', b, b.data[e.point.index])
        dataInfo.value = b.data[e.point.index];
        console.log('点击', e)
      }
    }
  }
  if (array != null) {
    let arr = array.reverse()
    objData.name = arr[0].T_id
    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>
