<script setup lang="tsx">
import { PropType, reactive, ref, unref, watch } from 'vue';
import { TableData } from '@/api/csck/CsckDataCheckResultComment/types';
import { Table, TableColumn } from '@/components/Table';
import { Form, FormSchema } from '@/components/Form';
import { useTable } from '@/hooks/web/useTable';
import { exportCommentsExcelByRuleApi, getCsckCommentsListApi, getCsckCommentsSubListApi } from '@/api/csck/CsckDataCheckResultComment';
import { SpanMethodProps } from '@/api/csck/CsckDataCheckResult/types';
import { ElButton } from 'element-plus';
import { ContentWrap } from '@/components/ContentWrap';
import { organTreeApi } from '@/api/system/SysUser';
import { ORGAN_DICT_LIST } from '../constants';
import { useValidator } from '@/hooks/web/useValidator';
import { useForm } from '@/hooks/web/useForm';
import { getLoginOrganCodeByUserInfo } from '@/utils/auth';
import { randomCode } from '@/utils';
import { isNotEmpty } from '@/utils/is';

const { required } = useValidator();

// 获取当前用户机构号
const loginOrganCode = getLoginOrganCodeByUserInfo();
const props = defineProps({
  currentRow: {
    type: Object as PropType<TableData>,
    default: () => {},
  },
});

// 根据数据判断行合并
const RowSpanByData = function (data, setRandomCode = false) {
  let rowspan = 0;
  let orgName = '';
  let item;
  let _list = data;
  // 判断行合并
  for (let i = 0; i < data.length; i++) {
    rowspan = 1;
    item = data[i];
    if (setRandomCode) {
      item.randomCode = randomCode(32);
    }
    orgName = item.orgname ?? '';
    // 被合并的下标需要被过滤
    if (!item.hasChildren && orgName) {
      for (let id = i + 1; id < _list.length; id++) {
        if (!item.hasChildren && orgName === _list[id].orgname) {
          // 被合并的单元格设置为0
          _list[id]._rowspan = 0;
          rowspan += 1;
          i++;
        } else {
          break;
        }
      }
    }
    if (rowspan > 1) {
      item._rowspan = rowspan;
    }
  }
  return data;
};

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState;
    const res = await getCsckCommentsListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      loginOrganCode: unref(loginOrganCode),
      ...props.currentRow,
    });
    // 判断是否有下级
    const list = res.body.list.map((item: TableData) => {
      item.randomCode = randomCode(32);
      // 判断是否有下级
      if (item.subOrgan && item.subOrgan === 'true') {
        item.hasChildren = true;
      } else {
        item.hasChildren = false;
      }
      return item;
    });

    const _list = RowSpanByData(list);
    return {
      list: _list,
      total: res.body.total,
    };
  },
  immediate: false,
});
const { loading, dataList, total, currentPage, pageSize } = tableState;
const { refresh, getList } = tableMethods;
/** 按规则导出情况说明Excel */
const exportCommentsExcelByRule = async () => {
  const data = { fileName: '按规则导出情况说明', pkid: props.currentRow.pkid, dataDate: props.currentRow.dataDate, loginOrganCode: loginOrganCode };
  exportCommentsExcelByRuleApi(data);
};
const tableColumns: TableColumn[] = [
  {
    field: 'orgname',
    label: '机构',
    headerAlign: 'center',
    align: 'center',
  },
  {
    field: 'orgcode',
    hidden: true,
  },
  {
    field: 'dataDate',
    hidden: true,
  },
  {
    field: 'comment',
    label: '情况说明',
    headerAlign: 'center',
    align: 'center',
  },
  {
    field: 'systemGroup',
    label: '系统组',
    headerAlign: 'center',
    align: 'center',
    formatter: (row: Recordable) => {
      return <div class={{ 'pre-wrap': true }}>{row.systemGroup + row.commentTime}</div>;
    },
  },
];

const disabled = ref(true);
const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0;
};

const { formRegister, formMethods } = useForm();
const { setValues, getFormData, getElFormExpose } = formMethods;
const formSchema = reactive<FormSchema[]>([
  {
    field: 'pkid',
    label: '主键',
    component: 'Input',
    hidden: true,
    value: props.currentRow.pkid,
  },
  {
    field: 'organCode',
    label: '机构',
    component: 'TreeSelect',
    optionApi: async () => {
      const res = await organTreeApi({
        treeid: '1',
        systemCode: 'portal',
        loginOrganCode
      });
      return res.body.result;
    },
    componentProps: {
      filterable: true,
      checkStrictly: true,
      showCheckbox: true,
      nodeKey: 'id',
      props: { children: 'childs', label: 'nodeName' },
    },
  },
  {
    field: 'grade',
    label: '机构层级',
    component: 'RadioGroup',
    componentProps: {
      options: ORGAN_DICT_LIST,
    },
    value: '2',
  },
  {
    field: 'comment',
    label: '添加说明',
    component: 'Input',
    colProps: {
      span: 24,
    },
    componentProps: { type: 'textarea' },
  },
]);

/** 数据加载 */
const load = async (row: TableData, __: any, resolve: (date: TableData[]) => void) => {
  const formData = {
    orgCode: row.orgcode,
    pkid: props.currentRow.pkid,
    dataDate: row.dataDate,
  };
  const res = await getCsckCommentsSubListApi(formData);
  if (res) {
    const data = res?.body?.list;
    const list = RowSpanByData(data, true);
    resolve(list);
  }
};

const rules = reactive({
  organCode: [required()],
  comment:[required()]
});

const submit = async () => {
  const elForm = await getElFormExpose();
  const valid = await elForm?.validate().catch(err => {
    console.log(err);
  });
  if (valid) {
    const formData = await getFormData();
    return formData;
  }
};

const resetField = async () => {
  const elFormExpose = await getElFormExpose();
  elFormExpose?.resetFields();
};

watch(
  () => props.currentRow,
  currentRow => {
    if (!currentRow) return;
    setValues(currentRow);
    getList();
  },
  {
    deep: true,
    immediate: true,
  },
);

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 0) {
    const rowspan = row._rowspan;
    if (isNotEmpty(rowspan)) {
      if (rowspan && rowspan > 1) {
        return {
          rowspan: rowspan,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    } else {
      return {
        rowspan: 1,
        colspan: 1,
      };
    }
  }
};

defineExpose({
  submit,
  resetField,
  getList,
});
</script>

<template>
  <ContentWrap>
    <Table
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      default-expand-all
      border
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total,
      }"
      @selection-change="onSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
      row-key="randomCode"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :fullHeight="false"
      :span-method="objectSpanMethod"
    >
      <template #buttons>
        <ElButton type="primary" @click="exportCommentsExcelByRule()">{{ '按规则导出说明' }}</ElButton>
      </template>
    </Table>
    <Form :rules="rules" @register="formRegister" :schema="formSchema" />
  </ContentWrap>
</template>
