import {
  addNeConfigData,
  editNeConfigData,
  delNeConfigData,
} 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 { nextTick, reactive } from 'vue';

/**
 * 参数配置array类型的嵌套array
 * @param param 父级传入 { t, treeState, neTypeSelect, fnActiveConfigNode, ruleVerification, modalState, arrayState, arrayInitEdit, arrayInitAdd, arrayEditClose}
 * @returns
 */
export default function useConfigArrayChild({
  t,
  treeState,
  neTypeSelect,
  fnActiveConfigNode,
  ruleVerification,
  modalState,
  arrayState,
  arrayInitEdit,
  arrayInitAdd,
  arrayEditClose,
}: any) {
  /**多列嵌套列表状态类型 */
  type ArrayChildStateType = {
    /**标题 */
    title: string;
    /**层级index */
    loc: string;
    /**紧凑型 */
    size: SizeType;
    /**多列嵌套记录字段 */
    columns: Record<string, any>[];
    /**表格字段列排序 */
    columnsDnd: Record<string, any>[];
    /**多列记录数据 */
    columnsData: Record<string, any>[];

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

  /**多列嵌套表格状态 */
  let arrayChildState: ArrayChildStateType = reactive({
    title: '',
    loc: '',
    size: 'small',
    columns: [],
    columnsDnd: [],
    columnsData: [],
    data: [],
    dataRule: {},
  });

  /**多列表展开嵌套行 */
  function arrayChildExpand(
    indexRow: Record<string, any>,
    row: Record<string, any>
  ) {
    const loc = indexRow.value;
    if (arrayChildState.loc === `${loc}/${row.name}`) {
      arrayChildState.loc = '';
      arrayState.arrayChildExpandKeys = [];
      return;
    }
    arrayChildState.loc = '';
    arrayState.arrayChildExpandKeys = [];
    const from = Object.assign({}, JSON.parse(JSON.stringify(row)));
    // 无数据时
    if (!Array.isArray(from.value)) {
      from.value = [];
    }
    const dataArr = Object.freeze(from.value);
    const ruleArr = Object.freeze(from.array);

    // 列表项数据
    const dataArray: Record<string, any>[] = [];
    for (const item of dataArr) {
      const index = item['index'];
      let record: Record<string, any>[] = [];
      for (const key of Object.keys(item)) {
        // 规则为准
        for (const rule of ruleArr) {
          if (rule['name'] === key) {
            const ruleItem = Object.assign({ optional: 'true' }, rule, {
              value: item[key],
            });
            record.push(ruleItem);
            break;
          }
        }
      }
      // dataArray.push(record);
      dataArray.push({ title: `Index-${index}`, key: index, record });
    }
    arrayChildState.data = dataArray;

    // 无数据时，用于新增
    arrayChildState.dataRule = {
      title: `Index-0`,
      key: 0,
      record: ruleArr,
    };

    // 列表数据
    const columnsData: Record<string, any>[] = [];
    for (const v of arrayChildState.data) {
      const row: Record<string, any> = {};
      for (const item of v.record) {
        row[item.name] = item;
      }
      columnsData.push(row);
    }
    arrayChildState.columnsData = columnsData;

    // 列表字段
    const columns: Record<string, any>[] = [];
    for (const rule of arrayChildState.dataRule.record) {
      columns.push({
        title: rule.display,
        dataIndex: rule.name,
        align: 'left',
        resizable: true,
        width: 50,
        minWidth: 50,
        maxWidth: 250,
      });
    }
    columns.push({
      title: t('common.operate'),
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      fixed: 'right',
      width: 100,
    });
    arrayChildState.columns = columns;

    nextTick(() => {
      // 设置展开key
      arrayState.arrayChildExpandKeys = [indexRow];
      // 层级标识
      arrayChildState.loc = `${loc}/${from['name']}`;
      // 设置展开列表标题
      arrayChildState.title = `${from['display']}`;
    });
  }

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

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

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

    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 hide = message.loading(t('common.loading'), 0);
    editNeConfigData({
      neType: neTypeSelect.value[0],
      neId: neTypeSelect.value[1],
      paramName: treeState.selectNode.paramName,
      paramData: data,
      loc,
    })
      .then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success({
            content: t('views.ne.neConfig.updateItem', {
              num: modalState.title,
            }),
            duration: 3,
          });
          fnActiveConfigNode('#');
        } else {
          message.warning({
            content: t('views.ne.neConfig.updateItemErr'),
            duration: 3,
          });
        }
      })
      .finally(() => {
        hide();
        arrayEditClose();
      });
  }

  /**多列表嵌套行删除单行 */
  function arrayChildDelete(rowIndex: Record<string, any>) {
    const index = rowIndex.value;
    const loc = `${arrayChildState.loc}/${index}`;
    const title = `${arrayChildState.title} Index-${index}`;

    Modal.confirm({
      title: t('common.tipTitle'),
      content: t('views.ne.neConfig.delItemTip', {
        num: title,
      }),
      onOk() {
        delNeConfigData({
          neType: neTypeSelect.value[0],
          neId: neTypeSelect.value[1],
          paramName: treeState.selectNode.paramName,
          loc,
        }).then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('views.ne.neConfig.delItemOk', {
                num: title,
              }),
              duration: 2,
            });
            arrayEditClose();
            fnActiveConfigNode('#');
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 2,
            });
          }
        });
      },
    });
  }

  /**多列表嵌套行新增单行 */
  function arrayChildAdd() {
    const from = arrayInitAdd(arrayChildState.data, arrayChildState.dataRule);
    // 处理信息
    const row: Record<string, any> = {};
    for (const v of from.record) {
      if (Array.isArray(v.array)) {
        continue;
      }
      row[v.name] = Object.assign({}, v);
    }

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

  /**多列表新增单行确认 */
  function arrayChildAddOk(from: Record<string, any>) {
    const loc = `${arrayChildState.loc}/${from['index']['value']}`;

    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 hide = message.loading(t('common.loading'), 0);
    addNeConfigData({
      neType: neTypeSelect.value[0],
      neId: neTypeSelect.value[1],
      paramName: treeState.selectNode.paramName,
      paramData: data,
      loc,
    })
      .then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success({
            content: t('views.ne.neConfig.addItemOk', {
              num: modalState.title,
            }),
            duration: 3,
          });
          fnActiveConfigNode('#');
        } else {
          message.warning({
            content: t('views.ne.neConfig.addItemErr'),
            duration: 3,
          });
        }
      })
      .finally(() => {
        hide();
        arrayEditClose();
      });
  }

  return {
    arrayChildState,
    arrayChildExpand,
    arrayChildEdit,
    arrayChildEditOk,
    arrayChildDelete,
    arrayChildAdd,
    arrayChildAddOk,
  };
}
