import { ExcelDownLoad } from '@/utils/request';
import service from '@/utils/request';
import type { App } from 'vue';
import type { ComponentPublicInstance } from 'vue';
import type { Router } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
// 在 curd.ts 中确保这些类型都已导出

export interface CreateDataParams {
  type: string;
  name: string;
  param: string;
  pageSize?: number;
  pageList?: number[];
  UserID?: string | number;
  ModularID?: string;
}

export interface RequestResponse {
  data: any;
  rows?: any[];
  total?: number;
}

export interface SelectOption {
  label?: string;
  value: any;
}

export interface FormComponent {
  resetFields(): void;
  validate(validator: (valid: boolean) => void): void;
}

export interface CurdInstance extends ComponentPublicInstance {
  $refs: {
    [key: string]: FormComponent;
  };
  $router: Router;
  $message: typeof ElMessage;
  $confirm: typeof ElMessageBox.confirm;
  id?: string | number;
  [key: string]: any;
}

// 下载相关函数
function download(url: string, imgblob: Blob): void {
  getBlob(url, (blob: Blob, filename: string) => {
    saveAs(blob, filename);
  }, imgblob);
}

function getBlob(url: string, cb: (blob: Blob, filename: string) => void, imgblob: Blob): void {
  const xhr = new XMLHttpRequest();
  const fromData = new FormData();
  fromData.append('base64', imgblob);
  xhr.open('POST', url, true);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (xhr.status === 200) {
      const contentDisposition = xhr.getResponseHeader('content-disposition');
      if (contentDisposition) {
        const name = contentDisposition.split('=')[1];
        const filename = decodeURIComponent(name);
        cb(xhr.response, filename);
      }
    }
  };
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send(fromData);
}

function saveAs(blob: Blob, filename: string): void {
  if ((window.navigator as any).msSaveOrOpenBlob) {
    (window.navigator as any).msSaveBlob(blob, filename);
  } else {
    const link = document.createElement('a');
    const body = document.querySelector('body');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    link.style.display = 'none';
    body?.appendChild(link);
    link.click();
    body?.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  }
}

export default {
  install(app: App): void {
    // 导出Excel方法
    app.config.globalProperties.exportExcel_NPOI = function (this: CurdInstance, param: string, blob: Blob): void {
      download(`${ExcelDownLoad}?param=${param}`, blob);
    };

    // 用于生成传通讯服务器参数
    app.config.globalProperties.CreateData = function (
      this: CurdInstance,
      type: string,
      name: string,
      data?: any[][],
      pageSize?: number,
      pageList?: number
    ): string {
      let param_Str: string = '';
      const param_array: ParamItem[] = [];

      if (type === '7') {
        data?.forEach(v => {
          pageSize?.toString().split('').forEach(h => {
            const val = h.toString();
            if (!v[val]) {
              v[val] = '';
            }
          });
        });
        param_Str = JSON.stringify(data);
      } else {
        if (data !== undefined) {
          for (let i = 0; i < data.length; i++) {
            param_array.push({
              name: data[i][0],
              value: data[i][1],
              type: data[i][2],
              output: data[i][3]
            });
          }
          param_Str = JSON.stringify(param_array);
        }
      }

      const obj: CreateDataParams = {
        type,
        name,
        param: param_Str,
        pageSize,
        pageList,
        UserID: this.id,
        ModularID: this.$router.currentRoute.value.path
      };

      return JSON.stringify(obj);
    };
    app.config.globalProperties.ExecDatabase = function (num: string) {
      return service({
        url: '',
        method: 'post',
        data: num
      })
    }
  }
};
