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

/**
 * list类型参数处理
 * @param param 父级传入 {t, treeState, neTypeSelect, neIdSelect, ruleVerification}
 * @returns
 */
export default function useConfigList({
  t,
  treeState,
  neTypeSelect,
  neIdSelect,
  ruleVerification,
}: any) {
  /**单列表状态类型 */
  type ListStateType = {
    /**紧凑型 */
    size: SizeType;
    /**单列记录字段 */
    columns: Record<string, any>[];
    /**单列记录数据 */
    data: Record<string, any>[];
    /**编辑行记录 */
    editRecord: Record<string, any>;
    /**确认提交等待 */
    confirmLoading: boolean;
  };

  /**单列表状态 */
  let listState: ListStateType = reactive({
    size: 'small',
    columns: [
      {
        title: 'Key',
        dataIndex: 'display',
        align: 'left',
        width: '30%',
      },
      {
        title: 'Value',
        dataIndex: 'value',
        align: 'left',
        width: '70%',
      },
    ],
    data: [],
    confirmLoading: false,
    editRecord: {},
  });

  /**单列表编辑 */
  function listEdit(row: Record<string, any>) {
    if (
      listState.confirmLoading ||
      ['read-only', 'read', 'ro'].includes(row.access)
    ) {
      return;
    }

    listState.editRecord = Object.assign({}, row);
  }

  /**单列表编辑关闭 */
  function listEditClose() {
    listState.confirmLoading = false;
    listState.editRecord = {};
  }

  /**单列表编辑确认 */
  function listEditOk() {
    if (listState.confirmLoading) return;
    const from = toRaw(listState.editRecord);
    // 检查规则
    const [ok, msg] = ruleVerification(from);
    if (!ok) {
      message.warning({
        content: `${msg}`,
        duration: 3,
      });
      return;
    }

    // 请求
    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: {
              [from['name']]: from['value'],
            },
          })
        );
      }
    } else {
      reqArr.push(
        editNeConfigData({
          neType: neTypeSelect.value[0],
          neId: neTypeSelect.value[1],
          paramName: treeState.selectNode.paramName,
          paramData: {
            [from['name']]: from['value'],
          },
        })
      );
    }
    // 无请求提示
    if (reqArr.length === 0) {
      message.warning({
        content: t('views.ne.neConfig.neIdSyncPleace'),
        duration: 3,
      });
      listState.confirmLoading = false;
      listState.editRecord = {};
      return;
    }

    listState.confirmLoading = true;
    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.updateValueErr'),
            duration: 3,
          });
        } else {
          message.success({
            content: t('views.ne.neConfig.updateValue', {
              num: from['display'],
            }),
            duration: 3,
          });
        }
        const fulfilled = resArr.find(res => res.status === 'fulfilled');
        if (fulfilled) {
          // 改变表格数据
          const item = listState.data.find(
            (item: Record<string, any>) => from['name'] === item['name']
          );
          if (item) {
            Object.assign(item, listState.editRecord);
          }
        }
      })
      .finally(() => {
        hide();
        listState.confirmLoading = false;
        listState.editRecord = {};
      });
  }

  /**表格分页器参数 */
  let tablePagination = reactive({
    /**当前页数 */
    current: 1,
    /**每页条数 */
    pageSize: 10,
    /**默认的每页条数 */
    defaultPageSize: 10,
    /**指定每页可以显示多少条 */
    pageSizeOptions: ['10', '20', '50', '100'],
    /**只有一页时是否隐藏分页器 */
    hideOnSinglePage: true,
    /**是否可以快速跳转至某页 */
    showQuickJumper: true,
    /**是否可以改变 pageSize */
    showSizeChanger: true,
    /**数据总数 */
    total: 0,
    showTotal: (total: number) => t('common.tablePaginationTotal', { total }),
    onChange: (page: number, pageSize: number) => {
      tablePagination.current = page;
      tablePagination.pageSize = pageSize;
    },
  });

  return { tablePagination, listState, listEdit, listEditClose, listEditOk };
}
