<script lang="tsx" setup>
import { onMounted, reactive, ref, watch } from 'vue';
import { NButton, NTag, useNotification, NSpin, NPagination, NDataTable, NCol, NSpace, NRow, useMessage } from 'naive-ui';
import { ArrowLeft20Filled } from '@vicons/fluent';
/** api_algorithms 算法列表 api_modifyAlgorithms 修改算法 */
import { api_algorithms, api_delPushItem, api_findPushItem, api_modifyAlgorithms } from '@/api/index';
import type { ItablePagination } from '@/views/AlgorithmConfiguration/index';
import { api_getKeyOfAnaly, api_getKeyOfVideoSource, api_getKeyTaskInfo, api_addAlarmPush, api_videoTaskKey, api_pushList, api_modifyAlarmPush, api_test } from '@/api/index.ts'
import { ConstructionOutlined } from '@vicons/material';
import { ConsoleSqlOutlined } from '@vicons/antd';
import { EditArrowBack20Filled } from '@vicons/fluent';
import { render } from 'nprogress';

const page = ref(1);
const pageSize = ref(10);

const tableData = ref([]);
const isInfo = ref(false);
const notification = useNotification();
const show = ref(false);
const testModal = ref(false);
const message = useMessage();
// key | 任务 相关
let taskKey = reactive([]);
// key | 算法 相关
let analyKey = reactive([]);

const testMsg = ref([]);

const getTest = async () => {
  return await api_test().then(res => {
    if (res.data.code === 200) {
      getAlgorithms()
      testMsg.value = res.data.data;
      return message.success("测试成功!")
    }
    return message.error(res.data.msg)
  })
}

const total = ref(0);
const getAlgorithms = async () => {
  show.value = true;

  const param: ItablePagination = {
    pageNum: page.value,
    pageSize: pageSize.value
  };

  await api_pushList(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 delPushItem = async (id) => {
  return await api_delPushItem(id).then(res => {
    if (res.data.code === 200) {
      getAlgorithms();
      return message.success("删除成功!")
    }
    return message.error(res.data.msg)
  })
}

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

// 创建
const createModal = ref(false);

const curInfo = ref({});

const tableColumn = [
  {
    title: '推送任务名称',
    key: 'pushName',
    minWidth: 180,
    align: 'center',
  },
  {
    title: '推送地址',
    key: 'pushAddress',
    minWidth: 180,
    align: 'center',
  },
  {
    title: '推送视频分析任务项',
    minWidth: 180,
    align: 'center',
    render: (row: any) => {
      return row.videoTaskVoList.map((item: any) => item.videoTaskName).join(",")
    }
  },
  {
    title: '测试 (模拟发送)',
    key: 'grade',
    align: 'center',
    minWidth: 220,
    render: (row: any) => {
      return <NSpace justify="center">
        <NTag type="error" bordered={false}>离线</NTag>
        <NButton type="primary" quaternary onClick={() => {
          testModal.value = true;
        }}>测试</NButton>
      </NSpace>
    }
  },
  {
    title: '操作',
    minWidth: 220,
    key: 'actions',
    align: 'center',
    render(row: any) {
      return (
        <NSpace justify='center'>
          <NButton
            onClick={() => {
              curInfo.value = row;
              isInfo.value = true;
              isInfoModule.value = true;
              findCurPushInfo();
            }}
            quaternary
            type="info"
          >
            详情
          </NButton>
          <NButton
            onClick={() => {
              curInfo.value = row;
              isInfo.value = true;
              delPushItem(curInfo.value.id);
            }}
            quaternary
            type="error"
          >
            删除
          </NButton>
        </NSpace>
      );
    }
  }
];

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

const handleCheck = (rowKeys: any) => {
  selectWebCaM.value = rowKeys;
};

const generalOptions = [
  {
    id: 0,
    label: '一级'
  },
  {
    id: 1,
    label: '二级'
  },
  {
    id: 2,
    label: '三级'
  },
  {
    id: 3,
    label: '四级'
  },
  {
    id: 4,
    label: '五级'
  }
];

let taskKeys = ref([]);
let sourceKeys = ref([]);
let analyKeys = ref([]);
let selTaskKey = reactive([]);
let selTaskKeys = ref([]);


let form = reactive({
  algorithmList: [],
  cameraList: [],
  pushAddress: '',
  pushName: '',
  resultList: [],
  videoTaskVoList: [],
});

let oldForm = reactive({
  algorithmList: [],
  cameraList: [],
  pushAddress: '',
  pushName: '',
  resultList: [],
  videoTaskVoList: [],
});


// 新增提交
const onSubmit = async () => {
  console.log("====================== form", form)
  let algorithmList = analyKey.filter(item => analyKeys.value.includes(item.contentName)).map(item => {
    return { contentName: item.contentName, contentRemark: item.contentRemark }
  });

  let cameraList = sourceKey.filter(item => sourceKeys.value.includes(item.contentName)).map(item => {
    return { contentName: item.contentName, contentRemark: item.contentRemark }
  });

  let resultList = taskKey.filter(item => taskKeys.value.includes(item.contentName)).map(item => {
    return { contentName: item.contentName, contentRemark: item.contentRemark }
  });

  let videoTaskVoList = selTaskKey.filter(item => selTaskKeys.value.includes(item.id)).map(item => {
    return { videoTaskId: item.id, videoTaskName: item.taskName }
  });

  form.algorithmList = algorithmList;
  form.cameraList = cameraList;
  form.resultList = resultList;
  form.videoTaskVoList = videoTaskVoList;
  // selTaskKeys

  if (!algorithmList.length) {
    return message.error("请勾选算法信息!")
  }

  if (!cameraList.length) {
    return message.error("请勾选视频源信息!")
  }

  if (!resultList.length) {
    return message.error("请勾选分析结果!")
  }

  if (!videoTaskVoList.length) {
    return message.error("请勾选任务列表!")
  }

  if (!form.pushName) {
    return message.error("请填写推送名称!")
  }

  if (!form.pushAddress) {
    return message.error("请填写推送地址!")
  }



  console.log(" ============================ form", form)
  await api_addAlarmPush(form).then(res => {
    if (res.data.code === 200) {
      createModal.value = false;
      form = oldForm;
      console.log("======================== ", res.data.data)
      getAlgorithms();
      return message.success("创建成功!")
    }
    return message.error(res.data.msg)
  });
};

const numModule = ref("0");

const isInfoModule = ref(false);


// 任务列表
const getTaskList = async () => {
  await api_getKeyTaskInfo().then(res => {
    if (res.data.code === 200) {
      console.log("================= res", res.data.data)
      taskKey = res.data.data;
    }
  })
}

// 选择任务 - api_videoTaskKey
const getSelTaskKey = async () => {
  return await api_videoTaskKey().then(res => {
    if (res.data.code === 200) {
      selTaskKey = res.data.data;
    }
  })
};

const handleUpdateSelTaskItem = (value) => {
  selTaskKeys.value = value;
}

// 算法字段
const getAnalyList = async () => {
  await api_getKeyOfAnaly().then(res => {
    if (res.data.code === 200) {
      console.log("================= res", res.data.data)
      analyKey = res.data.data;
    }
  })
}

let sourceKey = reactive([]);
// 视频源信息 & 摄像头信息 & 分析结果
const getVideoSourceKey = async () => {
  await api_getKeyOfVideoSource().then(res => {
    if (res.data.code === 200) {
      sourceKey = res.data.data;
    }
  })
}


const handleUpdateSourceItem = (value) => {
  sourceKeys.value = value;
  // sourceKeys = [...sourceKeys, ...value];
  console.log("================= value", value);
}

const handleUpdateTaskItem = (value) => {
  console.log("================= value", value)
  taskKeys.value = value;
}

const handleUpdateAnalyItem = (value) => {
  console.log("================= value", value)
  analyKeys.value = value;
}

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

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

const cities = ref([]);

// const handleUpdateValue = (value) => {
//   console.log("---------- value ----------", value)
//   cities.value = value;
// }

const findCurPushInfo = async () => {
  return await api_findPushItem(curInfo.value.id).then(res => {
    if (res.data.code === 200) {
      let data = res.data.data;
      // ===================== list
      analyKeys.value = data.algorithmList.map(item => item.contentName);
      sourceKeys.value = data.cameraList.map(item => item.contentName);
      taskKeys.value = data.resultList.map(item => item.contentName);
      selTaskKeys.value = data.videoTaskVoList.map(item => item.videoTaskId);
      // ==================== name

      form.pushName = data.pushName;
      form.pushAddress = data.pushAddress;

      // ==================== ||||
      console.log("================= data ================= =================", analyKeys.value, data, data.algorithmList, sourceKeys.value);
      return message.success(res.data.msg)
    }
    return message.error(res.data.msg)
  })
};

const onSave = async () => {
  let algorithmList = analyKey.filter(item => analyKeys.value.includes(item.contentName)).map(item => {
    return { contentName: item.contentName, contentRemark: item.contentRemark }
  });

  let cameraList = sourceKey.filter(item => sourceKeys.value.includes(item.contentName)).map(item => {
    return { contentName: item.contentName, contentRemark: item.contentRemark }
  });

  let resultList = taskKey.filter(item => taskKeys.value.includes(item.contentName)).map(item => {
    return { contentName: item.contentName, contentRemark: item.contentRemark }
  });

  let videoTaskVoList = selTaskKey.filter(item => selTaskKeys.value.includes(item.id)).map(item => {
    return { videoTaskId: item.id, videoTaskName: item.taskName }
  });

  form.algorithmList = algorithmList;
  form.cameraList = cameraList;
  form.resultList = resultList;
  form.videoTaskVoList = videoTaskVoList;

  form.id = curInfo.value.id;

  if (!algorithmList.length) {
    return message.error("请勾选算法信息!")
  }

  if (!cameraList.length) {
    return message.error("请勾选视频源信息!")
  }

  if (!resultList.length) {
    return message.error("请勾选分析结果!")
  }

  if (!videoTaskVoList.length) {
    return message.error("请勾选任务列表!")
  }

  await api_modifyAlarmPush(form).then(res => {
    if (res.data.code === 200) {
      isInfoModule.value = false;
      getAlgorithms()
      form = oldForm;
      return message.success(res.data.msg)
    }
    return message.error(res.data.msg)
  })
};


const cleanCacheInfo = () => {
  analyKeys.value = [];
  sourceKeys.value = [];
  taskKeys.value = [];
  selTaskKeys.value = [];
  form.pushName = '';
  form.pushAddress = '';
}

const isEditName = ref(false);
const isEditAddress = ref(false);

// 关闭标签
const handleClose = (id: string) => {
  console.log(" ====== id", id, selTaskKeys.value)
  selTaskKeys.value = selTaskKeys.value.filter(item => item !== `${id}`);
}


onMounted(() => {
  getAlgorithms();
  getAnalyList();
  getTaskList();
  getVideoSourceKey();
  getSelTaskKey();

  document.addEventListener("click", () => {
    isEditName.value = false;
    isEditAddress.value = false;
  })
});
</script>

<template>
  <div id="alarmpush">
    <!-- ================================== 视频源 多选框 | E -->
    <NModal v-model:show="testModal">
      <NCard style="width: 600px" title="Callback 模拟发送" closable @close="testModal = false">
        <NForm label-placement="left" label-width="auto" style="margin-left: 20px">
          <NFormItem label="测试结果 : ">
            离线
          </NFormItem>
          <NFormItem label="返回结果 : ">
            <!-- {{ testMsg }} -->
            <n-button size="tiny" secondary strong>
              {{ testMsg }}
            </n-button>
          </NFormItem>
        </NForm>

        <NFlex justify="space-between">
          <NSpace>
            <NButton type="info" strong secondary @click="() => {
              testMsg = '暂未开始测试!';
              getTest();
            }">测试发送</NButton>
            <NButton strong secondary type="tertiary" @click="testMsg = '暂未开始测试!'">重置</NButton>
          </NSpace>
          <NButton type="primary" @click="testModal = false">关闭</NButton>
        </NFlex>
      </NCard>
    </NModal>

    <!-- 对话框 - 创建 -->
    <NModal v-model:show="createModal">
      <NCard title="创建推送任务" style="width: 80%" closable @close="() => {
        createModal = false
      }">
        <NRow :gutter="30">
          <NCol span="3">
            <div style="height: 400px; padding-top: 10px;">
              <n-steps vertical size="small">
                <n-step title="配置内容" description="配置视频源信息、算法信息、分析结果的相关配置信息." />
                <n-step title="选择任务" description="选择已创建后, 将要设置推送的任务." />
                <n-step title="配置地址" description="配置推送任务名称、推送地址的相关信息." />
              </n-steps>
            </div>
          </NCol>

          <NCol span="21">
            <!-- 右侧 -->
            <div v-if="numModule === '0'" style="height: 200px; padding: 0px 10px;">
              <!-- ================ tabs 分支 | S -->

              <n-tabs type="line" animated>
                <n-tab-pane name="source" tab="视频源信息">
                  <n-infinite-scroll style="height: 300px" :distance="10" @load="handleLoad">
                    <!-- ================================== 视频源 多选框 | S -->
                    <NCheckboxGroup v-model:value="sourceKeys" @update:value="handleUpdateSourceItem">
                      <n-space vertical>
                        <NCheckbox v-for="item in sourceKey" :value="item?.contentName"
                          :label="`${item?.contentName} - ${item.contentRemark}`" />
                      </n-space>
                    </NCheckboxGroup>
                    <!-- ================================== 视频源 多选框 | E -->
                  </n-infinite-scroll>
                </n-tab-pane>

                <n-tab-pane name="analy" tab="算法信息">
                  <n-infinite-scroll style="height: 300px" :distance="10" @load="handleLoad">
                    <NCheckboxGroup :value="analyKeys" @update:value="handleUpdateAnalyItem">
                      <n-space vertical>
                        <NCheckbox v-for="item in analyKey" :key="item?.contentName" :value="item?.contentName"
                          :label="`${item?.contentName} - ${item.contentRemark}`" />
                      </n-space>
                    </NCheckboxGroup>
                  </n-infinite-scroll>
                </n-tab-pane>

                <n-tab-pane name="result" tab="分析结果">
                  <n-infinite-scroll style="height: 300px" :distance="10" @load="handleLoad">
                    <NCheckboxGroup :value="taskKeys" @update:value="handleUpdateTaskItem">
                      <n-space vertical>
                        <NCheckbox v-for="item in taskKey" :key="item?.contentName" :value="item?.contentName"
                          :label="`${item?.contentName} - ${item.contentRemark}`" />
                      </n-space>
                    </NCheckboxGroup>
                  </n-infinite-scroll>
                </n-tab-pane>

              </n-tabs>
            </div>

            <div v-if="numModule === '1'">
              <NRow :gutter="20">
                <NCol :span="12">
                  <NCard title="任务列表">
                    <n-infinite-scroll style="height: 300px" :distance="10" @load="handleLoad">
                      <NCheckboxGroup :value="selTaskKeys" @update:value="handleUpdateSelTaskItem">
                        <n-space vertical>
                          <NCheckbox v-for="item in selTaskKey" :key="item?.id" :value="item?.id"
                            :label="item?.taskName" />
                        </n-space>
                      </NCheckboxGroup>
                    </n-infinite-scroll>
                  </NCard>
                </NCol>
                <NCol :span="12">
                  <NCard title="已选择">
                    <n-infinite-scroll style="height: 300px" :distance="10" @load="handleLoad">
                      <NSpace vertical>
                        <!-- ------------------------- 列表 | S -->
                        <n-tag v-for="item in selTaskKey.filter(item => selTaskKeys.includes(item.id))" size="medium"
                          type="info" :bordered="false" closable @close="handleClose(item.id)">
                          {{ item.taskName }}
                        </n-tag>
                        <!-- ------------------------- 列表 | E -->
                      </NSpace>
                    </n-infinite-scroll>
                  </NCard>
                </NCol>
              </NRow>

            </div>
            <!-- ============================================ 选择任务 | S -->

            <!-- ============================================ 选择任务 | E -->

            <!-- 提交表单 -->
            <div v-if="numModule === '2'">
              <NForm label-placement="left" label-width="auto">
                <NFormItem required label="任务名称">
                  <NInput v-model:value="form.pushName" placeholder="请输入任务名称" />
                </NFormItem>

                <NFormItem required label="推送地址">
                  <n-input v-model:value="form.pushAddress" placeholder="请输入任务地址" type="textarea" :autosize="{
                    minRows: 3,
                    maxRows: 5,
                  }" />
                </NFormItem>
              </NForm>
            </div>
          </NCol>
        </NRow>

        <template #footer>
          <!-- =============================================== 新增提交 | S -->
          <NSpace v-if="numModule === '0'" justify="center">
            <NButton @click="createModal = false">取消</NButton>
            <NButton type="primary" @click="numModule = '1'">下一步</NButton>
          </NSpace>

          <NSpace v-if="numModule === '1'" justify="center">
            <NButton @click="numModule = '0'">上一步</NButton>
            <NButton type="primary" @click="numModule = '2'">下一步</NButton>
          </NSpace>

          <NSpace v-if="numModule === '2'" justify="center">
            <NButton @click="numModule = '1'">上一步</NButton>
            <NButton type="primary" @click="onSubmit">确定创建</NButton>
          </NSpace>
          <!-- =============================================== 新增提交 | E -->
        </template>
      </NCard>
    </NModal>

    <!-- 推送任务列表 -->

    <!-- ===================================== 数据展示 | S -->
    <div v-if="!isInfoModule">
      <NSpin :show="show">
        <NCard size="medium">
          <template #header>
            <NButton type="primary" ghost @click="() => {
              numModule = '0';
              form = oldForm;
              createModal = true;
              cleanCacheInfo();
            }">
              <template #icon>
                <icon-ic:baseline-plus class="text-icon" />
              </template>
              新增推送任务
            </NButton>
          </template>
          <NDataTable :row-key="row => row.id" :columns="tableColumn" :data="tableData" :bordered="false"
            @update:checked-row-keys="handleCheck" />

          <!-- =============================================== 分页器 | S  -->
          <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>
          <!-- =============================================== 分页器 | E  -->
        </NCard>
      </NSpin>
    </div>

    <!-- ===================================== 数据展示 | S -->
    <div v-else>
      <NCard :bordered="false" style="margin: 10px">
        <template #header>
          <n-page-header @back="isInfoModule = false">
            <!-- 标题 -->
            <template #title>
              <NSpace align="center">
                <span v-if="!isEditName">{{ form.pushName }} </span>
                <NInput @click.stop="() => { }" v-else size="small" v-model:value="form.pushName" clearable />
                <NButton text @click.stop="isEditName = !isEditName">
                  <n-icon color="#646cff" size="17">
                    <EditArrowBack20Filled />
                  </n-icon>
                </NButton>
              </NSpace>
            </template>
            <!-- 地址 -->
            <NSpace align="center">
              <span v-if="!isEditAddress">{{ form.pushAddress }} </span>
              <NInput v-else @click.stop="() => { }" size="small" v-model:value="form.pushAddress" clearable />
              <NButton text @click.stop="isEditAddress = !isEditAddress">
                <n-icon color="#646cff" size="17">
                  <EditArrowBack20Filled />
                </n-icon>
              </NButton>
            </NSpace>
            <template #extra>
              <NButton strong secondary type="info" @click="onSave">保存配置</NButton>
            </template>
          </n-page-header>
        </template>
      </NCard>

      <NRow :gutter="5" style="margin: 10px">
        <NCol :span="12">
          <NCard :bordered="false" title="配置内容">
            <n-infinite-scroll style="height: 400px" :distance="10" @load="handleLoad">
              <n-tabs type="segment" animated>
                <n-tab-pane name="oasis" tab="视频源信息">
                  <!-- ================================== 视频源 多选框 | S -->
                  <NCheckboxGroup v-model:value="sourceKeys" @update:value="handleUpdateSourceItem">
                    <n-space vertical>
                      <NCheckbox v-for="item in sourceKey" :value="item?.contentName"
                        :label="`${item?.contentName} - ${item.contentRemark}`" />
                    </n-space>
                  </NCheckboxGroup>
                  <!-- ================================== 视频源 多选框 | E -->
                </n-tab-pane>
                <n-tab-pane name="the beatles" tab="算法信息">
                  <NCheckboxGroup :value="analyKeys" @update:value="handleUpdateAnalyItem">
                    <n-space vertical>
                      <NCheckbox v-for="item in analyKey" :key="item?.field_name" :value="item?.contentName"
                        :label="`${item?.contentName} - ${item.contentRemark}`" />
                    </n-space>
                  </NCheckboxGroup>
                </n-tab-pane>
                <n-tab-pane name="jay chou" tab="分析结果">
                  <NCheckboxGroup :value="taskKeys" @update:value="handleUpdateTaskItem">
                    <n-space vertical>
                      <NCheckbox v-for="item in taskKey" :key="item?.field_name" :value="item?.contentName"
                        :label="`${item?.contentName} - ${item.contentRemark}`" />
                    </n-space>
                  </NCheckboxGroup>
                </n-tab-pane>
              </n-tabs>
            </n-infinite-scroll>
          </NCard>
        </NCol>
        <NCol :span="12">
          <n-split direction="horizontal">
            <template #1>
              <div style="margin: 0 10px">
                <NCard :bordered="false" title="任务列表">
                  <n-infinite-scroll style="height: 400px" :distance="10" @load="handleLoad">
                    <NCheckboxGroup :value="selTaskKeys" @update:value="handleUpdateSelTaskItem">
                      <n-space vertical>
                        <NCheckbox v-for="item in selTaskKey" :key="item?.id" :value="item?.id"
                          :label="item?.taskName" />
                      </n-space>
                    </NCheckboxGroup>
                  </n-infinite-scroll>
                </NCard>
              </div>
            </template>
            <template #2>
              <div style="margin: 0 10px">
                <NCard :bordered="false" title="已选任务">
                  <NSpace vertical>
                    <!-- ------------------------- 列表 | S -->
                    <n-infinite-scroll style="height: 400px" :distance="10" @load="handleLoad">
                      <NSpace vertical>
                        <!-- ------------------------- 列表 | S -->
                        <n-tag v-for="item in selTaskKey.filter(item => selTaskKeys.includes(item.id))" size="medium"
                          type="info" :bordered="false" closable @close="handleClose(item.id)">
                          {{ item.taskName }}
                        </n-tag>
                        <!-- ------------------------- 列表 | E -->
                      </NSpace>
                    </n-infinite-scroll>
                    <!-- ------------------------- 列表 | E -->
                  </NSpace>
                </NCard>
              </div>
            </template>
          </n-split>
        </NCol>
      </NRow>
    </div>
  </div>
</template>

<style>
#alarmpush {
  .active {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
