text: import store from '../store';
  import { post } from './http';
  import { ElMessage } from 'element-plus';
  import tools from '../../src/utils/tools';
  
  export class Dummy {
    constructor(parms, isAdmin) {
      return new Promise((resolve) => {
        const query = {
          Path: '/v1/open/user/register',
          Body: JSON.stringify(parms),
        };
        Dummy.ServiceProxy(query).then((res) => {
          const data = JSON.parse(res.Data);
          if (data.error_code === 0) {
            if (isAdmin) {
              const admin = {
                token: data.token,
                UserID: data.user_id,
                admin: true,
                nickname: '管理员',
              };
              store.commit('setAdmin', admin);
              resolve(admin);
            } else {
              const Dummy = {
                token: data.token,
                UserID: data.user_id,
                nickname: 'wabiwabo',
              };
              // 普通学员统一在加入群聊的时候setDummy
              resolve(Dummy);
            }
          }
        });
      });
    }
  
    /*
  
    //////////////////////////////////////////////////////tcic业务接口//////////////////////////////////////////////////////////////////////////
    返回数据形式：{
      Data: "{\"class_duration\":0,\"class_task_seq\":0,\"classq\":38,\"request_id\":\"5d632879-b5a3-45dc-8b1e-17353138a9ea\"}"
      Error: {Code: "OK", Message: "success"}
      RequestID: "5d632879-b5a3-45dc-8b1e-17353138a9ea"
    }
  
    */
    static ServiceProxy(parms) {
      const TCIC_URL = `${Dummy.DASHBOARD_URL + Dummy.DEFAULT_URL}`;
      const requestParms = {
        DeveloperID: store.state.DeveloperID,
        EnvName: store.state.EnvName,
        ...parms,
      };
      return post(`${TCIC_URL}ServiceProxy?token=${localStorage.getItem('token')}`, requestParms);
    }
  
    // 批量注册
    static batchRegister(parms) {
      return new Promise((resolve) => {
        const query = {
          Path: '/v1/open/user/batchRegister',
          Body: JSON.stringify(parms),
        };
        Dummy.ServiceProxy(query).then((res) => {
          const data = JSON.parse(res.Data);
          if (data.error_code === 0) {
            resolve(data);
          }
        });
      });
    }
  
    // 根据origin_id 登录，获取token
    static loginByOriginID(parms) {
      return new Promise((resolve) => {
        const query = {
          Path: '/v1/open/user/loginByOriginID',
          Body: JSON.stringify(parms),
        };
        Dummy.ServiceProxy(query).then((res) => {
          const data = JSON.parse(res.Data);
          if (data.error_code === 0) {
            resolve(data);
          }
        });
      });
    }
  
    static searchSchoolInfo(parms, token) {
      const query = {
        Path: `/v1/school/getInfo?token=${token}`,
        Body: JSON.stringify(parms),
      };
      this.ServiceProxy(query).then((res) => {
        const data = JSON.parse(res.Data);
        store.commit('setSchoolInfo', data);
      });
    }
  
    static getClassInfo(parms, token) {
      const query = {
        Path: `/v1/class/getInfo?token=${token}`,
        Body: JSON.stringify(parms),
      };
      this.ServiceProxy(query).then((res) => {
        const data = JSON.parse(res.Data);
        store.commit('addClassInfo', data);
      });
    }
  
    static searchMemberList(parms, token) {
      const query = {
        Path: `/v1/member/memberList?token=${token}`,
        Body: JSON.stringify(parms),
      };
      this.ServiceProxy(query).then((res) => {
        const data = JSON.parse(res.Data);
        /* 不包括老师，包括上线和未上线的学生。*/
        if (data.error_code === 0) {
          for (let item of data.members) {
            item = tools.transformMemberStatus(item);
          }
          store.commit('setClassMemberList', data.members);
        }
      });
    }
  
    // 以访客的身份访问
    static DummyJoin(parms, token) {
      return new Promise((resolve, reject) => {
        const query = {
          Path: `/v1/member/join?token=${token}`,
          Body: JSON.stringify(parms),
        };
        this.ServiceProxy(query).then((res) => {
          if (res.Error.Code === 'OK') {
            const data = JSON.parse(res.Data);
            data.token = token;
            /* 学生老师都在，并且都是在线的状态 */
            resolve(data);
          } else {
            reject(res);
          }
        });
      });
    }
  
    static addMember(parms, token) {
      return new Promise((resolve, reject) => {
        const query = {
          Path: `/v1/open/classroom/addMember?token=${token}`,
          Body: JSON.stringify(parms),
        };
        this.ServiceProxy(query).then((res) => {
          if (res.Error.Code === 'OK') {
            const data = JSON.parse(res.Data);
            data.token = token;
            /* 学生老师都在，并且都是在线的状态 */
            resolve(data);
          } else {
            reject(res);
          }
        });
      });
    }
  
    static quit(parms, token) {
      return new Promise((resolve, reject) => {
        const query = {
          Path: `/v1/member/quit?token=${token}`,
          Body: JSON.stringify(parms),
        };
        this.ServiceProxy(query).then((res) => {
          if (res.Error.Code === 'OK') {
            const data = JSON.parse(res.Data);
            resolve(data);
          } else {
            reject(res);
          }
        });
      });
    }
  
    static updateTask(parms, token) {
      return new Promise((resolve) => {
        const query = {
          Path: `/v1/class/updateTask?token=${token}`,
          Body: JSON.stringify(parms),
        };
        this.ServiceProxy(query).then((res) => {
          res.token = token;
          resolve(res);
        });
      });
    }
  
    static action(parms, token) {
      return new Promise((resolve) => {
        const query = {
          Path: `/v1/member/action?token=${token}`,
          Body: JSON.stringify(parms),
        };
        this.ServiceProxy(query).then((res) => {
          if (res.Error.Code === 'OK') {
            const data = JSON.parse(res.Data);
            data.token = token;
            resolve(data);
          } else {
            resolve(res);
          }
        });
      });
    }
  
    static heartBeat(token, interval) {
      console.log(`心跳间隔：${interval / 1000}秒`, 'hearbeat');
      return new Promise((resolve, reject) => {
        const heartBeat = setTimeout(() => {
          const query = {
            Path: `/v1/member/heartbeat?token=${token}`,
            Body: JSON.stringify({
              class_id: store.state.classInfo.ClassID,
              state_report: JSON.stringify({
                RtcInfos: [],
                Role: 0,
              }),
            }),
          };
          this.ServiceProxy(query).then((res) => {
            const data = JSON.parse(res.Data);
            if (res.Error.Code === 'OK') {
              clearTimeout(heartBeat);
              Dummy.heartBeat(token, data.interval);
              resolve(res);
            } else {
              reject(res);
            }
          });
        }, interval);
      });
    }
  
    /*
  
    //////////////////////////////////////////////////////IM通信模块//////////////////////////////////////////////////////////////////////////
    返回数据格式：{
      ActionStatus: "OK"
      ErrorCode: 0
      ErrorInfo: ""
      HugeGroupFlag: 0
      JoinedStatus: "JoinedSuccess"
      JoinedTime: 1626752320
      Type: "Public"
    }
   */
    static IM_URL = 'https://yun.tim.qq.com/';
  
    // 加入群聊
    static joinGroup(parms) {
      post(
        `${Dummy.IM_URL}v4/group_open_http_svc/apply_join_group?usersig=${parms.usersig}&identifier=${parms.identifier}&sdkappid=${parms.sdkappid}&contenttype=json`,
        {
          GroupId: `${parms.class_id}`,
        },
      )
        .then(() => {
          const DummyDetail = {
            usersig: parms.usersig,
            UserID: parms.identifier,
            sdkappid: parms.sdkappid,
            class_id: parms.class_id,
            token: parms.token,
          };
          store.commit('setDummy', DummyDetail);
        })
        .catch((err) => {
          console.error('joinGroupError', err);
        });
    }
  
    // 发送IM信息
    static sendGroupMessage(parms) {
      return new Promise((resolve) => {
        post(
          `${Dummy.IM_URL}/v4/group_open_http_svc/send_group_msg?usersig=${parms.usersig}&identifier=${parms.identifier}&sdkappid=${parms.sdkappid}&contenttype=json`,
          {
            GroupId: `${parms.class_id}`,
            Random: 8912345,
            MsgBody: [
              // 消息体，由一个 element 数组组成，详见字段说明
              // exploit:后续完善，见https://cloud.tencent.com/document/product/269/1629
              {
                MsgType: 'TIMTextElem', // 文本
                MsgContent: {
                  Text: parms.groupMessage,
                },
              },
            ],
          },
        )
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.error('joinGroupError', err);
          });
      });
    }
  
    /*
  
    //////////////////////////////////////////////////////仪表盘接口//////////////////////////////////////////////////////////////////////////
    返回数据形式：{
      DeveloperID: "8720bbab-e9cf-461f-b5f4-bf07d6defc56"
      EnvName: "testenv"
      Error: {Code: "OK", Message: "success"}
      Found: true
      RequestID: "0d74ddee-c34f-43fa-846d-b9ea0e76f5c0"
    }
    */
    static DASHBOARD_URL = 'https://dashboard-middleware-test.qcloudclass.com/';
  
    static DEFAULT_URL = 'tcic_dc.dashboard_middleware.default/';
    static MAIN_URL = 'tcic_dc.dashboard_middleware.main/';
  
    // 查询课室的基础环境（开发商、是否为测试环境）
    static searchBasicEnvironment(parm) {
      return new Promise((resolve) => {
        post(
          `${Dummy.DASHBOARD_URL + Dummy.MAIN_URL}DescribeClassEnvInfo?token=${localStorage.getItem('token')}`,
          parm,
        ).then((res) => {
          if (res.EnvName !== '') {
            store.commit('setBasicEnvironment', res);
          }
          resolve(res);
        });
      });
    }
  
    static searchClassInfo(parm) {
      return new Promise((resolve, reject) => {
        post(
          `${Dummy.DASHBOARD_URL + Dummy.DEFAULT_URL}DescribeRTCClassInfo?token=${localStorage.getItem('token')}`,
          parm,
        ).then((res) => {
          if (res.Error.Code === 'OK') {
            res.StartTime = tools.transformDate(res.StartTime);
            res.EndTime = tools.transformDate(res.EndTime);
            res.RealStartTime = tools.transformDate(res.RealStartTime);
            res.RealEndTime = res.Status >= 2 ? tools.transformDate(res.RealEndTime) : '';
            const classInfo = tools.transformMemberStatus(res);
            Dummy.searchUserInfo({
              DeveloperID: parm.DeveloperID,
              EnvName: parm.EnvName,
              UserIDs: [`${res.TeacherID}`],
            }).then((data) => {
              classInfo.TeacherID = `${data.UserInfos[0].Nickname}(${classInfo.TeacherID})`;
              store.commit('setClassInfo', classInfo);
            });
            resolve(res);
          } else {
            reject(res);
            ElMessage.error(`error:${res}`);
          }
        });
      });
    }
  
    static searchUserInfo(parm) {
      return new Promise((resolve, reject) => {
        post(
          `${Dummy.DASHBOARD_URL + Dummy.DEFAULT_URL}DescribeUserInfos?token=${localStorage.getItem('token')}`,
          parm,
        ).then((res) => {
          if (res.Error.Code === 'OK') {
            resolve(res);
          } else {
            reject(res);
            ElMessage.error(`error:${res}`);
          }
        });
      });
    }
  }
  