import {
  addNeConfigData,
  delNeConfigData,
  editNeConfigData,
} from '@/api/ne/neConfig';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { Modal, message } from 'ant-design-vue/es';
import { SizeType } from 'ant-design-vue/es/config-provider';
import { reactive, watch } from 'vue';

/**
 * 参数配置array类型
 * @param param 父级传入 { t, treeState, neTypeSelect, neIdSelect, fnActiveConfigNode, ruleVerification, modalState, fnModalCancel}
 * @returns
 */
export default function useConfigArray({
  t,
  treeState,
  neTypeSelect,
  neIdSelect,
  fnActiveConfigNode,
  ruleVerification,
  modalState,
  fnModalCancel,
}: any) {
  /**多列列表状态类型 */
  type ArrayStateType = {
    /**紧凑型 */
    size: SizeType;
    /**多列嵌套记录字段 */
    columns: Record<string, any>[];
    /**表格字段列排序 */
    columnsDnd: Record<string, any>[];
    /**多列记录数据 */
    columnsData: Record<string, any>[];
    /**多列嵌套展开key */
    arrayChildExpandKeys: any[];

    /**多列记录数据 */
    data: Record<string, any>[];
    /**多列记录规则 */
    dataRule: Record<string, any>;
  };

  /**多列列表状态 */
  let arrayState: ArrayStateType = reactive({
    size: 'small',
    columns: [],
    columnsDnd: [],
    columnsData: [],
    arrayChildExpandKeys: [],
    data: [],
    dataRule: {},
  });

  /**多列表编辑 */
  function arrayEdit(rowIndex: Record<string, any>) {
    const item = arrayState.data.find((s: any) => s.key === rowIndex.value);
    if (!item) return;
    const from = arrayInitEdit(item, arrayState.dataRule);
    // 处理信息
    const row: Record<string, any> = {};
    for (const v of from.record) {
      if (Array.isArray(v.array)) {
        continue;
      }
      row[v.name] = Object.assign({}, v);
    }

    // 特殊SMF-upfid选择
    if (neTypeSelect.value[0] === 'SMF' && Reflect.has(row, 'upfId')) {
      const v = row.upfId.value;
      if (typeof v === 'string') {
        if (v === '') {
          row.upfId.value = [];
        } else if (v.includes(';')) {
          row.upfId.value = v.split(';');
        } else if (v.includes(',')) {
          row.upfId.value = v.split(',');
        } else {
          row.upfId.value = [v];
        }
      }
    }

    modalState.from = row;
    modalState.type = 'arrayEdit';
    modalState.title = `${treeState.selectNode.paramDisplay} ${from.title}`;
    modalState.key = from.key;
    modalState.data = from.record.filter((v: any) => !Array.isArray(v.array));
    modalState.open = true;

    // 关闭嵌套
    arrayState.arrayChildExpandKeys = [];
  }

  /**多列表编辑关闭 */
  function arrayEditClose() {
    arrayState.arrayChildExpandKeys = [];
    fnModalCancel();
  }

  /**多列表编辑确认 */
  function arrayEditOk(from: Record<string, any>) {
    const loc = `${from['index']['value']}`;

    // 特殊SMF-upfid选择
    if (neTypeSelect.value[0] === 'SMF' && Reflect.has(from, 'upfId')) {
      const v = from.upfId.value;
      if (Array.isArray(v)) {
        from.upfId.value = v.join(';');
      }
    }

    // 遍历提取属性和值
    let data: Record<string, any> = {};
    for (const key in from) {
      // 子嵌套的不插入
      if (from[key]['array']) {
        continue;
      }
      // 检查规则
      const [ok, msg] = ruleVerification(from[key]);
      if (!ok) {
        message.warning({
          content: `${msg}`,
          duration: 3,
        });
        return;
      }
      data[key] = from[key]['value'];
    }

    // 请求
    const reqArr = [];
    if (neTypeSelect.value[1].startsWith('SYNC')) {
      for (const neId of neIdSelect.value) {
        reqArr.push(
          editNeConfigData({
            neType: neTypeSelect.value[0],
            neId: neId,
            paramName: treeState.selectNode.paramName,
            paramData: data,
            loc: loc,
          })
        );
      }
    } else {
      reqArr.push(
        editNeConfigData({
          neType: neTypeSelect.value[0],
          neId: neTypeSelect.value[1],
          paramName: treeState.selectNode.paramName,
          paramData: data,
          loc: loc,
        })
      );
    }
    // 无请求提示
    if (reqArr.length === 0) {
      message.warning({
        content: t('views.ne.neConfig.neIdSyncPleace'),
        duration: 3,
      });
      arrayEditClose();
      return;
    }

    const hide = message.loading(t('common.loading'), 0);
    Promise.allSettled(reqArr)
      .then(resArr => {
        const rejected = resArr.find(res => res.status === 'rejected');
        if (rejected) {
          message.warning({
            content: t('views.ne.neConfig.updateItemErr'),
            duration: 3,
          });
        } else {
          message.success({
            content: t('views.ne.neConfig.updateItem', {
              num: modalState.title,
            }),
            duration: 3,
          });
        }
        const fulfilled = resArr.find(res => res.status === 'fulfilled');
        if (fulfilled) {
          fnActiveConfigNode('#');
        }
      })
      .finally(() => {
        hide();
        arrayEditClose();
      });
  }

  /**多列表删除单行 */
  function arrayDelete(rowIndex: Record<string, any>) {
    const loc = `${rowIndex.value}`;
    const title = `${treeState.selectNode.paramDisplay} Index-${loc}`;

    Modal.confirm({
      title: t('common.tipTitle'),
      content: t('views.ne.neConfig.delItemTip', {
        num: title,
      }),
      onOk() {
        // 请求
        const reqArr = [];
        if (neTypeSelect.value[1].startsWith('SYNC')) {
          for (const neId of neIdSelect.value) {
            reqArr.push(
              delNeConfigData({
                neType: neTypeSelect.value[0],
                neId: neId,
                paramName: treeState.selectNode.paramName,
                loc: loc,
              })
            );
          }
        } else {
          reqArr.push(
            delNeConfigData({
              neType: neTypeSelect.value[0],
              neId: neTypeSelect.value[1],
              paramName: treeState.selectNode.paramName,
              loc: loc,
            })
          );
        }
        // 无请求提示
        if (reqArr.length === 0) {
          message.warning({
            content: t('views.ne.neConfig.neIdSyncPleace'),
            duration: 3,
          });
          arrayEditClose();
          return;
        }

        const hide = message.loading(t('common.loading'), 0);
        Promise.allSettled(reqArr)
          .then(resArr => {
            const rejected = resArr.find(res => res.status === 'rejected');
            if (rejected) {
              message.error({
                content: `${rejected.reason}`,
                duration: 2,
              });
            } else {
              message.success({
                content: t('views.ne.neConfig.delItemOk', {
                  num: title,
                }),
                duration: 2,
              });
            }
            const fulfilled = resArr.find(res => res.status === 'fulfilled');
            if (fulfilled) {
              fnActiveConfigNode('#');
            }
          })
          .finally(() => {
            hide();
            arrayEditClose();
          });
      },
    });
  }

  /**多列表新增单行 */
  function arrayAdd() {
    const from = arrayInitAdd(arrayState.data, arrayState.dataRule);

    // 处理信息
    const row: Record<string, any> = {};
    for (const v of from.record) {
      if (Array.isArray(v.array)) {
        continue;
      }
      row[v.name] = Object.assign({}, v);
    }

    // 特殊SMF-upfid选择
    if (neTypeSelect.value[0] === 'SMF' && Reflect.has(row, 'upfId')) {
      const v = row.upfId.value;
      if (typeof v === 'string') {
        if (v === '') {
          row.upfId.value = [];
        } else if (v.includes(';')) {
          row.upfId.value = v.split(';');
        } else if (v.includes(',')) {
          row.upfId.value = v.split(',');
        } else {
          row.upfId.value = [v];
        }
      }
    }

    modalState.from = row;
    modalState.type = 'arrayAdd';
    modalState.title = `${treeState.selectNode.paramDisplay} ${from.title}`;
    modalState.key = from.key;
    modalState.data = from.record.filter((v: any) => !Array.isArray(v.array));
    modalState.open = true;
  }

  /**多列表新增单行确认 */
  function arrayAddOk(from: Record<string, any>) {
    // 特殊SMF-upfid选择
    if (neTypeSelect.value[0] === 'SMF' && Reflect.has(from, 'upfId')) {
      const v = from.upfId.value;
      if (Array.isArray(v)) {
        from.upfId.value = v.join(';');
      }
    }

    // 遍历提取属性和值
    let data: Record<string, any> = {};
    for (const key in from) {
      // 子嵌套的不插入
      if (from[key]['array']) {
        continue;
      }
      // 检查规则
      const [ok, msg] = ruleVerification(from[key]);
      if (!ok) {
        message.warning({
          content: `${msg}`,
          duration: 3,
        });
        return;
      }
      data[key] = from[key]['value'];
    }

    // 请求
    const reqArr = [];
    if (neTypeSelect.value[1].startsWith('SYNC')) {
      for (const neId of neIdSelect.value) {
        reqArr.push(
          addNeConfigData({
            neType: neTypeSelect.value[0],
            neId: neId,
            paramName: treeState.selectNode.paramName,
            paramData: data,
            loc: `${from['index']['value']}`,
          })
        );
      }
    } else {
      reqArr.push(
        addNeConfigData({
          neType: neTypeSelect.value[0],
          neId: neTypeSelect.value[1],
          paramName: treeState.selectNode.paramName,
          paramData: data,
          loc: `${from['index']['value']}`,
        })
      );
    }
    // 无请求提示
    if (reqArr.length === 0) {
      message.warning({
        content: t('views.ne.neConfig.neIdSyncPleace'),
        duration: 3,
      });
      arrayEditClose();
      return;
    }

    const hide = message.loading(t('common.loading'), 0);
    Promise.allSettled(reqArr)
      .then(resArr => {
        const rejected = resArr.find(res => res.status === 'rejected');
        if (rejected) {
          message.warning({
            content: t('views.ne.neConfig.addItemErr'),
            duration: 3,
          });
        } else {
          message.success({
            content: t('views.ne.neConfig.addItemOk', {
              num: modalState.title,
            }),
            duration: 3,
          });
        }
        const fulfilled = resArr.find(res => res.status === 'fulfilled');
        if (fulfilled) {
          fnActiveConfigNode('#');
        }
      })
      .finally(() => {
        hide();
        arrayEditClose();
      });
  }

  /**多列表编辑行数据初始化 */
  function arrayInitEdit(data: Record<string, any>, dataRule: any) {
    const dataFrom = data.record;
    const ruleFrom = Object.assign({}, JSON.parse(JSON.stringify(dataRule)));
    for (const row of ruleFrom.record) {
      // 子嵌套的不初始
      if (row.array) {
        row.value = [];
        continue;
      }
      // 查找项的值
      const item = dataFrom.find((s: any) => s.name === row.name);
      if (!item) {
        continue;
      }
      // 可选的
      row.optional = 'true';
      // 根据规则类型转值
      if (['enum', 'int'].includes(row.type)) {
        row.value = Number(item.value);
      } else if ('bool' === row.type) {
        row.value = Boolean(item.value);
      } else {
        row.value = item.value;
      }
    }
    ruleFrom.key = data.key;
    ruleFrom.title = data.title;
    return ruleFrom;
  }

  /**多列表新增行数据初始化 */
  function arrayInitAdd(data: any[], dataRule: any) {
    // 有数据时取得最后的index
    let dataLastIndex = 0;
    if (data.length !== 0) {
      const lastFrom = Object.assign(
        {},
        JSON.parse(JSON.stringify(data.at(-1)))
      );
      if (lastFrom.record.length > 0) {
        dataLastIndex = parseInt(lastFrom.key);
        dataLastIndex += 1;
      }
    }

    const ruleFrom = Object.assign({}, JSON.parse(JSON.stringify(dataRule)));
    for (const row of ruleFrom.record) {
      // 子嵌套的不初始
      if (row.array) {
        row.value = [];
        continue;
      }
      // 可选的
      row.optional = 'true';
      // index值
      if (row.name === 'index') {
        let newIndex =
          dataLastIndex !== 0 ? dataLastIndex : parseInt(row.value);
        if (isNaN(newIndex)) {
          newIndex = 0;
        }
        row.value = newIndex;
        ruleFrom.key = newIndex;
        ruleFrom.title = `Index-${newIndex}`;
        continue;
      }
      // 根据规则类型转值
      if (['enum', 'int'].includes(row.type)) {
        row.value = Number(row.value);
      }
      if ('bool' === row.type) {
        row.value = Boolean(row.value);
      }

      // 特殊SMF-upfid选择
      if (neTypeSelect.value[0] === 'SMF' && row.name === 'upfId') {
        const v = row.value;
        if (typeof v === 'string') {
          if (v === '') {
            row.value = [];
          } else if (v.includes(';')) {
            row.value = v.split(';');
          } else if (v.includes(',')) {
            row.value = v.split(',');
          } else {
            row.value = [v];
          }
        }
      }
    }
    return ruleFrom;
  }

  // 监听表格字段列排序变化关闭展开
  watch(
    () => arrayState.columnsDnd,
    () => {
      arrayEditClose();
    }
  );

  return {
    arrayState,
    arrayEdit,
    arrayEditClose,
    arrayEditOk,
    arrayDelete,
    arrayAdd,
    arrayAddOk,
    arrayInitEdit,
    arrayInitAdd,
  };
}
