/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:46:47
 * @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 { createFromIconfontCN } from '@ant-design/icons';
import { ActionType } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import {
  Dropdown,
  Input,
  MenuProps,
  message,
  Form,
  Tooltip,
  Popconfirm,
} from 'antd';

import { Key } from 'react';
import { useEffect, useRef, useState } from 'react';

import {
  getOrderList,
  getOrderItemList,
  addLeftList,
  editLeftList,
  delLeftList,
  batchDelTableData,
  addTableData,
  delData,
  getOrderType,
  importLeftListData,
  editTableData,
} from './service';

import './style.less';

import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from 'react-sortable-hoc';

import '../../../../utils/zhongtaiB';
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { getTargetDic } from '@/services/auth';
import TableSelecter from './tableSelector';
import { downloadTemplateReq } from '@/utils/tooljs';
import KCIMUpload from '@/components/KCIMUpload';
const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

let _currentSelectedType: any = undefined;

const MedicalOrderProjectMana = () => {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const [selectedRowKeys, set_selectedRowKeys] = useState<Key[]>([]);
  const [typeList, set_typeList] = useState<any[]>([]);
  const [showTypeListArr, set_showTypeListArr] = useState<any[]>([]);
  const [currentSelectedType, set_currentSelectedType] = useState<
    any | undefined
  >(undefined);

  const [tableSelecterVisible, set_tableSelecterVisible] = useState(false);

  const [currentEditLeftData, set_currentEditLeftData] = useState<
    any | undefined
  >(undefined);

  const [currentEditRow, set_currentEditRow] = useState<undefined | any>(
    undefined,
  );

  const [leftDataSearchKeyVal, set_leftDataSearchKeyVal] = useState<
    undefined | string
  >(undefined);

  const tableRef = useRef<ActionType>();

  const [orderType, set_orderType] = useState<undefined | string>(undefined);

  const column: ProColumns[] = [
    {
      title: '收费项目代码',
      ellipsis: true,
      width: 120,
      dataIndex: 'itemCode',
    },
    {
      title: '收费项目名称',
      dataIndex: 'itemName',
    },
    {
      title: '收费项目类别',
      width: 100,
      dataIndex: 'itemTypeName',
    },
    {
      title: '数量',
      dataIndex: 'num',
      width: 100,
      renderText(num, record, index, action) {
        return (
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
            }}
          >
            {currentEditRow && currentEditRow.id == record.id && (
              <>
                <ProFormDigit
                  width={80}
                  noStyle
                  fieldProps={{
                    value: num,
                    onChange(value) {
                      set_currentEditRow({ ...record, num: value ? value : 0 });
                    },
                  }}
                />
                <img
                  onClick={() => updateTable({ ...record }, 'EDIT')}
                  style={{
                    width: 16,
                    height: 16,
                    display: 'inline-block',
                    marginLeft: 8,
                    cursor: 'pointer',
                  }}
                  src={require('../../../../../static/confirmIcon.png')}
                />
              </>
            )}

            {(!currentEditRow ||
              (currentEditRow && currentEditRow.id != record.id)) && (
              <>
                <div>{num}</div>
                <img
                  onClick={() => set_currentEditRow(record)}
                  style={{
                    width: 16,
                    height: 16,
                    display: 'inline-block',
                    marginLeft: 8,
                    cursor: 'pointer',
                  }}
                  src={require('../../../../../static/editIcon.png')}
                />
              </>
            )}
          </div>
        );
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 60,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record.id)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getOrderItemList({ ...params });
    if (resp) {
      return {
        data: resp.list,
        success: true,
        total: resp.totalCount,
        pageSize: resp.pageSize,
        totalPage: resp.totalPage,
      };
    } else {
      return [];
    }
  };

  //获取左侧列表
  const getPageLeftReports = async (orderType?: string) => {
    const resp = await getOrderList(orderType);

    if (resp) {
      set_typeList(resp);
      set_showTypeListArr(resp);
    }
  };

  const delTableData = async (id: number) => {
    const resp = await delData(id);
    if (resp) {
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  const batchDelHandle = async () => {
    const resp = await batchDelTableData(selectedRowKeys);
    if (resp) {
      message.success('操作成功！');
      set_selectedRowKeys([]);
      tableRef.current?.reload();
    }
  };

  const tableSelecterCommit = async (keys: Key[], rows: any[]) => {
    const arr = rows.map((a, index) => ({
      itemCode: a.itemCode,
      itemName: a.itemName,
      itemType: a.itemType,
    }));
    const result = {
      orderCode: currentSelectedType.code,
      items: arr,
    };
    const resp = await addTableData(result);
    if (resp) {
      message.success('操作成功');
      set_tableSelecterVisible(false);
      tableRef.current?.reload();
    }
  };

  const updateTable = async (
    formVal: any,
    type: 'EDIT' | 'ADD' | 'ADD_LEFTDATA' | 'EDIT_LEFTDATA',
    data?: any[],
  ) => {
    // console.log({formVal,type});

    if (type == 'ADD_LEFTDATA') {
      const resp = await addLeftList({
        name: formVal.name,
        type: formVal.type,
        code: formVal.code,
        description: formVal.description,
      });
      if (resp) {
        getPageLeftReports();
      }
    }

    if (type == 'EDIT_LEFTDATA') {
      const resp = await editLeftList({
        id: formVal.id,
        name: formVal.name,
        code: formVal.code,
        type: formVal.type,
        description: formVal.description,
      });
      if (resp) {
        getPageLeftReports();
      }
    }

    if (type == 'EDIT') {
      const resp = await editTableData({
        id: formVal.id,
        orderCode: currentSelectedType.code,
        itemCode: formVal.itemCode,
        num: currentEditRow.num,
      });

      if (resp) {
        tableRef.current?.reload();
      }
    }

    set_currentEditRow(undefined);

    return true;
  };

  const downloadTemplate = async () => {
    await downloadTemplateReq('/costAccount/setting/exportOrder');
  };

  const importData = () => {
    return (
      <ModalForm
        width={360}
        title={`导入数据`}
        trigger={
          <a className="import" key="3">
            导入
          </a>
        }
        submitter={{
          render: (props, defaultDoms) => {
            const needBtn = defaultDoms.filter((b) => {
              return b.key != 'rest';
            });
            return [...needBtn];
          },
        }}
        onFinish={async (values) => {
          const {
            importFile: { fileList },
          } = values;

          let formData = new FormData();
          formData.append('file', fileList[0].originFileObj);
          const resp = await importLeftListData(formData);

          if (resp) {
            getPageLeftReports();
            return true;
          }
        }}
      >
        <Form.Item name={'importFile'}>
          <KCIMUpload downloadTemplateFile={() => downloadTemplate()} />
        </Form.Item>
      </ModalForm>
    );
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD' | 'ADD_LEFTDATA' | 'EDIT_LEFTDATA';
  }) => {
    const getTrriger = () => {
      if (type == 'ADD') {
        return <span className="add">新增</span>;
      }
      if (type == 'EDIT') {
        return <a key="edit">编辑</a>;
      }
      if (type == 'ADD_LEFTDATA') {
        return <a key="edit">新增</a>;
      }
      if (type == 'EDIT_LEFTDATA') {
        return <a key="edit">编辑</a>;
      }
    };

    return (
      <ModalForm
        title={type == 'ADD_LEFTDATA' ? `新增医嘱项目` : `编辑医嘱项目`}
        width={352}
        initialValues={type == 'EDIT_LEFTDATA' ? { ...record } : {}}
        trigger={getTrriger()}
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT_LEFTDATA' ? { ...record, ...val } : val,
            type,
          );
        }}
      >
        <ProFormText
          label="医嘱项目代码："
          name="code"
          rules={[{ required: true, message: '医嘱项目代码不能为空!' }]}
        />
        <ProFormText
          label="医嘱项目名称："
          name="name"
          rules={[{ required: true, message: '医嘱项目名称不能为空!' }]}
        />
        <ProFormSelect
          name="type"
          label="医嘱项目类别："
          placeholder="请选择"
          request={async () => {
            const resp = await getOrderType();
            if (resp) {
              return resp.map((a: any) => ({ label: a.name, value: a.code }));
            }
            return [];
          }}
          rules={[{ required: true, message: '医嘱项目类别不能为空!' }]}
        />
        <ProFormTextArea label="说明：" name="description" />
      </ModalForm>
    );
  };

  const optItems: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <UpDataActBtn key={'act'} record={undefined} type="ADD_LEFTDATA" />
      ),
    },
    {
      key: '2',
      label: importData(),
    },
  ];
  const moreItems: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <UpDataActBtn
          key={'act'}
          record={currentEditLeftData}
          type="EDIT_LEFTDATA"
        />
      ),
    },
    {
      key: '2',
      label: (
        <a
          onClick={async (e) => {
            e.preventDefault();
            const resp = await delLeftList(currentEditLeftData.id);
            if (resp) {
              getPageLeftReports();
            }
          }}
        >
          删除
        </a>
      ),
    },
  ];

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

  useEffect(() => {
    if (currentSelectedType) {
      set_tableDataFilterParams({
        ...tableDataFilterParams,
        orderCode: currentSelectedType.code,
      });
    }
  }, [currentSelectedType]);

  useEffect(() => {
    if (showTypeListArr.length > 0) {
      set_currentSelectedType(showTypeListArr[0]);
      _currentSelectedType = showTypeListArr[0];
      // set_tableDataFilterParams({ ...tableDataFilterParams, orderCode: showTypeListArr[0].code });
    }
  }, [showTypeListArr]);

  useEffect(() => {
    const result = typeList.filter(
      (item) => item.name.indexOf(leftDataSearchKeyVal) != -1,
    );
    set_showTypeListArr(result);
  }, [leftDataSearchKeyVal]);

  useEffect(() => {
    if (orderType != '-1') {
      getPageLeftReports(orderType);
    } else {
      getPageLeftReports();
    }
  }, [orderType]);

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

  return (
    <KCIMPagecontainer title={false} className="MedicalOrderProjectMana">
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="添加"
        rowKey={'itemCode'}
        defaultSelectedKeys={[]}
        record={_currentSelectedType}
        open={tableSelecterVisible}
        onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
      />
      {selectedRowKeys.length > 0 && (
        <div className="bottomBar">
          <span>
            已选择<a>{selectedRowKeys.length}</a>项
          </span>
          <a onClick={() => batchDelHandle()}>批量删除</a>
        </div>
      )}
      <div className="left">
        <div style={{ padding: '0 8px' }}>
          <ProFormSelect
            noStyle
            style={{ width: '100%', marginBottom: 8 }}
            placeholder="选择医嘱类型"
            fieldProps={{
              defaultValue: -1,
              onChange(value, option) {
                set_leftDataSearchKeyVal(undefined);
                set_orderType(`${value}`);
              },
            }}
            request={async () => {
              const resp = await getOrderType();
              if (resp) {
                const arr = resp.map((a: any) => ({
                  label: a.name,
                  value: a.code,
                }));
                return [{ label: '全部医嘱类型', value: -1 }, ...arr];
              }
              return [{ label: '全部医嘱类型', value: -1 }];
            }}
          />
        </div>
        <div className="toolbar">
          <Input
            placeholder={'报表名称'}
            allowClear
            autoComplete="off"
            suffix={<IconFont type="iconsousuo" style={{ color: '#99A6BF' }} />}
            value={leftDataSearchKeyVal}
            style={{ width: 156 }}
            onChange={(e) => {
              set_leftDataSearchKeyVal(e.target.value);
            }}
          />
          <Dropdown menu={{ items: optItems }} placement="bottom">
            <div className="add">
              <img
                src={require('../../../../../static/addIcon_black.png')}
                alt=""
              />
            </div>
          </Dropdown>
        </div>

        <div className="wrap">
          {showTypeListArr.map((item, index) => {
            return (
              <div
                className={
                  currentSelectedType
                    ? currentSelectedType.id == item.id
                      ? 'type on'
                      : 'type'
                    : 'type'
                }
                key={index}
                onClick={() => {
                  set_currentSelectedType(item);
                  _currentSelectedType = item;
                }}
              >
                <img
                  className="icon"
                  src={require('../../../../../static/reportIcon.png')}
                  alt=""
                />
                <div className="content">
                  <Tooltip title={item.name}>
                    <div className="name">{item.name}</div>
                    <div className="sub">{item.typeName}</div>
                  </Tooltip>
                </div>

                <Dropdown
                  menu={{ items: moreItems }}
                  placement="bottom"
                  onOpenChange={(bool) => {
                    bool && set_currentEditLeftData(item);
                  }}
                >
                  <div className="more">
                    <img
                      src={require('../../../../../static/more_point_gray.png')}
                      alt=""
                    />
                  </div>
                </Dropdown>
              </div>
            );
          })}
        </div>
      </div>
      <div className="right">
        <div className="toolBar">
          <div className="filter">
            <div className="filterItem">
              <span className="label" style={{ whiteSpace: 'nowrap' }}>
                {' '}
                项目名称：
              </span>
              <Input
                placeholder={'请输入'}
                allowClear
                autoComplete="off"
                suffix={
                  <IconFont
                    type="iconsousuo"
                    style={{ color: '#99A6BF' }}
                    onClick={() => tableDataSearchHandle('itemName')}
                  />
                }
                onChange={(e) => {
                  set_tableDataSearchKeywords(e.target.value);
                  if (e.target.value.length == 0) {
                    set_tableDataFilterParams({
                      ...tableDataFilterParams,
                      itemName: '',
                    });
                  }
                }}
                onPressEnter={(e) => {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    itemName: (e.target as HTMLInputElement).value,
                  });
                }}
              />
            </div>
          </div>
          <div className="btnGroup">
            <span
              className="add"
              onClick={() => set_tableSelecterVisible(true)}
            >
              添加
            </span>
          </div>
        </div>
        <div style={{ marginTop: 16 }}>
          {currentSelectedType && (
            <KCIMTable
              actionRef={tableRef}
              columns={column}
              scroll={{ y: `calc(100vh - 233px)` }}
              rowKey="id"
              params={tableDataFilterParams}
              request={(params) => getTableData(params)}
              tableAlertRender={false}
              rowSelection={{
                onChange(selectedRowKeys, selectedRows, info) {
                  set_selectedRowKeys(selectedRowKeys);
                },
              }}
            />
          )}
        </div>
      </div>
    </KCIMPagecontainer>
  );
};

export default MedicalOrderProjectMana;
