<!-- eslint-disable no-underscore-dangle -->
<script lang="tsx" setup>
import { onMounted, ref, watch } from 'vue';
import type { DataTableColumns, TreeOverrideNodeClickBehavior } from 'naive-ui';
import { NButton, NSpace, NTag, useDialog, useMessage } from 'naive-ui';
import { Add20Regular, ArrowLeft20Filled, Delete16Regular, Settings24Regular, DocumentEdit16Regular, CheckmarkCircle20Regular, DeleteOff24Regular } from '@vicons/fluent';
import { CashOutline as CashIcon } from '@vicons/ionicons5';
import { PublishedWithChangesRound as SuccessIcon2, DeleteOutlineFilled } from '@vicons/material';
import { LoadingOutlined } from '@vicons/antd'
import type { ItablePagination } from '@/views/AlgorithmConfiguration/index';

// api_modifyTaskStatus  api_delTask  api_getTask  api_modifyTask  api_addTask
/** api_modifyTaskStatus 任务状态变更 api_delTask 删除任务 api_getTask 任务分页 api_modifyTask 修改状态 api_addTask 添加任务 */

import {
  api_addTask,
  api_algorithms,
  api_delTask,
  api_findModifyTaskInfo,
  api_getAreaNode,
  api_getCameraList,
  api_getTask,
  api_modifyTask,
  api_modifyTaskStatus,
  api_videosPage
} from '@/api/index';
import type { ITreeNode, IWebCamTable } from './index.ts';
import Draw from './draw.vue';

interface ITableItemInfo {
  [key: string]: any;
};

const cName = ref('');
const val = ref('');
const dialog = useDialog();
const page = ref(1);
const pageSize = ref(10);
const tableData = ref<ITableItemInfo[] | null>([]);
const treeRootId = ref('');
const isMofiyPage = ref(false);
const cameraModal = ref(false);
const show = ref(false);
const analyModal = ref(false);
const message = useMessage();
const treeData = ref<ITreeNode[] | []>([]);
const curTree = ref<null | { number?: number | string; id?: string }>();
const webcams = ref<string[] | number[]>([]);
const webcamData = ref<IWebCamTable[]>([]);
// eslint-disable-next-line no-underscore-dangle
const _curTableItem = ref<ITableItemInfo>({});
const curAnalyInfo = ref({});
const curCameraInfo = ref({});
const isInfoPage = ref(false);
const modifyAnalyModal = ref(false);
// 修改算法ID集合
const analies = ref([]);
const modifyCameraModal = ref(false);
// 修改 - 摄像头ID
const modifcameras = ref([]);
const openTaskModal = ref(false);
const modifyAnalyConfModal = ref(false);

// 滑动块左右
const slider1 = ref(0);
const slider2 = ref(0);
const slider3 = ref(0);

// 新增任务 - 表单
const form = ref({
  status: '',
  taskName: '',
  videoVo: []
});

// 修改任务 - 表单
const modifyForm = ref({
  transcribeTime: '',
  timeInterval: '',
  taskName: '',
  status: '',
  isGrab: false,
  id: '',
  algorithmList: []
});

const total = ref(0);
// 任务表格 - 全部列表
const getTaskList = async () => {
  const param = {
    pageNum: page.value,
    pageSize: pageSize.value,
    taskName: cName.value
  } as ItablePagination;

  show.value = true;

  await api_getTask(param)
    .then(res => {
      if (res.data.code === 200) {
        tableData.value = res.data.data.records;
        total.value = res.data.data.total;
      }
      show.value = false;
    })
    .catch(() => {
      show.value = false;
    });
};

// 任务表格 - 更新状态
const handleUpdateTaskStatus = async (id: string | number, status: string | number, callback?: () => void) => {
  await api_modifyTaskStatus(id, status).then(res => {
    if (res.data.code === 200) {
      !callback && message.success('任务状态变更成功！');
      !callback && getTaskList();
      callback && callback()
    } else {
      message.success(res.data.msg);
    }
  });
};

// 任务表格 - 删除
const delTask = async (id: string) => {
  await api_delTask(id).then(res => {
    if (res.data.code === 200) {
      getTaskList();
      message.success('删除成功！');
    } else {
      message.error(res.data.msg);
    }
  });
};

// 任务表格 - 单所有数据
const findTaskInfo = async (id: string) => {
  await api_findModifyTaskInfo(id).then(res => {
    if (res.data.code === 200) {
      modifyForm.value = {
        ...res.data.data,
        isGrab: res.data.data.isGrab == "0" ? true : false
      };
      slider1.value = 100 - parseInt(res.data.data.transcribeTime.split(",")[0]);
      slider2.value = parseInt(res.data.data.transcribeTime.split(",")[1]);
      slider3.value = parseInt(res.data.data.transcribeTime.split(",")[0]);
      console.log('=============================== 修改表单', modifyForm.value, res.data.data);
    }
  });
};

const tableColumn: DataTableColumns = [
  {
    title: '任务ID',
    key: 'id',
    align: 'center',
    minWidth: 180
  },
  {
    title: '任务名称',
    key: 'taskName',
    align: 'center',
    minWidth: 180
  },
  {
    title: '关联算法',
    align: 'center',
    key: 'relevancyAlgorithm',
    minWidth: 180
  },
  {
    title: '任务启用状态',
    key: 'status',
    minWidth: 180,
    align: 'center',
    render: (row: any) => {
      return <NSpace justify='center'>{row.status === 0 ? <NTag bordered={false} type="success">已启动</NTag> : <NTag bordered={false} type="error">已停用</NTag>}</NSpace>;
    }
  },
  {
    title: '操作',
    minWidth: 220,
    key: 'actions',
    align: 'center',
    render(row: any) {
      console.log('=================', row.status);
      return (
        <NSpace justify='center'>
          <NSpace>
            <n-button
              onClick={() => {
                _curTableItem.value = row;
                isInfoPage.value = true;
                console.log('======================_curTableItem', _curTableItem);
              }}
              quaternary
              type="info"
            >
              详情
            </n-button>

            {/* TSX 状态反转 */}
            {row.status === 0 ? (
              <n-button
                onClick={() => {
                  _curTableItem.value = row;
                  handleUpdateTaskStatus(row.id, 1);
                }}
                quaternary
                type="error"
              >
                停用
              </n-button>
            ) : (
              <n-button
                onClick={() => {
                  _curTableItem.value = row;
                  handleUpdateTaskStatus(row.id, 0);
                }}
                quaternary
                type="info"
              >
                启用
              </n-button>
            )}

            <n-button
              onClick={() => {
                _curTableItem.value = row;
                const d = dialog.warning({
                  title: '确定删除该任务吗?',
                  content: '删除后该数据将无法恢复',
                  positiveText: '确认',
                  negativeText: '取消',
                  onPositiveClick: () => {
                    d.loading = true;
                    return new Promise(resolve => {
                      delTask(row.id).then(resolve);
                    });
                  }
                });
              }}
              quaternary
              type="error"
            >
              删除
            </n-button>
          </NSpace>


        </NSpace>

      );
    }
  }
];

const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
];

const analyData = ref([]);

/** 算法列表 */
const getAlgorithms = async () => {
  // eslint-disable-next-line no-underscore-dangle
  const param = {
    pageNum: page.value,
    pageSize: 10000,
  } as ItablePagination;
  show.value = true;
  return await api_algorithms(param)
    .then(res => {
      if (res.data.code === 200) analyData.value = res.data.data.records;
      show.value = false;
    })
    .catch(() => {
      show.value = false;
    });
};

const selectWebCaM = ref<any>([]);

/** 区域分布 */
const getAreaNode = async () => {
  await api_getAreaNode().then(res => {
    if (res.data.code === 200) {
      treeRootId.value = res.data.data.items[0].id;
      treeData.value = res.data.data.items[0].children;
    }
  });
};

/** 摄像头列 */
const getCamera = () => {
  const params = {
    pageNum: page.value,
    pageSize: pageSize.value,
    resourceNo: curTree.value?.id ? curTree.value?.id : '100001000000000'
  };
  return api_getCameraList(params).then(res => {
    if (res.data.code === 200) {
      webcamData.value = res.data.data.records;
      webcams.value = res.data.data.records.map((item: IWebCamData) => item.id);
    }
  });
};

/** tablle 取值 */
const handleTreeCheck = (rowKeys: any) => {
  selectWebCaM.value = rowKeys;
};

// 树取值
const handleOverrideNode: TreeOverrideNodeClickBehavior = ({ option }) => {
  // 当前
  curTree.value = option as { id: number | string };
  treeRootId.value = option?.id as string;

  page.value = 1;
  pageSize.value = 10;
  getCamera();
  if (option.children) {
    return 'toggleExpand';
  }
  return 'default';
};

// 算法列表项的选择
const handleSelItem = (item: IAnalyItem) => {
  let exist = false;
  form.value.videoVo.forEach((oItem: { id: string }) => {
    if (oItem?.id === item.id) {
      exist = true;
    }
  });

  if (!exist) {
    // 不存在
    form.value.videoVo.push({ ...item, algorithmId: item.id, cameraIds: [] });
  } else {
    // 存在
    // eslint-disable-next-line no-underscore-dangle
    form.value.videoVo = form.value.videoVo.filter(oItem => {
      // eslint-disable-next-line no-underscore-dangle
      let _type = true;
      if (item.id === oItem.id) _type = false;
      return _type;
    });
  }
};

// 添加算法对话框 - 多选算法取值
const handleUpdateAnalyItem = (value: (string | number)[]) => {
  (analies.value as string[]) = value as string[];
  // message.info(JSON.stringify(value));
};

// 修改 - 多选添加
const handleUpdateModifyValue = (value: (string | number)[]) => {
  modifcameras.value = value as string[];
  // message.info(JSON.stringify(value));
};

// 多选类型取值
const handleUpdateValue = (value: (string | number)[]) => {
  webcams.value = value as string[];
  // message.info(JSON.stringify(value));
};

interface IAnalyItem {
  id?: string;
}

// 修改 - 添加摄像头对话框 - tag 联动
const handleModifyCameraClose = (item: IAnalyItem) => {
  console.log(item, analies.value);
  modifcameras.value = modifcameras.value.filter(i => {
    // eslint-disable-next-line no-underscore-dangle
    let _type = true;
    if (i === item.id) _type = false;
    return _type;
  });
};


// 修改 - 添加算法对话框 - tag 移动
const handleModifyAnalyTagClose = (a, i) => {
  // console.log(item, analies.value);


  // // 当前剩余
  // analies.value = analies.value.filter(i => {
  //   // eslint-disable-next-line no-underscore-dangle
  //   let _type = true;
  //   if (i === item.id) _type = false;
  //   return _type;
  // });

  // 循环结构剩余

  let _aId = a.id;
  let _cId = i.id;

  let _curA = modifyForm.value.algorithmList.filter(a => a.id === _aId)[0];


  _curA.cameras = _curA.cameras.filter(c => c.cameraId !== _cId);
  _curA.cameraList = _curA.cameraList.filter(c => c.id !== _cId);
};

// 添加算法对话框 - tag 移动
const handleAnalyTagClose = (item: IAnalyItem) => {
  console.log(item, analies.value);
  analies.value = analies.value.filter(i => {
    // eslint-disable-next-line no-underscore-dangle
    let _type = true;
    if (i === item.id) _type = false;
    return _type;
  });
};

// 穿梭表， 多选 => tag 联动
const handleClose = (item: ITableItemInfo) => {
  console.log(item, webcams.value);
  (webcams.value as number[]) = webcams.value.filter(i => {
    // eslint-disable-next-line no-underscore-dangle
    let _type = true;
    if (i === item.id) _type = false;
    return _type;
  });
};

const nextBtn = ref(false);

/**
 * status 状态 （创建还是创建并启动） taskName 任务名称 videoVo 算法列表 - algorithmId 算法ID - algorithmId 算法名称 - cameraIds 摄像头列表 - cameraId
 * 摄像头ID - coordinate 坐标点位 - isFilter 是否开始报警过滤(0,开启，1，未开启) - threshold 算法阈值(预留)
 */

const handleNextBtn = () => {
  if (form.value.taskName) {
    nextBtn.value = true;
  } else {
    message.error('任务名称必填！');
  }
};

// canvas 组件图片回调
const getCanvasImg = (str: string) => {
  console.log('--------------------- getCanvasImg', str);

  analyConfigForm.value.image = str;

  // for (const a of form.value.videoVo) {
  //   if (a.algorithmId === curAnalyInfo.value.id) {
  //     for (const c of a.cameraIds) {
  //       if (c.cameraId === curCameraInfo.value.id) {
  //         c.image = str;
  //       }
  //     }
  //   }
  // }
};

// 添加任务提交
const handleClickAddTask = async () => {
  await api_addTask(form.value).then(res => {
    if (res.data.code === 200) {
      isMofiyPage.value = false;
      openTaskModal.value = false;
      form.value = {
        status: '',
        taskName: '',
        videoVo: []
      };
      nextBtn.value = false;
      getTaskList();
      message.success('创建成功！');
    } else {
      message.warning(res.data.msg);
      openTaskModal.value = false;
    }
  });
};

// 修改 - 提交
const onSubmitModifyCamera = () => {

  // eslint-disable-next-line no-underscore-dangle

  // 选中的摄像头过滤出来
  const clsit = webcamData.value.filter(allCamera => modifcameras.value.includes(allCamera.id));

  const _id = curAnalyInfo.value.id;

  const curA = modifyForm.value.algorithmList.filter(a => a.id === _id)[0]

  for (let camera of clsit) {
    // 判断是否重复
    let isAdd = false;

    curA.cameras?.filter(c => c?.cameraId === camera?.id).length ? isAdd = false : isAdd = true;

    if (isAdd) {
      // 不重复添加
      curA.cameras.push({
        cameraId: camera.id,
        coordinate: ``,
        image: ``,
        isFilter: 0,
        threshold: ``
      });
      if (!Array.isArray(curA?.cameraList)) curA.cameraList = [];

      curA?.cameraList.push(camera);
    }
  }
  modifyCameraModal.value = false;
};

// 对话框 - 新增摄像头 - 提交
const onSubmitCamera = () => {
  /**
   * 1. curAnalyInfo 当前的算法项ID
   * 2. 找到算法信息 - 将ids添加进去
   * 3. 模块出那些摄像头
   * 4. 数据以那组数据为准
   *
   * webcams 最终留 webcamData 全部
   */
  // eslint-disable-next-line no-underscore-dangle
  const _id = curAnalyInfo.value.id;

  form.value.videoVo.forEach(item => {
    if (item.id === _id) {

      // 拿到当前 - 摄像头
      const formatData = webcamData.value.filter(camera => {
        // eslint-disable-next-line no-underscore-dangle
        let _type = false;

        webcams.value.forEach(id => {
          if (id === camera.id) _type = true;
        });

        Array.isArray(item._cameraAllData) && item._cameraAllData.forEach(oItem => {
          if (oItem.id === camera.id) _type = false;
        })

        return _type;
      });
      console.log("================formatData ", formatData)

      // 摄像头信息遍历 - 重置
      if (!Array.isArray(item._cameraAllData)) item._cameraAllData = [];

      // eslint-disable-next-line no-underscore-dangle
      item._cameraAllData = [...item._cameraAllData, ...formatData];

      let cur = formatData.map(allItem => {
        return {
          cameraId: allItem.id,
          coordinate: ``,
          image: ``,
          isFilter: null,
          threshold: null
        };
      })

      // item.cameraIds = [
      //   ...item.cameraIds,
      //   ...formatData.map(allItem => {
      //     return {
      //       cameraId: allItem.id,
      //       coordinate: ``,
      //       image: ``,
      //       isFilter: null,
      //       threshold: null
      //     };
      //   })
      // ]
      // cur[0] && item.cameraIds.push(cur[0])
      // cur.length && item.cameraIds = .push(cur[0])
      if (cur.length) {
        item.cameraIds = [...item.cameraIds, ...cur]
      }
    }
  });
  cameraModal.value = false;
  console.log("============= 新增对话结束", form.value, webcamData.value, webcams.value);
};

// 新增 - 删除摄像头
const handleCloseCameraItem = (id: string) => {
  const _id = curAnalyInfo.value.id;


  // form.value
  console.log("======================= ", _id, form.value.videoVo)
  form.value.videoVo.forEach(a => {
    if (_id === a.id) {
      // 当前算法项
      a.cameraIds = a.cameraIds.filter(camera => {
        // c
        return camera.cameraId !== id
      })
      a._cameraAllData = a._cameraAllData.filter(camera => {
        // c
        return camera.id !== id
      })
      // a._cameraAllData = []
      console.log("======================= filter camera", a.cameraIds, a._cameraAllData)
    }
  })

}

// 对话框 - 新增摄像头 - 算法配置表单
const analyConfigForm = ref({
  isFilter: '',
  threshold: '',
  coordinate: '',
  image: ``,
  checkedValue: 'g'
});

// 修改 - 算法配置 - 提交
// onSubmitModifyAnalyConf
const onSubmitModifyAnalyConf = () => {
  console.log(curAnalyInfo.value, curCameraInfo.value, form.value);
  const analyID = curAnalyInfo.value.id;
  const cameraID = curCameraInfo.value.id;
  modifyForm.value.algorithmList.forEach(item => {
    if (item.id === analyID) {
      item.cameras.forEach(c => {
        if (c.cameraId === cameraID) {
          console.log('===================================cameraID', c);
          // eslint-disable-next-line no-param-reassign
          // c.coordinate = analyConfigForm.value.coordinate;

          c.coordinate = analyConfigForm.value.coordinate;

          if (analyConfigForm.value.checkedValue === 'g') {
            c.coordinate = ``;
          }

          c.image = analyConfigForm.value.image;
          c.isFilter = analyConfigForm.value.isFilter ? 0 : 1;
          c.threshold = analyConfigForm.value.threshold;
        }
      });
    }
  });
  console.log('================= form', modifyForm.value, analyConfigForm.value);
  modifyAnalyConfModal.value = false;
};

// 对话框 - 算法配置 - 提交
const onSubmit = () => {
  console.log(curAnalyInfo.value, curCameraInfo.value, form.value);
  const analyID = curAnalyInfo.value.id;
  const cameraID = curCameraInfo.value.id;
  form.value.videoVo.forEach(item => {
    if (item.id === analyID) {
      item.cameraIds.forEach(c => {
        if (c.cameraId === cameraID) {
          console.log('===================================cameraID', c);
          // eslint-disable-next-line no-param-reassign
          // c.coordinate = analyConfigForm.value.coordinate;
          c.coordinate = analyConfigForm.value.coordinate;

          if (analyConfigForm.value.checkedValue === 'g') {
            c.coordinate = ``;
          }
          c.image = analyConfigForm.value.image;
          c.isFilter = analyConfigForm.value.isFilter ? 0 : 1;
          c.threshold = analyConfigForm.value.threshold;
        }
      });
    }
  });
  console.log('================= 新增 form', form.value, analyConfigForm.value);
  analyModal.value = false;
};

// 对话框 - 算法配置 - 单选切换
const handleChange = (e: Event) => {
  console.log("单选切换", e.target)
  analyConfigForm.value.checkedValue = (e.target as HTMLInputElement).value;
};

// 表单修改提交
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const modifyTaskInfo = async () => {
  await api_modifyTask().then(res => {
    if (res.data.code === 200) {
      getTaskList();
      message.success('修改成功！');
      isInfoPage.value = false;
    } else {
      message.error(res.data.msg);
    }
  });
};

// 修改任务 - 返回按钮
const handleBack = () => {
  isInfoPage.value = false;
};

// 关闭已存在的算法
const handleCloseAnalyItem = (id: string) => {
  modifyForm.value.algorithmList = modifyForm.value.algorithmList.filter(item => {
    let type = true;
    if (item.id === id) type = false;
    return type;
  });
};

const openAnalyModal = () => {
  // analyData.value = analyData.value.filter(oItem => {
  //   let type = true;
  //   if()
  // })
  modifyAnalyModal.value = true;
};

// 获取字符串坐标信息
const getLocalInfo = (str: string) => {
  console.log(str)
  //   <!-- curAnalyInfo.algorithmName curCameraInfo.cameraName -->
  // console.log(
  //   `curAnalyInfo curCameraInfo =========================`,
  //   form.value.videoVo,
  //   curAnalyInfo.value.id,
  //   curCameraInfo.value.id
  // );

  analyConfigForm.value.coordinate = str;

  // val.value = str;

  // for (const a of form.value.videoVo) {
  //   if (a.algorithmId === curAnalyInfo.value.id) {
  //     for (const c of a.cameraIds) {
  //       if (c.cameraId === curCameraInfo.value.id) {
  //         c.coordinate = str;
  //         console.log('--------------------- coordinate', curCameraInfo.value.id);
  //       }
  //     }
  //   }
  // }
  // console.log('============== 返回坐标', form.value.videoVo);
};


// 新增 - 算法配置对话框
const beforeAnalyModalCallback = (curAnaly, curCamera) => {
  curAnalyInfo.value = curAnaly;
  curCameraInfo.value = curCamera;
  videoAddress.value = curCamera.cameraAddress;


  /**
   *  算法对话框前钩子, 统一中专  _analyForm analyConfigForm
   */

  console.log('算法框前数据 ==========', curAnaly, curCamera, videoAddress.value);

  const _curInfo = curAnaly.cameraIds.filter(cameras => cameras.cameraId === curCamera.id)[0];

  // eslint-disable-next-line no-underscore-dangle
  const _analyForm = {
    // ...analyConfigForm.value,
    // <!-- algorithmName cameraName -->
    algorithmName: curAnaly.algorithmName,
    cameraName: curCamera.cameraName,
    checkedValue: _curInfo?.coordinate ? 'm' : 'g',
    coordinate: _curInfo?.coordinate || ``,
    image: _curInfo?.image || '',
    isFilter: _curInfo?.isFilter === 0 ? true : false,
    threshold: _curInfo?.threshold
  };

  /** cameraId : "7" coordinate : "" image : "" isFilter : null threshold : null */
  console.log("_analyForm ================ ", _analyForm);

  analyConfigForm.value = _analyForm;

  analyModal.value = true;
};

const videoAddress = ref('');
// 修改 - 算法配置对话框
const beforeModifyAnalyModalCallback = (curAnaly, curCamera) => {
  curAnalyInfo.value = curAnaly;
  curCameraInfo.value = curCamera;
  videoAddress.value = curCamera.cameraAddress;
  console.log('=================================== 视频地址', curCamera, curCamera.cameraAddress)
  /**
   *  算法对话框前钩子, 统一中专  _analyForm analyConfigForm
   */

  console.log('算法框前数据 ==========', curAnaly, curCamera);

  const _curInfo = curAnaly.cameras.filter(cameras => cameras.cameraId === curCamera.id)[0];

  // eslint-disable-next-line no-underscore-dangle
  const _analyForm = {
    // ...analyConfigForm.value,
    // <!-- algorithmName cameraName -->
    algorithmName: curAnaly.algorithmName,
    cameraName: curCamera.cameraName,
    checkedValue: _curInfo?.coordinate ? 'm' : 'g',
    coordinate: _curInfo?.coordinate || ``,
    image: _curInfo.image,
    isFilter: _curInfo.isFilter === 0 ? true : false,
    threshold: _curInfo.threshold
  };

  /** cameraId : "7" coordinate : "" image : "" isFilter : null threshold : null */
  console.log("_analyForm ================ ", _analyForm);

  analyConfigForm.value = _analyForm;


  modifyAnalyConfModal.value = true;
};

const count = ref(0)

watch(form, () => {
  //  .reduce((p, item) => p?.cameraIds?.length + item?.cameraIds?.length)

  let i = 0;
  for (let a of form.value.videoVo) {
    if (Array.isArray(a.cameraIds)) i += a.cameraIds.length || 0;
  }
  count.value = i;

}, {
  deep: true
});

const modifyCount = ref(0)

watch(modifyForm, () => {
  //  .reduce((p, item) => p?.cameraIds?.length + item?.cameraIds?.length)

  let i = 0;
  for (let a of modifyForm.value.algorithmList) {
    if (Array.isArray(a.cameras)) i += a.cameras.length || 0;
  }
  modifyCount.value = i;

}, {
  deep: true
});

// algorithmList
const load = ref(false);

const delay = () => {
  setTimeout(() => {
    load.value = true;
  }, 3000)
}

watch(openTaskModal, (o, n) => {
  if (!n) {
    load.value = false;
  }
})

watch(page, () => {
  getTaskList();
});

watch(pageSize, () => {
  getTaskList();
});

watch(_curTableItem, (o, n) => {
  console.log('DATA: _curTableItem =============> FUNCTION: findTaskInfo', o, n);
  findTaskInfo(o.id);
});


// 修改 - 新增算法 - 提交
const onSubmitModifyAnaly = () => {

  // 当前选中算法
  let selAnalyA = analyData.value.filter(analy => analies.value.includes(analy?.id));

  for (let item of selAnalyA) {

    let isAdd = false;

    // 将存在过滤出， 存在索引， 既不需要了
    modifyForm.value.algorithmList.filter(old => old?.id === item.id).length === 0 ? isAdd = true : isAdd = false;

    if (isAdd) {
      // 添加 => modifyForm
      modifyForm.value.algorithmList.push({
        algorithmName: item.algorithmName,
        cameraList: [],
        cameras: [],
        id: item.id,
        version: item.version
      });
    }
  }

  modifyAnalyModal.value = false;
};
const openModifyTaskModal = ref(false);


// 修改 - 启动任务
const onSubmitModifyTask = async () => {
  const modify = async () => {

    // 左侧不能大于间隔时间
    if (slider3.value > (Number(modifyForm.value.timeInterval) || 0)) {
      return message.error("不可以大于间隔时间！")
    }

    let form = {
      ...modifyForm.value,
      isGrab: modifyForm.value.isGrab ? "0" : "1",
      transcribeTime: `${slider3.value},${slider2.value}`,
      videoVo: modifyForm.value.algorithmList
    }

    form.videoVo = form.videoVo.map(item => {
      return {
        algorithmId: item.id,
        algorithmName: item.algorithmName,
        cameraIds: [
          ...item.cameras
        ]
      }
    });


    // 修改
    await api_modifyTask(form).then(res => {
      if (res.data.code === 200) {
        getTaskList();
        isInfoPage.value = false;
        openModifyTaskModal.value = false;
        return message.success("修改成功！")
      };
      return message.error(res.data.msg);
    })
  }
  if (modifyForm.value.status === '0') {
    // 启动
    handleUpdateTaskStatus(_curTableItem.value.id, 1, () => {
      modify()
    });
  } else {
    // 停止
    modify()
  }
  // 格式化 Form
  // algorithmList
  //    modifyForm.value.isGrab
  // slider1.value = res.data.data.timeInterval.split(",")[0]
  //     slider1.value = res.data.data.timeInterval.split(",")[1]

};

// 修改 - 算法配置
const handleModifyAnalyConf = (a, i) => {
  modifyAnalyConfModal.value = true;
  console.log("sdfasfasdfds")
};

// watch(slider1, (o, n) => {
//   slider3.value = 100 - n;
//   console.log("slider", slider1, slider3.value)
// });

onMounted(() => {
  getAlgorithms();
  getAreaNode();
  getTaskList();
});
</script>

<template>
  <div id="videoanalysistask">

    <!-- ===================== 算法配置 - 对话框 -->
    <NModal v-model:show="modifyAnalyConfModal"></NModal>

    <!-- 新增 | 删除 | 修改 都需 -->
    <!-- ============================= 启动任务对话框 | S -->
    <NModal v-model:show="openTaskModal">
      <NCard style="width: 600px" title="启动任务" closable @close="openTaskModal = false">
        <div class="open_task-title">任务就绪检查项</div>
        <div class="open_task-item">
          <div class="dot"></div>
          推理算法
        </div>
        <NRow gutter="12">
          <NCol :span="12">
            <div class="aitem_left">已选择算法</div>
          </NCol>
          <NCol :span="12">
            <div class="aitem_right">
              <span>{{ form.videoVo.length }} 种算法</span>
              <span>
                <NIcon v-if="!load" class="load-animate" color="#1872F0" size="20">
                  <LoadingOutlined />
                </NIcon>

                <NIcon v-else color="#1872F0" size="20">
                  <CheckmarkCircle20Regular />
                </NIcon>
              </span>
            </div>
          </NCol>
        </NRow>
        <div class="open_task-item">
          <div class="dot"></div>
          监控点位
        </div>
        <NRow gutter="12">
          <NCol :span="12">
            <div class="aitem_left">已选择摄像头</div>
          </NCol>
          <NCol :span="12">
            <div class="aitem_right">
              <span> {{ count }} 个摄像头</span>
              <span>
                <NIcon v-if="!load" class="load-animate" color="#1872F0" size="20">
                  <!-- <SuccessIcon2 /> -->
                  <LoadingOutlined />
                </NIcon>

                <NIcon v-else color="#1872F0" size="20">
                  <!-- <SuccessIcon2 /> -->
                  <CheckmarkCircle20Regular />
                </NIcon>
              </span>
            </div>
          </NCol>
        </NRow>
        <div class="open_task-title">任务就绪检查结果</div>
        <div style="height: 80px; display: flex; align-items: center; background: #e8eaeb; margin-bottom: 50px;   c">
          <div
            style="width: 60px; height: 60px; margin: 10px; display: flex; justify-content: center; align-items: center">
            <NIcon v-if="!load" class="load-animate" color="#1872F0" size="50">
              <LoadingOutlined />
            </NIcon>

            <!-- <NIcon  class="load-animate" color="#1872F0" size="50">
                <LoadingOutlined />
              </NIcon> -->

            <NIcon v-else color="#1872F0" size="50">
              <!-- <SuccessIcon2 /> -->
              <CheckmarkCircle20Regular />
            </NIcon>
          </div>
          <div>
            <div>任务就绪</div>
            <div>任务已准备就绪</div>
          </div>
        </div>
        <template #footer>
          <NFlex justify="end">
            <NSpace>
              <NButton @click="openTaskModal = false">取 消</NButton>

              <NButton type="primary" @click="() => {
                load && handleClickAddTask();
              }">立即启动</NButton>
            </NSpace>
          </NFlex>
        </template>
      </NCard>
    </NModal>
    <!-- ============================= 启动任务对话框 | E -->

    <!-- 新增 | 删除 | 修改 都需 -->
    <!-- ============================= 修改 - 启动任务对话框 | S -->
    <NModal v-model:show="openModifyTaskModal">
      <NCard style="width: 600px" title="启动任务" closable @close="openModifyTaskModal = false">
        <div class="open_task-title">任务就绪检查项</div>
        <div class="open_task-item">
          <div class="dot"></div>
          推理算法
        </div>
        <NRow gutter="12">
          <NCol :span="12">
            <div class="aitem_left">已选择算法</div>
          </NCol>
          <NCol :span="12">
            <div class="aitem_right">
              <span>{{ modifyForm.algorithmList.length }} 种算法</span>
              <span>
                <NIcon v-if="!load" class="load-animate" color="#1872F0" size="20">
                  <!-- <SuccessIcon2 /> -->
                  <LoadingOutlined />
                </NIcon>

                <NIcon v-else color="#1872F0" size="20">
                  <!-- <SuccessIcon2 /> -->
                  <CheckmarkCircle20Regular />
                </NIcon>


              </span>
            </div>
          </NCol>
        </NRow>
        <div class="open_task-item">
          <div class="dot"></div>
          监控点位
        </div>
        <NRow gutter="12">
          <NCol :span="12">
            <div class="aitem_left">已选择摄像头</div>
          </NCol>
          <NCol :span="12">
            <div class="aitem_right">
              <span> {{ modifyCount }} 个摄像头</span>
              <span>
                <NIcon v-if="!load" class="load-animate" color="#1872F0" size="20">
                  <!-- <SuccessIcon2 /> -->
                  <LoadingOutlined />
                </NIcon>

                <NIcon v-else color="#1872F0" size="20">
                  <!-- <SuccessIcon2 /> -->
                  <CheckmarkCircle20Regular />
                </NIcon>


              </span>
            </div>
          </NCol>
        </NRow>
        <div class="open_task-title">任务就绪检查结果</div>
        <div style="height: 80px; display: flex; align-items: center; background: #e8eaeb; margin-bottom: 50px;   border-radius: 5px;
  overflow: hidden;">
          <div
            style="width: 60px; height: 60px; margin: 10px; display: flex; justify-content: center; align-items: center">
            <NIcon v-if="!load" class="load-animate" color="#1872F0" size="50">
              <LoadingOutlined />
            </NIcon>

            <!-- <NIcon  class="load-animate" color="#1872F0" size="50">
                <LoadingOutlined />
              </NIcon> -->

            <NIcon v-else color="#1872F0" size="50">
              <!-- <SuccessIcon2 /> -->
              <CheckmarkCircle20Regular />
            </NIcon>
          </div>
          <div>
            <div>任务就绪</div>
            <div>任务已准备就绪</div>
          </div>
        </div>
        <template #footer>
          <NFlex justify="end">
            <NSpace>
              <NButton @click="openModifyTaskModal = false">取 消</NButton>

              <NButton type="primary" @click="() => {
                delay()
                load && onSubmitModifyTask();
              }">立即启动</NButton>
            </NSpace>
          </NFlex>
        </template>
      </NCard>
    </NModal>
    <!-- ============================= 修改 - 启动任务对话框 | E -->

    <!-- 1、重 2、 效 -->
    <!-- ============================= 修改 - 添加算法对话框 | S -->
    <NModal v-model:show="modifyAnalyModal">
      <NCard style="width: 800px" title="添加算法" closable @close="modifyAnalyModal = false">
        <div v-if="analies.length">已选点位 :</div>
        <!--
        + 点位排列
              - analies   算法ID汇总
              - analyData 算法信息汇总
        -->
        <div style="margin-top: 20px">
          <NTag v-for="item in analyData.filter(analy => analies.includes(analy?.id))" :key="item?.id"
            style="margin-bottom: 10px; margin-right: 10px" closable @close="() => {
              handleModifyAnalyTagClose(item);
            }
              ">
            {{ item.algorithmName }}
          </NTag>
        </div>
        <!-- 穿梭表 -->
        <NRow style="margin-top: 20px" gutter="20">
          <NCol :span="18">
            <!-- 全部摄像头的选项框 -->
            <NCard title="全部" size="small">
              <template #header-extra></template>
              <NCheckboxGroup :value="analies" @update:value="handleUpdateAnalyItem">
                <NGrid :y-gap="35" :cols="2">
                  <NGi>
                    <NCheckbox v-for="item in analyData" :key="item?.id" :value="item?.id"
                      :label="`ID ：${item.id} ${item.algorithmName}`" />
                  </NGi>
                </NGrid>
              </NCheckboxGroup>
            </NCard>
          </NCol>
        </NRow>

        <!--  -->
        <template #footer>
          <NFlex justify="end">
            <NSpace>
              <NButton @click="modifyAnalyModal = false">取 消</NButton>
              <NButton type="primary" @click="onSubmitModifyAnaly">确 定</NButton>
            </NSpace>
          </NFlex>
        </template>
      </NCard>
    </NModal>
    <!-- ============================= 修改 - 添加算法对话框 | E -->

    <!--  -->
    <!-- ============================= 修改 - 添加摄像头对话框 | S -->
    <NModal v-model:show="modifyCameraModal">
      <NCard style="width: 800px" title="新增摄像头" closable @close="modifyCameraModal = false">
        <div v-if="webcams.length">已选点位 :</div>
        <!-- 点位排列 -->
        <div style="margin-top: 20px">
          <NTag v-for="item in webcamData.filter(camera => modifcameras.includes(camera.id))" :key="item.id"
            style="margin-bottom: 10px; margin-right: 10px" closable @close="() => {
              handleModifyCameraClose(item);
            }
              ">
            {{ item.cameraName }}
          </NTag>
        </div>
        <!-- 穿梭表 -->
        <NRow style="margin-top: 20px" gutter="20">
          <NCol :span="8">
            <NCard title="分布" size="small">
              <template #header-extra></template>
              <!-- ================= 摄像头区域节点数列表 -->
              <NTree :override-default-node-click-behavior="handleOverrideNode" show-line block-line :data="treeData"
                key-field="id" default-expand-all></NTree>
            </NCard>
          </NCol>
          <!-- 全部 -->
          <NCol :span="16">
            <NCard title="全部" size="small">
              <template #header-extra></template>
              <NCheckboxGroup :value="modifcameras" @update:value="handleUpdateModifyValue">
                <NGrid :y-gap="35" :cols="3">
                  <NGi>
                    <NCheckbox v-for="item in webcamData" :key="item?.id" :value="item?.id" :label="item.cameraName" />
                  </NGi>
                </NGrid>
              </NCheckboxGroup>
            </NCard>
          </NCol>
        </NRow>
        <template #footer>
          <NFlex justify="end">
            <NSpace>
              <NButton @click="modifyCameraModal = false">取 消</NButton>
              <NButton type="primary" @click="onSubmitModifyCamera">确 定</NButton>
            </NSpace>
          </NFlex>
        </template>
      </NCard>
    </NModal>
    <!-- ============================= 修改 - 添加摄像头对话框 | E -->


    <!-- ============================= 新增 - 算法配置对话框 | S -->
    <NModal v-model:show="analyModal">
      <!--
      curAnalyInfo 当前表单项信息
      curCameraInfo 当前摄像头项的信息

      -->
      <NCard style="width: 600px" title="算法配置" closable @close="analyModal = false">
        <div class="analy-modal_title">
          <!-- ============ 标题 -->
          <div>
            <span style="color: #667278; line-height: 30px">算法</span>
            <br />
            <span style="font-size: 20px; font-weight: 500">{{ analyConfigForm.algorithmName }}</span>
          </div>
          <!-- ============ 标题 -->
          <div>
            <span style="color: #667278; line-height: 30px">摄像头</span>
            <br />
            <span style="font-size: 20px; font-weight: 500">{{ analyConfigForm.cameraName }}</span>
          </div>
        </div>
        <!-- 表单 | S -->
        <NForm label-placement="left">
          <NFormItem label="报警过滤" :style="{ ' --n-feedback-height': 0 }">
            <NSwitch :round="false" v-model:value="analyConfigForm.isFilter" />
          </NFormItem>
          <NFormItem label="算法阀值" :style="{ ' --n-feedback-height': 0 }">
            <NInput v-model:value="analyConfigForm.threshold" placeholder="请输入"></NInput>
          </NFormItem>
          <NFormItem label="检测区域" :style="{ ' --n-feedback-height': 0 }">
            <NRadio :checked="analyConfigForm.checkedValue === 'g'" value="g" name="basic-demo" @change="handleChange">
              全图
            </NRadio>
            <NRadio :checked="analyConfigForm.checkedValue === 'm'" value="m" name="basic-demo" @change="handleChange">
              自定义
            </NRadio>
          </NFormItem>
        </NForm>
        <!-- val -->
        <!-- 表单 | E -->
        <Draw v-if="analyConfigForm.checkedValue === 'm'" :image="analyConfigForm.image"
          :val="analyConfigForm.coordinate" :callback="getLocalInfo" :address="videoAddress"
          :img-callback="getCanvasImg"></Draw>
        <template #footer>
          <NFlex justify="end">
            <NSpace>
              <NButton @click="analyModal = false">取 消</NButton>
              <NButton type="primary" @click="onSubmit">确 定</NButton>
            </NSpace>
          </NFlex>
        </template>
      </NCard>
    </NModal>
    <!-- ============================= 新增 - 算法配置对话框 | E -->

    <!-- ============================= 修改 - 算法配置对话框 | S -->
    <NModal v-model:show="modifyAnalyConfModal">
      <!--
      curAnalyInfo 当前表单项信息
      curCameraInfo 当前摄像头项的信息
      -->
      <NCard style="width: 600px" title="算法配置" closable @close="modifyAnalyConfModal = false">
        <div class="analy-modal_title">
          <!-- ============ 标题 -->

          <div>
            <span style="color: #667278; line-height: 30px">算法</span>
            <br />
            <span style="font-size: 20px; font-weight: 500">{{ analyConfigForm.algorithmName }}</span>
          </div>
          <!-- ============ 标题 -->
          <div>
            <span style="color: #667278; line-height: 30px">摄像头</span>
            <br />
            <span style="font-size: 20px; font-weight: 500">{{ analyConfigForm.cameraName }}</span>
          </div>
        </div>
        <!-- 表单 | S -->
        <NForm label-placement="left">
          <NFormItem label="报警过滤" :style="{ ' --n-feedback-height': '0' }">
            <NSwitch :round="false" v-model:value="analyConfigForm.isFilter" />
          </NFormItem>
          <NFormItem label="算法阀值">
            <NInput v-model:value="analyConfigForm.threshold" placeholder="请输入任务名称"></NInput>
          </NFormItem>
          <NFormItem label="检测区域">
            <NRadio :checked="analyConfigForm.checkedValue === 'g'" value="g" name="basic-demo" @change="handleChange">
              全图
            </NRadio>
            <NRadio :checked="analyConfigForm.checkedValue === 'm'" value="m" name="basic-demo" @change="handleChange">
              自定义
            </NRadio>
          </NFormItem>
        </NForm>
        <!-- val -->
        <!-- 表单 | E -->
        <Draw v-if="analyConfigForm.checkedValue === 'm'" :image="analyConfigForm.image"
          :val="analyConfigForm.coordinate" :callback="getLocalInfo" :address="videoAddress"
          :img-callback="getCanvasImg"></Draw>
        <template #footer>
          <NFlex justify="end">
            <NSpace>
              <NButton @click="modifyAnalyConfModal = false">取消</NButton>
              <NButton type="primary" @click="onSubmitModifyAnalyConf">确定</NButton>
            </NSpace>
          </NFlex>
        </template>
      </NCard>
    </NModal>
    <!-- ============================= 修改 - 算法配置对话框 | E -->


    <!-- ============================= 新增模块 | S -->
    <NRow v-if="isMofiyPage" :gutter="20">
      <NCol :span="8">
        <NCard>
          <template #header-extra></template>
          <template #header>
            <n-page-header title="返回" @back="isMofiyPage = false">
              <template #extra>
              </template>
            </n-page-header>
          </template>

          <!-- ============================================================== 算法左侧树 | S -->
          <template #footer>
            <n-steps vertical>
              <n-step title="选择算法">
                <template #default>
                  <span>填写任务名称, 及当前创建任务项下将包含那些算法项</span>
                  <br />
                  已选择
                  <i style="color: #1872f0; font-size: 25px; ">{{ form.videoVo.length }}</i>
                  个
                </template>
              </n-step>

              <n-step title="选择摄像头" description="选择已创建后, 将要设置推送的任务.">
                <template #default>
                  <span>配置任务-算法项后, 将选择配置算法下对应的摄像头列表进行摄像头配置</span>
                  <br />
                  已选择
                  <i style="color: #1872f0;font-size: 25px; ">
                    {{ count || 0 }}
                  </i>
                  个
                </template>
              </n-step>
              <n-step title="创建" description="配置推送任务名称、推送地址的相关信息.">
                <template #default>
                  <span>创建任务或启用任务</span>
                </template>
              </n-step>
            </n-steps>
          </template>
        </NCard>
      </NCol>

      <!-- ============================= 新增任务编辑模块左侧 | S -->
      <NCol v-if="nextBtn" :span="16">
        <NCard title="算法列表" size="small">
          <div v-for="a of form.videoVo" :key="a.id" class="analy-list-wrap">
            <!-- ========================================================= 描述信息 -->
            <div class="analy-list-wrap_left">
              <div class="analy-t">{{ a.algorithmName }}</div>
              <div class="analy-v">
                <span>
                  ID: <i>{{ a.id }}</i>
                  <NDivider vertical />
                  版本 <i>{{ a.version }}</i>
                </span>
              </div>
              <div class="analy-s">
                已选摄像头 :
                <i>{{ a.cameraIds.length }}</i>
              </div>
              <!-- ========================================================= 算法列表 -->
            </div>
            <div class="analy-list-wrap_right">
              <div v-for="i of a._cameraAllData" :key="i.id" class="analy-item" @click="
                curAnalyInfo = a;
              curCameraInfo = i;
              ">
                <!-- 文字描述区 -->
                <div class="analy-item_t">{{ i.cameraName.length > 16 ? `${i.cameraName.slice(0, 14)} ...` :
                  i.cameraName }}
                </div>

                <!-- 摄像头单项， 右侧设置 -->
                <div class="icon-wrap">
                  <NSpace>
                    <NIcon size="15" @click="beforeAnalyModalCallback(a, i)">
                      <Settings24Regular />
                    </NIcon>
                    <NIcon size="17" @click="() => handleCloseCameraItem(i.id)">
                      <Delete16Regular />
                    </NIcon>
                  </NSpace>
                </div>
              </div>

              <!-- 新增摄像头 -->
              <div class="analy-item" @click="_ => {
                curAnalyInfo = a;
                cameraModal = true;
                webcamData = [];

              }
                ">
                <!-- 文字描述区 -->
                <div style="text-align: center !important; width: 100%">
                  <NIcon size="15" style="position: relative; top: 2px">
                    <Add20Regular />
                  </NIcon>
                  新增摄像头
                </div>
                <!-- 摄像头单项， 右侧设置 -->
              </div>
            </div>
          </div>
          <NSpace justify="space-between">
            <NButton strong secondary @click="_ => {
              nextBtn = false;
            }
              ">
              <template #icon>
                <icon-ic:baseline-keyboard-backspace class="text-icon" />
              </template>
              <!-- ic:baseline-keyboard-backspace -->
              上一步
            </NButton>
            <NSpace>
              <NButton strong secondary type="primary" @click="() => {
                form.status = '1';
                handleClickAddTask();
              }
                ">
                <template #icon>
                  <icon-ic:baseline-power-settings-new class="text-icon" />
                </template>
                创建任务
              </NButton>
              <NButton type="primary" @click="() => {
                form.status = '0';
                openTaskModal = true;
                // load.value = true;
                delay()
                // load && handleClickAddTask();
              }
                ">
                <!-- ic:outline-not-started -->
                <template #icon>
                  <icon-ic:baseline-power-settings-new class="text-icon" />
                </template>
                立即启用
              </NButton>
            </NSpace>
          </NSpace>
        </NCard>
      </NCol>
      <!-- ============================= 新增任务编辑模块左侧 | E -->

      <!-- ============================= 新增任务编辑模块右侧 | S -->
      <NCol v-else :span="16">
        <NCard title="任务名称" size="small" style="margin: 0 0 10px 0">
          <NInput v-model:value="form.taskName" placeholder="请输入" clearable></NInput>
        </NCard>

        <NCard title="算法列表" size="small">
          <NRow gutter="12">
            <!-- 算法单项 -->
            <NCol v-for="i of analyData" :key="i.id" span="8">
              <div :class="[form.videoVo.some(item => item.id == i.id) ? 'analysis-item-1' : 'analysis-item-2']"
                @click="handleSelItem(i)">
                <!-- 上 -->
                <div class="analysis-item-top">
                  <span>{{ i.algorithmName }}</span>
                  <div>
                    <div class="sel-icon">
                      <div></div>
                    </div>
                  </div>
                </div>
                <!-- 下 -->
                <div class="analysis-item-bottom">
                  <span>
                    ID : {{ i.id }}
                    <NDivider vertical />
                    版本 {{ i.version }}
                  </span>
                </div>
              </div>
            </NCol>
          </NRow>
          <NButton type="info" @click="handleNextBtn">
            下一步
            <template #icon>
              <icon-ic:baseline-arrow-right-alt class="text-icon" />
            </template>
          </NButton>
        </NCard>
      </NCol>
      <!-- ============================= 新增任务编辑模块右侧 | E -->


      <!-- ============================= 新增摄像头对话框 | S -->
      <NModal v-model:show="cameraModal">
        <NCard style="width: 800px" title="新增摄像头" closable @close="cameraModal = false">
          <div v-if="webcams.length">已选点位 :</div>
          <!-- 点位排列 -->
          <div style="margin-top: 20px">
            <NTag v-for="item in webcamData.filter(cameraData => webcams.includes(cameraData.id))" :key="item.id"
              style="margin-bottom: 10px; margin-right: 10px" closable @close="() => handleClose(item)">
              {{ item.cameraName }}
            </NTag>
          </div>
          <!-- 穿梭表 -->
          <NRow style="margin-top: 20px" gutter="20">
            <NCol :span="8">
              <NCard title="分布" size="small">
                <template #header-extra></template>
                <!-- ================= 摄像头区域节点数列表 -->
                <NTree :override-default-node-click-behavior="handleOverrideNode" show-line block-line :data="treeData"
                  key-field="id" default-expand-all></NTree>
              </NCard>
            </NCol>
            <NCol :span="16">
              <!-- 全部摄像头的选项框 -->
              <NCard title="全部" size="small">
                <template #header-extra></template>
                <NCheckboxGroup :value="webcams" @update:value="handleUpdateValue">
                  <NGrid :y-gap="35" :cols="3">
                    <NGi>
                      <NCheckbox v-for="item in webcamData" :key="item?.id" :value="item?.id"
                        :label="item.cameraName" />
                    </NGi>
                  </NGrid>
                </NCheckboxGroup>
              </NCard>
            </NCol>
          </NRow>
          <template #footer>
            <NFlex justify="end">
              <NSpace>
                <NButton @click="cameraModal = false">取消</NButton>
                <NButton type="primary" @click="onSubmitCamera">确定</NButton>
              </NSpace>
            </NFlex>
          </template>
        </NCard>
      </NModal>
      <!-- ============================= 新增摄像头对话框 | E -->



    </NRow>

    <!-- 修改模块 | E -->
    <div v-else-if="isInfoPage">
      <!-- ======================================================= 详情头部 | S -->
      <!-- <NPageHeader subtitle="" :title="modifyForm.taskName" style="margin: 10px;" @back="handleBack">
        <template #header></template>
        <template #footer>
          <div style="display: flex; justify-content: space-between; padding: 10px 20px">
            <div style="display: flex; align-items: center">
              <NSpace>
                <span>ID : {{ modifyForm.id }}</span>
              </NSpace>
            </div>
            <NButton type="primary" @click="() => {
              delay()
              openModifyTaskModal = true;
            }" secondary>启动任务</NButton>
          </div>
        </template>
      </NPageHeader> -->

      <NCard>
        <template #header>
          <n-page-header :title="modifyForm.taskName" @back="handleBack">
            <template #extra>
              <NButton type="info" @click="() => {
                delay()
                openModifyTaskModal = true;
              }">
                <template #icon>
                  <icon-ic:baseline-power-settings-new class="text-icon" />
                </template>
                启用任务
              </NButton>
            </template>
          </n-page-header>
        </template>
      </NCard>
      <!-- ======================================================= 详情头部 | E -->

      <NCard style="margin-top: 10px" :title="`算法与摄像头配置            `">
        <template #header-extra>
          {{ `ID : ${modifyForm.id}` }}
        </template>
        <!-- ======================================================= 添加算法 -->
        <NButton type="primary" ghost style="margin-bottom: 20px" @click="openAnalyModal"> <template #icon>
            <icon-ic:baseline-plus class="text-icon" />
          </template>添加算法</NButton>
        <!-- ======================================================= 算法列表 | S  -->

        <!-- ============================================================================================ 修改 - 摄像头列表 -->
        <div class="analy-list-wrap" v-for="a of modifyForm.algorithmList" :key="a?.id">
          <!-- 关闭 -->
          <div class="close-icon" @click="() => handleCloseAnalyItem(a?.id)">
            <NIcon size="14" color="#4F5D64">
              <DeleteOff24Regular />
            </NIcon>
          </div>
          <!-- ========================================================= 描述信息 -->
          <div class="analy-list-wrap_left">
            <div class="analy-t">{{ a?.algorithmName }}</div>
            <div class="analy-v">
              <span>
                ID: <i>{{ a.id }}</i>
                <NDivider vertical />
                版本 <i>{{ a.version }}</i>
              </span>
            </div>
            <div class="analy-s">
              已选摄像头 :
              <i style="font-size: 16px; font-weight: 520">{{ a?.cameras.length }}</i>
            </div>

            <!-- ========================================================= 算法列表 -->
          </div>
          <div class="analy-list-wrap_right">
            <!-- @click="() => {
            curAnalyInfo = a;
            curCameraInfo = i;
            console.log(a, i);
            modifyAnalyConfModal = true;
          }
            " -->
            <div v-for="i of a.cameraList" :key="`${i.id}__modify`" class="analy-item">
              <!-- 文字描述区 -->
              <div class="analy-item_t">{{ i.cameraName.length > 16 ? `${i.cameraName.slice(0, 14)} ...` :
                i.cameraName }}
              </div>

              <!-- 摄像头单项， 右侧设置 -->
              <div class="icon-wrap">
                <NSpace>
                  <NIcon size="15">
                    <Settings24Regular @click="beforeModifyAnalyModalCallback(a, i)" />
                  </NIcon>
                  <NIcon size="17" @click="() => handleModifyAnalyTagClose(a, i)">
                    <Delete16Regular />
                  </NIcon>
                </NSpace>
              </div>
            </div>

            <!-- 新增摄像头 -->
            <div class="analy-item" @click="_ => {
              curAnalyInfo = a;
              modifyCameraModal = true;
            }
              ">
              <!-- 文字描述区 -->
              <div style="text-align: center !important; width: 100%">
                <NIcon size="15" style="position: relative; top: 2px">
                  <Add20Regular />
                </NIcon>
                新增摄像头
              </div>
              <!-- 摄像头单项， 右侧设置 -->
            </div>
          </div>
        </div>
        <!-- ======================================================= 算法列表 | E  -->

        <!-- ======================================================= 视频截屏时间段 -->
        <div style="background: #f5f6ff; padding: 0px 10px; margin-top: 5px">
          <NForm label-placement="left">
            <NFormItem required label="启动状态" :style="{
              '--n-feedback-height': '0px'
            }">
              <NSwitch :round="false" size="small" v-model:value="modifyForm.isGrab" />

              <!-- 标题 -->
              <span
                style="margin-left: 30px; color: rgba(148,154,157,0.69);font-size: 13px;line-height: 19px;">启用后，我们将自动为每个视频片段抓取事件发生前后的视频片段；注意，该功能不能代替完整监控回放</span>
            </NFormItem>
            <NFormItem required label="最小间隔" :style="{
              '--n-feedback-height': '0px'
            }">
              <NInput size="small" v-model:value="modifyForm.timeInterval" style="width: 150px" placeholder="最小间隔时间">
              </NInput>
              <span style="margin-left: 5px">s</span>
              <span
                style="margin-left: 30px;color: rgba(148,154,157,0.69);font-size: 13px;line-height: 19px;">当同一摄像头的两次/多次报警事件时间相近时，只会抓取第一个事件的关联视频、并共享给相邻事件</span>
            </NFormItem>
            <NFormItem required label="录制时长" :style="{
              '--n-feedback-height': '0px'
            }">
              <!-- ==================================== 滑动块 | S -->
              <div class="left-slider">
                <NSlider size="small" v-model:value="slider1" :tooltip="false" @update:value="(val) => {
                  slider3 = 100 - val;
                }" />
              </div>
              <!-- logo -->
              <NButton quaternary style="margin: 0px 10px">
                <template #icon>
                  <icon-ic:outline-video-camera-front class="text-icon" />
                </template>
              </NButton>
              <!--  <NSlider /> -->
              <div style="width: 100px">
                <!-- ==================================== 滑动块 | S -->
                <NSlider size="small" v-model:value="slider2" :tooltip="false" />
              </div>
              {{ `- ${slider3} 秒 ~ ${slider2} 秒` }}
            </NFormItem>
          </NForm>
        </div>
      </NCard>
    </div>

    <!-- ============================= 全部任务清单 | S -->
    <div v-else>
      <NSpin :show="show">
        <NCard size="medium">
          <!-- =================== 创建 -->
          <template #header>


            <NSpace justify="space-between">
              <NButton type="primary" ghost @click="() => {
                isMofiyPage = true;
              }
                ">
                <template #icon>
                  <icon-ic:baseline-plus class="text-icon" />
                </template>
                创建视频分析任务
              </NButton>
              <!-- 回放 -->
              <div>
                <!-- 新增摄像头筛选 | S -->
                <NInput style="width: 200px; margin-right: 30px;" v-model:value="cName" placeholder="分析任务名称" clearable>
                </NInput>

                <NButton type="primary" style="margin-right: 30px" @click="() => getTaskList()">
                  <template #icon>
                    <icon-ic:baseline-search class="text-icon" />
                  </template>
                  查询
                </NButton>
                <!-- 新增摄像头筛选 | E -->
              </div>

            </NSpace>

          </template>
          <!-- =================== 创建 -->

          <!-- == Table -->
          <NDataTable striped bottom-bordered :row-key="row => row.id" :columns="tableColumn" :data="tableData"
            :bordered="true" @update:checked-row-keys="handleTreeCheck" />
          <!-- == NPagination -->
          <div style="display: flex; justify-content: end">
            <NPagination :item-count="total" v-model:page="page" v-model:page-size="pageSize" style="margin-top: 20px"
              :display-order="['quick-jumper', 'pages', 'size-picker']" :page-count="100" show-quick-jumper
              show-size-picker :page-sizes="pageSizes" />
          </div>
        </NCard>
      </NSpin>
    </div>
    <!-- ============================= 全部任务清单 | E -->
  </div>
</template>

<style scoped lang="scss">
#videoanalysistask {

  // ============= 滑动块
  .left-slider {
    width: 100px;
  }

  :global(.n-slider .n-slider-rail .n-slider-rail__fill) {
    background-color: transparent !important;
  }

  .dot {
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background-color: #415058;
    margin-right: 20px;
    line-height: 30px;
  }


  .open {
    width: 8px;
    margin: 0 7px 0 10px;
    height: 8px;
    background-color: green;
    border-radius: 50%;
    display: inline-block;
  }

  .close {
    width: 8px;
    margin: 0 7px 0 10px;
    height: 8px;
    background-color: red;
    border-radius: 50%;
    display: inline-block;
  }

  // 算法列 - 单项
  .analy-list-wrap {
    min-height: 80px;
    background-color: #f5f6ff;
    display: flex;
    margin-bottom: 20px;
    position: relative;
    box-shadow: 0 0 10px rgba(0, 0, 0, .05);

    .close-icon {
      position: absolute;
      right: 0;
      top: 0;
      width: 20px;
      height: 20px;
      background: #c6c7cd;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }

    // 算法列 - 单项 - 左侧区域
    .analy-list-wrap_left {
      flex: 0 0 160px;
      padding: 8px 10px;

      & .analy-t {
        font-weight: 550;
        font-size: 13px;
      }

      & .analy-s {
        font-size: 12px;
        margin-top: 5px;
        display: flex;
        align-items: center;

        &>i {
          display: inline-block;
          margin-left: 10px;
          font-size: 13px;
          font-weight: 500;
          color: #497cf0;
        }
      }

      & .analy-v {
        margin-top: 7px;
        font-size: 12px !important;
        line-height: 13px;

        >span>i {
          display: inline-block;
          margin-left: 3px;
        }
      }
    }

    // 算法列 - 单项 - 右侧区域
    .analy-list-wrap_right {
      flex: 1;
      min-height: 80px;
      display: flex;
      justify-content: start;
      align-items: center;
      flex-wrap: wrap;
      padding: 10px 10px;

      .analy-item {
        background: #fff;
        flex: 0 0 200px;
        width: 200px !important;
        display: flex;
        justify-content: space-between;
        margin-right: 10px;
        border-radius: 7px;
        padding-left: 10px;
        cursor: pointer;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
        align-items: center;
        margin-bottom: 20px;

        .analy-item_t {
          font-size: 13px !important;
        }

        .icon-wrap {
          position: relative;
          top: 3px;
          padding-right: 5px;
        }

        >.analy-item_left {
          width: 150px;
        }
      }
    }
  }

  // ===========================
  .active {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  // 算法选中
  .analysis-item-1 {
    cursor: pointer;
    height: 80px;
    background-color: #ebf3fe;
    border-radius: 10px;
    margin-bottom: 30px;
    padding: 10px 12px;
    box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.3);
    border-left: 2px solid #3f8cfe;
    border-right: 2px solid #3f8cfe;

    .analysis-item-top {
      display: flex;
      justify-content: space-between;
      margin-top: 3px;
    }

    .analysis-item-bottom {
      color: #a2a6af;
      font-size: 12px;
      margin-top: 8px;
    }

    .analysis-item-top:nth-child(0) {
      margin-top: 10px;
    }

    .sel-icon {
      width: 15px;
      height: 15px;
      border: 2px solid #192435;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .sel-icon>div {
      background: #3f8cfe;
      border-radius: 50%;
      width: 7px;
      height: 7px;
    }
  }

  // 算法未选
  .analysis-item-2 {
    cursor: pointer;
    height: 80px;
    background-color: #e9e9e9;
    border-radius: 10px;
    margin-bottom: 30px;
    padding: 10px 12px;
    box-shadow: 1px 1px 6px rgba(0, 0, 0, 0.3);

    .analysis-item-top {
      display: flex;
      justify-content: space-between;
      margin-top: 5px;
    }

    .analysis-item-bottom {
      color: #a2a6af;
      font-size: 12px;
      margin-top: 8px;
    }

    .analysis-item-top:nth-child(0) {
      margin-top: 10px;
    }

    .sel-icon {
      width: 15px;
      height: 15px;
      border: 2px solid #192435;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    // .sel-icon > div {
    //   background: #3f8cfe;
    //   border-radius: 50%;
    //   width: 7px;
    //   height: 7px;
    // }
  }
}

@keyframes AIcon {
  100% {
    transform: rotate(360deg)
  }
}

.load-animate {
  transform: rotate(0deg);
  animation: AIcon 0.75s infinite;
}

.open_task-item {
  display: flex;
  justify-content: start;
  align-items: center;
  margin: 10px;
}

.open_task-title {
  font-weight: 550;
  font-size: 15px;
  line-height: 30px;
  margin: 20px 0;
}

.aitem_left {
  text-indent: 35px;
  line-height: 30px;
}

.aitem_right {
  background: #e8eaeb;
  padding: 3px 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10px;
  border-radius: 5px;
  overflow: hidden;
}

.analy-modal_title {
  display: flex;
  height: 80px;
  background: #f8f8f9;

  &>div {
    flex: 1;
    height: 100%;
    text-align: center;
    padding-top: 7px;
  }

  &>div>div {
    display: inline-block;
  }
}
</style>
