import { HModal } from '@crami/ui';
import { nextTick, watch, h } from 'vue';
import { useHttp } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
// 从配置文件中引入需要弹出的页面
import * as Pages from '@/config/customForm/index';

// 页面数据定义
export type IPageData = {
  customFormSelectRef: any;
  selectValue: any;
  selectProps: any;
  coderValue: any;
  coderProps: any;
  confirm: any;
};

// click类型
export type IData = {
  type: string;
  value: string;
  text: string;
  param: any;
  autoQueryAllFields: boolean;
  row: Array<{ type: string; 'db-table-field': string; [key: string]: any }>;
  attribute: {
    objectId: string;
  };
  resolve: any;
  [key: string]: any;
};

// 根据id获取信息
const getDataById = async (id: string) => {
  let data = [];
  const result = await useHttp({
    url: commonApi().system.getObjectDataTestList.url,
    // 这里暂时使用mock接口提供假数据
    // url: 'http://10.0.59.229:7300/mock/622ff143ec91f63c580c0560/api/system/model/GetObjectDataTestList',
    method: commonApi().system.getObjectDataTestList.method,
    params: {
      ...commonApi().system.getObjectDataTestList.params,
      //queryType: 'multi', // 按照多选处理
      objectID: id, // 多个id用分号隔开
    },
  });
  if (result.code == 200) {
    data = result.data.data;
    // 返回的数据是json格式，处理一下
    // result.data.data.forEach(row => {
    //   data.push(JSON.parse(row));
    // });
  }

  return data;
};

// 数据处理
const processData = async (
  data: Array<{ text: string; value: string; type: string }>,
  options: {
    autoQueryAllFields?: boolean;
    row: Array<{ type: string; 'db-table-field': string; [key: string]: any }>;
    options?: any;
  },
) => {
  const newData = [...data];
  // const newData = [];

  if (options.autoQueryAllFields) {
    const allData = await getDataById(data[0]['value']);

    if (options.row && Array.isArray(options.row)) {
      options.row.forEach(element => {
        const filedName = element['db-table-field'];
        let obj: any = {};

        if (filedName) {
          obj = {
            text: allData[filedName + '_DisplayValue'], // 显示值
            value: allData[filedName],
            type: element.type,
          };
          newData.push(obj);
        } else {
          if (element.type == options.options.type) {
            obj = {
              text: data[0]['text'], // 显示值
              value: data[0]['value'],
              type: element.type,
            };
            newData.push(obj);
          }
        }
      });

      return newData;
    }
  } else {
    return data;
  }
};

/**
 * 组织选择:organization
 * 行政组选择:administrativeGroup
 * 用户组选择:userGroup
 * 角色选择:role
 * 岗位选择:position
 * 用户选择:user
 */

const getSelectData = async (type, data, resolveType) => {
  const commonParams = getInfo(ICP_CONFIG);
  const customSelectApiMap = {
    organization(value) {
      return {
        url: '/api/system/query/getSelectedOrg',
        method: 'post',
        params: {
          companyId: commonParams.companyId,
          orgIds: value,
          valueType: 'string',
        },
      };
    },
    administrativeGroup(value) {
      return {
        url: '/api/system/query/getSelectedDept',
        method: 'post',
        params: {
          companyId: commonParams.companyId,
          deptIds: value,
          valueType: 'string',
        },
      };
    },
    userGroup(value) {
      return {
        url: '/api/system/query/getSelectedGroup',
        method: 'post',
        params: {
          companyId: commonParams.companyId,
          groupIds: value,
          valueType: 'string',
        },
      };
    },
    role(value) {
      return {
        url: '/api/system/query/getSelectedRole',
        method: 'post',
        params: {
          companyId: commonParams.companyId,
          roleIds: value,
          valueType: 'string',
        },
      };
    },
    position(value) {
      return {
        url: '/api/system/query/getSelectedPost',
        method: 'post',
        params: {
          companyId: commonParams.companyId,
          postIds: value,
          valueType: 'string',
        },
      };
    },
    user(value) {
      return {
        url: '/api/system/query/getSelectedUser',
        method: 'post',
        params: {
          companyId: commonParams.companyId,
          userIds: value,
          valueType: 'string',
        },
      };
    },
  };
  const valueString = Array.isArray(data) ? data.join(';') : data;

  const result = await useHttp(customSelectApiMap[type](valueString));
  if (result.code === 200) {
    return [
      {
        text: result.data.map(item => item.ename).join(','),
        value: Array.isArray(data) ? data.join(',') : data,
        type: resolveType,
      },
    ];
  } else {
    return [
      {
        text: '',
        value: '',
        type: resolveType,
      },
    ];
  }
};

const customSelect = (
  params: { [key: string]: any },
  pageData: IPageData,
  data: IData,
  originData,
) => {
  // 设置相关的配置参数
  for (const key in params) {
    if (Object.prototype.hasOwnProperty.call(params, key)) {
      if (key == 'value') {
        // 设置数据的初始值
        pageData.customFormSelectRef.setData(params[key]);
      } else {
        pageData.selectProps[key] = params[key];
      }
    }
  }
  // 测试多选
  // pageData.selectProps.selectMode = 'multiple';
  // 设置数据
  console.log(new Date());
  nextTick(() => {
    console.log(new Date());
    let initData: Array<string> = [];
    try {
      initData = data.value.split(',');
    } catch (e) {
      console.log(e);
    }
    pageData.customFormSelectRef.resetModal();
    pageData.customFormSelectRef.setData(initData);
    pageData.customFormSelectRef.controlModal(); // 弹出选择窗
  });
  pageData.confirm = async () => {
    if (typeof data.resolve == 'function') {
      console.log(pageData.selectValue);
      const result = await getSelectData(params.componentType, pageData.selectValue, data.type);
      const processResult = await processData(result, data);
      data.resolve(processResult);
    }
  };
};

/**
 * 编码器自定义弹窗
 */

const coderSelect = (
  params: { [key: string]: any },
  pageData: IPageData,
  data: IData,
  originData,
) => {
  // 下拉框的值设置为空
  pageData.coderValue = data.value || '';
  // 设置相关的配置参数
  for (const key in params) {
    if (Object.prototype.hasOwnProperty.call(params, key)) {
      if (key == 'value') {
        pageData.coderValue = params[key];
      } else {
        pageData.coderProps[key] = params[key];
      }
    }
  }

  nextTick(() => {
    // 模拟点击触发弹框
    const buttonDom: any = document.querySelector('.custom-form-encoder .ant-btn');
    buttonDom.click();
  });

  setTimeout(() => {
    // 监听数据变化后返回
    const unwatch = watch(
      () => pageData.coderValue,
      async () => {
        if (typeof data.resolve == 'function') {
          console.log(pageData.coderValue);
          const result = pageData.coderValue;
          const processResult = await processData(
            [
              {
                text: result,
                value: result,
                type: data.type,
              },
            ],
            data,
          );
          data.resolve(processResult);
        }
        unwatch();
      },
    );
  }, 1000);
};

/**
 * 自定义弹出页面
 */

const pageSelect = (
  params: { [key: string]: any },
  pageData: IPageData,
  data: IData,
  originData,
) => {
  const currentPage = Pages[params.componentType];
  // 先判断页面有没有注册
  if (!currentPage) {
    HModal.error({
      title: '提示',
      content: `页面【${params.componentType}】未注册，请在先src/config/customForm文件夹中进行注册！`,
    });
    //reject('页面不存在');
    return;
  }
  const { page, inParam, outParam } = currentPage;
  const componentProp = inParam({ page, params, data, originData });
  const handleOk = (page, resolve) => {
    saveData(page, resolve);
  };
  // 弹出现有的vue页面
  const modalOptions = {
    title: params.title || '弹框',
    // content: defineAsyncComponent(() => import(params.componentType)),
    content: h(page, componentProp),
    width: params.width || 'auto',
    onOk: handleOk,
    ...params,
  };

  const saveData = async (page, resolve) => {
    const result = await outParam({ page, params, data, originData });
    if (result) {
      const processDataResult = await processData(result, originData);
      data.resolve(processDataResult);
      resolve();
      modalPage.destroy();
    }
  };
  const modalPage = HModal.page(modalOptions);
};

/**
 * 自定义弹窗处理
 * type: 弹窗类型
 * params: 弹窗的参数
 * */

export const customPopup = async (data: IData, pageData: IPageData, originData) => {
  let params: any = {};
  try {
    params = data.param;
  } catch (e) {
    console.log(e);
    console.log('params解析出错了');
  }
  const type = params.componentType;

  const selectMap = [
    'user',
    'position',
    'role',
    'userGroup',
    'administrativeGroup',
    'organization',
  ];
  if (selectMap.includes(type) || type == 'select') {
    // 自定义选择用户、组织、行政组
    customSelect(params, pageData, data, originData);
  } else if (type == 'coder') {
    // 编码器,默认参数
    const commonParams = getInfo(ICP_CONFIG);
    let objectId = ['', ''];
    try {
      objectId = data.attribute.objectId.split(':').filter(item => item);
    } catch (e) {
      console.log(e);
      console.log('objectId解析错误');
    }
    const defaultParams = {
      //来自公共参数
      productConnect: commonParams.connect,
      connect: commonParams.connect,
      lang: commonParams.lang,
      companyId: commonParams.companyId,
      user_id: commonParams.userId,
      formParams: {
        productConnect: commonParams.connect,
      },

      // objectId: 'P_SYS_CODE_SCHEME:CODETEST', //数据
      //组件用
      modelName: objectId[0],
      compentField: objectId[1],
    };
    coderSelect({ ...params, ...defaultParams }, pageData, data, originData);
  } else {
    // 自定义弹出页面
    pageSelect(params, pageData, data, originData);
  }
};
