<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 修改算法
 * */

//  // api_delRoleInfo api_modifyRoleInfo
// // api_modifyRoleInfo api_addRole
import { api_addRole, api_roleInfo, api_delRoleInfo, api_modifyRoleInfo, api_algorithms, api_findPushItem, api_modifyAlgorithms } from '@/api/index';
import type { ItablePagination } from '@/views/AlgorithmConfiguration/index';
import { api_permissionTreeList, api_findfRoleInfo, api_roleList, 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 permissionTree = ref([]);
// 获取权限
const getPermissionTreeList = async () => {
  return await api_permissionTreeList().then(res => {
    if (res.data.code === 200) {
      return permissionTree.value = res.data.data.items;
    };
    return message.error(res.data.msg);
  })
};


const getRoleInfo = async (id: string) => {
  await api_roleInfo(id).then(res => {
    if (res.data.code === 200) {
      form.permissions = [];
      form.roleName = res.data.data.roleName;
      form.roleRemark = res.data.data.roleRemark;
      form.permissions = res.data.data.permissions || [];
      console.log("|||||||||||||||||||================ form.permissions", form.permissions)

      isAddRoleModalType.value = false;
      createModal.value = true;
    }
  })
}

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


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

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

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

const delRoleInfo = async (id: string) => {
  return await api_delRoleInfo(id).then(res => {
    if (res.data.code === 200) {
      getRoleList();
      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: 'ID',
    key: 'id',
    align: 'center',
    minWidth: 180
  },
  {
    title: '角色名称',
    key: 'roleName',
    align: 'center',
    minWidth: 180
  },
  {
    title: '角色描述',
    key: 'roleRemark',
    align: 'center',
    minWidth: 180
  },
  {
    title: '操作',
    minWidth: 220,
    key: 'actions',
    align: 'center',
    render(row: any) {
      return (
        <NSpace justify='center'>
          <NButton
            onClick={() => {
              form.id = row.id;
              getRoleInfo(row.id);
            }}
            quaternary
            type="info"
          >
            编辑
          </NButton>
          < NButton
            onClick={() => {
              curInfo.value = row;
              isInfo.value = true;
              delRoleInfo(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({
  permissions: [
    "100001000000000", "100001001000000", "100001002000000", "100001003000000", "100001004000000", "100001005000000", "100001005001000", "100001005002000", "100001005003000", "100001006000000"
    , "100001006001000", "100001006002000"
  ],
  roleName: "",
  roleRemark: ""
});


const cleanFormInfo = () => {
  ['roleName', 'roleRemark'].forEach(item => {
    form[item] = '';
  })
}


let oldForm = reactive({
  permissions: [
    "100001000000000", "100001001000000", "100001002000000", "100001003000000", "100001004000000", "100001005000000", "100001005001000", "100001005002000", "100001005003000", "100001006000000"
    , "100001006001000", "100001006002000"
  ],
  roleName: "",
  roleRemark: ""
});

// 新增提交
const onSubmit = async () => {
  //
  if (!form.roleName || !form.roleRemark) {
    return message.error('选项皆为必填项!');
  }

  // api_modifyRoleInfo api_addRole
  if (isAddRoleModalType.value) {
    await api_addRole(form).then(res => {
      if (res.data.code === 200) {
        createModal.value = false;
        getRoleList();
        return message.success("添加成功!")
      }
      return message.error(res.data.msg);
    });
  } else {
    await api_modifyRoleInfo(form).then(res => {
      if (res.data.code === 200) {
        createModal.value = false;
        getRoleList();
        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, () => {
  getRoleList();
});

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

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;
      getRoleList()
      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}`);
}


// 树 - 节点
const treeData = ref([]);

const override = async () => {
  return 'default'
}

const isAddRoleModalType = ref(true);


// 节点勾选发生变化
const updateCheckedKeys = async (keys, option, meta, action) => {
  console.log("======= keys", keys, option, meta, action)
  form.permissions = keys;
}

onMounted(() => {
  getRoleList();
  // getAnalyList();
  // getTaskList();
  // getVideoSourceKey();
  // getSelTaskKey();
  getPermissionTreeList()

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

<template>
  <div id="RolePage">
    <!-- ================================== 视频源 多选框 | 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 }}
          </NFormItem>
        </NForm>

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

    <!-- 对话框 - 创建 -->
    <NModal v-model:show="createModal">
      <!--  -->
      <NCard :title="isAddRoleModalType ? '新增角色' : '修改角色'" style="width: 600px" closable @close="() => {
        createModal = false;
      }">
        <NRow :gutter="30">
          <NCol span="21">
            <NForm label-placement="left" label-width="auto">

              <NFormItem required label="角色名称">
                <NInput v-model:value="form.roleName" placeholder="请输入任务名称" />
              </NFormItem>

              <NFormItem required label="角色描述">
                <n-input v-model:value="form.roleRemark" placeholder="请输入任务地址" type="textarea" :autosize="{
                  minRows: 3,
                  maxRows: 5,
                }" />
              </NFormItem>

              <NFormItem required label="权限分配">
                <!-- :default-expanded-keys="defaultExpandedKeys" -->
                <!-- :override-default-node-click-behavior="override" -->
                <!-- expand-on-click -->
                <div style="width: 100%;">
                  <!-- default-selected-keys -->
                  <NTree cascade block-node checkbox-placement="right" @update:checked-keys="updateCheckedKeys"
                    :default-checked-keys="form.permissions" checkable accordion show-line block-line
                    :data="permissionTree" key-field="id" default-expand-all>
                  </NTree>
                </div>
              </NFormItem>
            </NForm>
          </NCol>
        </NRow>

        <template #footer>
          <!-- =============================================== 新增提交 | S -->
          <NSpace justify="end">
            <NButton @click="createModal = false">取消</NButton>
            <NButton type="primary" @click="onSubmit">确定</NButton>
          </NSpace>
          <!-- =============================================== 新增提交 | E -->
        </template>
      </NCard>
    </NModal>
    <!-- 推送任务列表 -->

    <!-- ===================================== 数据展示 | S -->
    <div>
      <NSpin :show="show">
        <NCard size="medium">
          <template #header>
            <NButton type="primary" ghost @click="() => {
              form = oldForm;
              isAddRoleModalType = true;
              createModal = true;
              cleanFormInfo();
            }">
              <template #icon>
                <icon-ic:baseline-plus class="text-icon" />
              </template>
              新增角色
            </NButton>
          </template>
          <NDataTable
           :item-count="total"
          :row-key="row => row.id" :columns="tableColumn" :data="tableData" :bordered="false"
            @update:checked-row-keys="handleCheck" />
          <!-- <div style="display: flex; justify-content: end">
            <NPagination 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>
  </div>
</template>

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