<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_userList api_addUserInfo api_modifyUserInfo api_delUserInfo api_modifyUserPass

/**
 * - api_algorithms 算法列表
 * - api_modifyAlgorithms 修改算法
 * */
import { api_algorithms, api_delPushItem, api_findPushItem, api_modifyAlgorithms } from '@/api/index';
import type { ItablePagination } from '@/views/AlgorithmConfiguration/index';

// api_userList api_addUserInfo api_modifyUserInfo api_delUserInfo api_modifyUserPass

import {
  api_getKeyOfAnaly,
  api_getKeyOfVideoSource,
  api_getKeyTaskInfo,
  api_addAlarmPush,
  api_videoTaskKey,
  api_pushList,
  api_modifyAlarmPush,
  api_test,
  // 用户管理相关
  api_userList,
  api_addUserInfo,
  api_modifyUserInfo,
  api_delUserInfo,
  api_modifyUserPass,
  api_roleList
} 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 updatePassModal = ref(false);

// 更新密码
const newPass = ref('');

// 当前用户id
const curUserId = ref('')

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

// 拿到角色信息
const roleOptions = ref([]);

const getRoleList = async () => {
  await api_roleList().then(res => {
    if (res.data.code === 200) {
      roleOptions.value = res.data.data;
    }
  })
}


// 查询用户
const total = ref(0);
const getUserList = async () => {
  show.value = true;
  const param: ItablePagination = {
    pageNum: page.value,
    pageSize: pageSize.value,
    userName: ''
  };
  await api_userList(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 addUserItem = async () => {

  console.log("============== form", form)

  if (form.name && form.phone && form.roleId && form.userName) {
    if (isAddUserModalType.value) {

      if (!form.password) {
        return message.error('选项皆为必选项!');
      }

      return await api_addUserInfo(form).then(res => {
        if (res.data.code === 200) {
          getUserList();
          form = oldForm;
          console.log("===================== create 后 houform", oldForm)
          createModal.value = false;
          return message.success("添加成功!")
        }
        return message.error(res.data.msg)
      })
    } else {
      return await api_modifyUserInfo(form).then(res => {
        if (res.data.code === 200) {
          getUserList();
          form = oldForm;
          createModal.value = false;
          console.log("===================== midify 后 form", oldForm)
          return message.success("修改成功!")
        }
        return message.error(res.data.msg)
      })
    }
  }

  return message.error('选项皆为必选项!');
};


const isAddUserModalType = ref(true);

// 删除用户
const delUserInfo = async (id) => {
  return await api_delUserInfo(id).then(res => {
    if (res.data.code === 200) {
      getUserList();
      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: 'name',
    align: 'center',
    minWidth: 180
  },
  {
    title: '用户名',
    key: 'userName',
    align: 'center',
    minWidth: 180
  },
  {
    title: '手机号',
    key: 'phone',
    align: 'center',
    minWidth: 180
  },
  {
    title: '角色',
    key: 'roleName',
    minWidth: 220,
    align: 'center',
  },
  {
    title: '操作',
    minWidth: 220,
    key: 'actions',
    align: 'center',
    render(row: any) {
      return (
        <NSpace justify='center'>
          <NButton
            onClick={() => {
              curInfo.value = row;
              createModal.value = true;
              let { name, userName, phone, roleId, } = row;
              isAddUserModalType.value = false;

              form.id = row.id;

              ['name', 'userName', 'phone', 'roleId'].forEach(key => {
                form[key] = row[key];
              });
            }
            }
            quaternary
            type="info"
          >
            编辑
          </NButton>

          <NButton
            onClick={() => {
              curUserId.value = row.id;
              updatePassModal.value = true;
            }}
            quaternary
            type="info"
          >
            修改密码
          </NButton>
          < NButton
            onClick={() => {
              curInfo.value = row;
              isInfo.value = true;
              delUserInfo(curInfo.value.id);
            }
            }
            quaternary
            type="error"
          >
            删除
          </NButton>
        </NSpace>
      );
    }
  }
];

const selectWebCaM = ref([]);

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({
  name: '用户名称0092000',
  password: '987654321',
  phone: '18363102084',
  roleId: '3',
  userName: '李四',
});

const cleanCreateFromInfo = () => {
  ['name', 'password', 'phone', 'roleId', 'userName'].forEach(item => {
    form[item] = '';
  })
}

let oldForm = reactive({
  name: '',
  password: '',
  phone: '',
  roleId: '',
  userName: '',
});


// 新增提交
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)
      getUserList();
      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, () => {
  getUserList();
});

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

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



// 修改密码
const updatePass = async (id: string, password: string) => {
  await api_modifyUserPass(id, password).then(res => {
    if (res.data.code === 200) {
      getUserList();
      updatePassModal.value = false;
      return message.success("修改成功!")
    }
    return message.error(res.data.msg)
  })
};

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

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

<template>
  <div id="UserPage">
    <NModal v-model:show="updatePassModal">
      <NCard title="更新密码" style="width: 600px;" closable @close="updatePassModal = false">

        <NInput style="margin: 30px 0;" v-model:value="newPass" placeholder="请输入新密码" clearable />

        <template #footer>
          <NSpace justify="end">
            <NButton @click="updatePassModal = false">取消</NButton>
            <NButton type="primary" @click="() => updatePass(curUserId, newPass)">确定</NButton>
          </NSpace>
        </template>
      </NCard>
    </NModal>

    <!-- ================================== 视频源 多选框 | 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="isAddUserModalType ? '新增' : '修改'" style="width: 600px" closable @close="() => {
        createModal = false;
      }">
        <!-- 提交表单 -->
        <NForm label-placement="left" label-width="auto">

          <NFormItem required label="用户名">
            <NInput v-model:value="form.userName" placeholder="请输入" />
          </NFormItem>

          <NFormItem required label="手机号">
            <NInput v-model:value="form.phone" placeholder="请输入" />
          </NFormItem>

          <NFormItem required label="真实姓名">
            <NInput v-model:value="form.name" placeholder="请输入" />
          </NFormItem>

          <NFormItem v-if="isAddUserModalType" required label="登录密码">
            <NInput v-model:value="form.password" placeholder="请输入" />
          </NFormItem>

          <NFormItem required label="角色权限">
            <n-select v-model:value="form.roleId" value-field="id" label-field="roleName" :options="roleOptions"
              @update:value="val => form.roleId" placeholder="请选择" />
          </NFormItem>
        </NForm>

        <template #footer>
          <!-- =============================================== 新增提交 | S -->
          <NSpace justify="end">
            <NButton @click="createModal = false">取 消</NButton>
            <NButton type="primary" @click="addUserItem">保 存</NButton>
          </NSpace>
          <!-- =============================================== 新增提交 | E -->
        </template>
      </NCard>
    </NModal>

    <!-- 推送任务列表 -->
    <!-- ===================================== 数据展示 | S -->
    <div>
      <NSpin :show="show">
        <NCard size="medium">
          <template #header>
            <NButton type="primary" ghost @click="() => {
              // numModule = '0';
              form = oldForm;
              isAddUserModalType = true;
              createModal = true;
              cleanCreateFromInfo();
              // 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" />

          <!--  -->
          <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>
  </div>
</template>

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