/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-02 14:06:35
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { KCInput } from '@/components/KCInput';
import KCTable from '@/components/kcTable';
import { getAllHosp } from '@/service/hospList';
import { getUserRelaSeletData } from '@/service/user';
import { ModalForm, ProFormCascader, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Popconfirm } from 'antd';
import { useEffect, useState } from 'react';
import { getSysLists } from '../paramsMana/service';
import { addData, delData, editData, getData } from './service';

import './style.less';
import { findParents, renameChildListToChildren, searchTreeAndKeepStructure } from '@/utils';

export default function KcClassification() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<{
    current: number;
    pageSize: number;
    name?: string;
  }>({
    current: 1,
    pageSize: 10
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
  const [reload, set_reload] = useState(false);
  const [currentEdit, set_currentEdit] = useState<any>(undefined);
  const [tableData, set_tableData] = useState<any[]>([]);
  const [dataSource, set_dataSource] = useState<any[]>([]);

  const columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
    },
    {
      title: '分类代码',
      dataIndex: 'code',
    },
    {
      title: '序号',
      dataIndex: 'sort',
    },
    {
      title: '说明',
      dataIndex: 'description',
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <Popconfirm title="是否确认删除？" key="del" onConfirm={() => delTableData(record)}>
            <a>删除</a>
          </Popconfirm>,
          <UpDataActBtn key={'act2'} record={record} type="ADDCHILD" />,
        ];
      },
    },
  ];

  const getTableData = async (params?: any) => {
    const resp = await getData();
    set_reload(false);
    if (resp) {
      const data = renameChildListToChildren(resp, 'childList');
      set_tableData(data);
      set_dataSource(data);
      
      // 处理分页
      const { current = 1, pageSize = 10, name } = params || {};
      const start = (current - 1) * pageSize;
      const end = start + pageSize;
      const filteredData = name ? searchTreeAndKeepStructure(data, 'name', name) : data;
      
      return {
        data: filteredData.slice(start, end),
        success: true,
        total: filteredData.length
      };
    }
    return {
      data: [],
      success: false,
      total: 0
    };
  };

  const delTableData = async (record: any) => {
    const resp = await delData(record.id);
    if (resp) {
      set_reload(true);
      // message.success('操作成功!');
    }
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD' | 'ADDCHILD') => {
    // const parents = findParents(tableData, 'id', formVal.id);
    // console.log({formVal});
    const result = {
      code: formVal.code,
      name: formVal.name,
      value: '',
      sort: formVal.sort,
      description: formVal.description,
    };
    if (type == 'ADD') {
      const resp = await addData({
        ...result,
        parentCode: undefined,
        codePath: formVal.code,
        levelName: formVal.name,
      });
      if (resp) {
        set_reload(true);
      }
    }
    if (type == 'ADDCHILD') {
      const resp = await addData({
        ...result,
        parentCode: formVal.parentCode,
        codePath: `${formVal.codePath},${formVal.code}`,
        levelName: `${formVal.levelName}/${formVal.name}`,
      });
      if (resp) {
        set_reload(true);
      }
    }
    if (type == 'EDIT') {
      // const parents = findParents(tableData,'id',formVal.id);
      // console.log({parents});

      const resp = await editData({
        ...result,
        id: formVal.id,
      });
      if (resp) {
        set_reload(true);
      }
    }
  };

  const UpDataActBtn = ({ record, type }: { record: any; type: 'EDIT' | 'ADD' | 'ADDCHILD' }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : type == 'ADDCHILD' ? '添加' : '新增'}康程分类`}
        width={350}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
              }
            : {}
        }
        trigger={type == 'EDIT' ? <a key="edit">编辑</a> : <a className="add">{type == 'ADDCHILD' ? '添加' : '新增'}</a>}
        onFinish={(val) => {
          return updateTable(type == 'EDIT' ? { ...val, id: record.id } : type == 'ADDCHILD' ? { ...record, ...val, parentCode: record.code } : { ...val }, type);
        }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormText name="name" label="分类名称：" placeholder="请输入" rules={[{ required: true, message: '名称不能为空!' }]} />
        <ProFormText name="code" label="分类代码：" placeholder="请输入" rules={[{ required: true, message: '代码不能为空!' }]} />
        <ProFormDigit name="sort" label="序号：" placeholder="请输入" rules={[{ required: true, message: '序号不能为空!' }]} />
        <ProFormTextArea colProps={{ span: 24 }} name="description" label="说明：" placeholder="请输入" />
      </ModalForm>
    );
  };

  const handleTableChange = (pagination: any) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: pagination.current,
      pageSize: pagination.pageSize
    });
  }

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: 1,
      [`${paramName}`]: tableDataSearchKeywords
    });
  }

  useEffect(() => {
    if (reload) {
      getTableData();
    }
  }, [reload]);

  useEffect(() => {
    if (tableDataFilterParams) {
      const { name } = tableDataFilterParams;
      const result = searchTreeAndKeepStructure(dataSource, 'name', name);
      set_tableData([...result]);
    } else {
      set_tableData(dataSource);
    }
  }, [tableDataFilterParams]);

  useEffect(() => {
    getTableData();
  }, []);

  return (
    <div className="KcClassification">
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem">
            <span className="label">分类名称：</span>
            <KCInput
              placeholder={'请输入'}
              style={{ width: 160 }}
              search
              allowClear
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    current:1,
                    name: '',
                  });
                }
              }}
              onSearch={() => tableDataSearchHandle('name')}
            />
          </div>
        </div>
        <div className="btnGroup">
          <UpDataActBtn record type="ADD" />
        </div>
      </div>
      <div style={{ marginTop: 16 }}>
        <KCTable
          columns={columns}
          scroll={{ y: `calc(100vh - 250px)` }}
          reload={reload}
          rowKey="id"
          newVer
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
          onChange={handleTableChange}
        />
      </div>
    </div>
  );
}
