import { defineStore } from 'pinia';

import {
  DAHUALogin,
  DAHUALoginParams,
  LoginResponse,
  DAHUAKeepAlive,
  DAHUAUserInfo,
  DAHUAInfomation,
  DAHUACreateMeet,
  DAHUADeleteMeet,
  DAHUAMeetingUser,
  DAHUADevice,
  DAHUAMeetingMember,
  MeetingResponse,
  DAHUAUserObj,
} from '@/api/dahua';
import isString from 'lodash/isString';
import { parseStr } from '@/utils';
import md5 from 'crypto-js/md5';
import { DA_HUA, DA_HUA_URL_PREFIX } from '@/constants/constants';
import { ElMessage } from 'element-plus';

export interface DaHuaStateType {
  dahuaUserVisible: boolean;
  dhuser: object;
  timer: NodeJS.Timer | null;
  dhToken: string;
}

export interface DaHuaActionsType {
  DAHUALogin(): void;
  KEEPAlive(): void;
  DAHUAUserInfo(): Promise<any>;
  DAHUAInfomation(): void;
  DAHUAUserObj(id: string): Promise<any>;
  DAHUAMeetingMember(obj: any): Promise<any>;
  DAHUADeviceList(id: string): Promise<any>;
  DAHUADeleteMeet(id: string): Promise<any>;
  DAHUAMeetingUser(id: string): void;
  DAHUACreateMeet(user: any): Promise<any>;
}

export default defineStore<'daHua', DaHuaStateType, {}, DaHuaActionsType>(
  'daHua',
  {
    state: () => ({
      dahuaUserVisible: false,
      dhuser: {},
      deviceUser: {},
      timer: null,
      dhToken: localStorage.getItem('DAHUA_token') ?? '',
    }),
    actions: {
      async DAHUALogin() {
        try {
          const { password, username } = DA_HUA;

          const firstLoginRes = await fetch(
            `${DA_HUA_URL_PREFIX}/videoService/accounts/authorize`,
            {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'X-Subject-Token': '',
              },
              body: JSON.stringify({
                userName: username,
                clientType: 'winpc',
                ipAddress: '', //可不传
                pid: 2548, //可不传
              }),
            },
          );

          const firstLogin = (await firstLoginRes.json()) as unknown as {
            realm?: string;
            randomKey: string;
          };

          const md1 = md5(password); //第1次加密
          const md2 = md5(username + md1); //第2次加密
          const md3 = md5(md2.toString()); //第3次加密
          const md4 = md5(username + ':' + firstLogin.realm + ':' + md3); //第4次加密
          const signature = md5(md4 + ':' + firstLogin.randomKey); //第5次加密
          const data = await DAHUALogin({
            userName: username,
            signature: signature.toString(),
            randomKey: firstLogin.randomKey,
            encryptType: 'MD5',
            clientType: 'winpc',
            pid: 2548,
          });
          const next = isString(data)
            ? parseStr<LoginResponse>(data)
            : data ?? {};
          this.dhToken = next.token ?? '';
          localStorage.setItem('DAHUA_token', next.token ?? '');
          localStorage.setItem(
            'DAHUA_userId',
            JSON.stringify(next.userId || ''),
          );
          this.timer && clearInterval(this.timer);
          this.KEEPAlive();
        } catch (err) {
          ElMessage.error({
            message: '大华应急指挥调度实战平台鉴权失败, 请尝试刷新页面重试',
          });
        }
      },
      async KEEPAlive() {
        const that = this;
        // this.timer = setInterval(() => {
        //   DAHUAKeepAlive({
        //     token: that.dhToken,
        //   });
        // }, 20000);
      },
      async DAHUAUserInfo() {
        const dahuaToken = localStorage.getItem('DAHUA_token') ?? '';
        const res = await DAHUAUserInfo({
          token: dahuaToken,
        });
        return res;
      },
      async DAHUAInfomation() {
        const res = await DAHUAInfomation({
          page: 1,
          pageSize: 1000,
          condition: {},
          keyCondition: {},
          token: this.dhToken,
        });
        return res;
      },
      async DAHUACreateMeet(user) {
        const res = await DAHUACreateMeet({
          masterName: user.userName,
          masterId: user.userCode,
          masterNumber: user.userPhone,
          region: user.paasId,
          mode: 'group',
          name: '11111',
          record: true,
          type: 'video',
          token: this.dhToken,
        });
        return isString(res) ? parseStr<MeetingResponse>(res) : res ?? {};
      },

      async DAHUAMeetingUser(id) {
        try {
          await DAHUAMeetingUser({
            token: this.dhToken,
            meetId: id,
          });
        } catch (error) {}
      },

      async DAHUADeleteMeet(id) {
        try {
          await DAHUADeleteMeet({
            token: this.dhToken,
            meetId: id,
          });
        } catch (error) {}
      },

      //设备列表
      async DAHUADeviceList(id) {
        const res = await DAHUADevice({
          token: this.dhToken,
          nodeType: 1,
          typeCode: '01;1;ALL',
          page: 1,
          pageSize: 100,
          id: id,
        });
        return res;
      },

      async DAHUAMeetingMember(obj) {
        await DAHUAMeetingMember({
          obj: {
            id: obj.meetId,
            inviteId: obj.user.userCode,
            inviteName: obj.user.userName,
            inviteNumber: obj.user.userPhone,
            member: obj.member,
          },
          token: this.dhToken,
        });
      },

      async DAHUAUserObj(id) {
        const res = await DAHUAUserObj({
          token: this.dhToken,
          id,
        });
        // this.deviceUser = res;
        return res;
      },
    },
  },
);
