/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-02-21 13:32:53
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-01-08 16:22:26
 * @FilePath: /CostAccountingSys/src/pages/costLibraryManagement/projectCostManagement/chargeItemsMana/components/setting.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { KCIMTable } from '@/components/KCIMTable';
import {
  ActionType,
  ModalForm,
  ProColumns,
  ProFormCascader,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Tabs } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';
import { Popconfirm, message } from 'antd';
import {
  addDrawerTableData,
  addDrugTableData,
  batchDelDrugTableData,
  delDrawerTableData,
  editDrawerTableData,
  getEmpsByItemCode,
  getEquipByItemCode,
  getNoValuationDrugByItemCode,
  getSpaceByItemCode,
  getValuationDrugByItemCode,
} from '../service';
import { getSpaceCostTableData } from '@/pages/costLibraryManagement/basicCostManagement/spaceCostManagement/service';
import { getEquipTableData } from '@/pages/costLibraryManagement/basicCostManagement/equipmentCostManagement/service';
import { getLeftList } from '@/pages/costLibraryManagement/basicCostManagement/personnelClassificationMana/service';
import TableSelecter from './tableSelector';
import { fetchAllDepartments } from '..';

const empColumns = [
  {
    title: '人员类别',
    dataIndex: 'empTypeCodeName',
  },
  {
    title: '数量',
    dataIndex: 'num',
  },
  {
    title: '执行时间（min）',
    dataIndex: 'executeTime',
  },
];
const equipColumns = [
  {
    title: '设备编编码',
    dataIndex: 'equipmentCode',
  },
  {
    title: '设备名称',
    dataIndex: 'equipmentCodeName',
  },
  {
    title: '数量',
    dataIndex: 'num',
  },
  {
    title: '执行时间(m)',
    dataIndex: 'executeTime',
  },
];
const spaceColumns = [
  {
    title: '空间编码',
    dataIndex: 'spaceCode',
  },
  {
    title: '空间名称',
    dataIndex: 'spaceCodeName',
  },
  {
    title: '数量',
    dataIndex: 'num',
  },
  {
    title: '执行时间(m)',
    dataIndex: 'executeTime',
  },
];

export const Setting = (props: any) => {
  const { record, onVisibleChange } = props;

  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [columns, set_columns] = useState<any[]>([]);
  const [currentTabKey, set_currentTabKey] = useState('1');
  const [dataSource, set_dataSource] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [selectedRows, set_selectedRows] = useState<any[]>([]);
  const [tableSelecterVisible, set_tableSelecterVisible] = useState(false);
  const [currentEditRow, set_currentEditRow] = useState<any>(undefined);

  const valuationColumns = [
    {
      title: '项目类别',
      width: 85,
      dataIndex: 'typeName',
    },
    {
      title: '项目代码',
      width: 85,
      dataIndex: 'code',
    },
    {
      title: '项目名称',
      dataIndex: 'name',
    },
    {
      title: '数量',
      dataIndex: 'num',
      width: 120,
      renderText(num: any, record: any) {
        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 });
                    },
                  }}
                />
                <img
                  onClick={() =>
                    updateTable(
                      { ...record, ...currentEditRow },
                      'EDIT',
                      Number(currentTabKey),
                    )
                  }
                  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>
        );
      },
    },
  ];

  const columnsData = (key: number) => [
    {
      title: '操作',
      key: 'option',
      width: 160,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn
            key={'act'}
            record={record}
            type="EDIT"
            currentTabKey={key}
          />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const getTableData = async (tabCode: string) => {
    let resp = undefined;
    if (tabCode == '1') {
      resp = await getEmpsByItemCode(record.code, record.departmentCode);
    }
    if (tabCode == '2') {
      resp = await getEquipByItemCode(record.code, record.departmentCode);
    }
    if (tabCode == '3') {
      resp = await getSpaceByItemCode(record.code, record.departmentCode);
    }
    if (tabCode == '4') {
      resp = await getValuationDrugByItemCode(
        record.code,
        record.departmentCode,
      );
    }
    if (tabCode == '5') {
      resp = await getNoValuationDrugByItemCode(
        record.code,
        record.departmentCode,
      );
    }

    set_dataSource(resp);
  };

  const delTableData = async (record: any) => {
    const resp = await delDrawerTableData(record.id, Number(currentTabKey));
    if (resp) {
      message.success('操作成功！');
      //tableRef.current?.reload();
      getTableData(`${currentTabKey}`);
      // message.success('操作成功!');
    }
  };

  const updateTable = async (
    formVal: any,
    type: 'EDIT' | 'ADD',
    currentTabKey: number,
  ) => {
    let result = undefined;

    if (type == 'ADD') {
      if (currentTabKey == 1) {
        result = {
          itemCode: record.code,
          empTypeCode: formVal.empType.value,
          empTypeCodeName: formVal.empType.label,
          num: formVal.num,
          executeTime: formVal.executeTime,
        };
      }
      if (currentTabKey == 2) {
        result = {
          itemCode: record.code,
          equipmentCode: formVal.equipmentCode,
          num: formVal.num,
          executeTime: formVal.executeTime,
        };
      }
      if (currentTabKey == 3) {
        result = {
          itemCode: record.code,
          spaceCode: formVal.space[formVal.space.length - 1],
          num: formVal.num,
          spaceCodePath: formVal.spaceCodePath,
          executeTime: formVal.executeTime,
        };
      }

      const resp = await addDrawerTableData(
        { ...result, departmentCode: record.departmentCode },
        currentTabKey as number,
      );
      if (resp) {
        //tableRef.current?.reload();
        getTableData(`${currentTabKey}`);
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      try {
        if (currentTabKey == 1) {
          result = {
            itemCode: record.code,
            empTypeCode: formVal.empType.value,
            empTypeCodeName: formVal.empType.label,
            num: formVal.num,
            executeTime: formVal.executeTime,
          };
        }
        if (currentTabKey == 2) {
          result = {
            itemCode: record.code,
            equipmentCode: formVal.equipmentCode,
            num: formVal.num,
            executeTime: formVal.executeTime,
          };
        }
        if (currentTabKey == 3) {
          result = {
            itemCode: record.code,
            spaceCode: formVal.spaceCode,
            num: formVal.num,
            spaceCodePath: formVal.spaceCodePath,
            executeTime: formVal.executeTime,
          };
        }
        if (currentTabKey == 4 || currentTabKey == 5) {
          result = {
            ...currentEditRow,
          };
        }

        const resp = await editDrawerTableData(
          { ...result, id: formVal.id, departmentCode: record.departmentCode },
          currentTabKey,
        );
        if (resp) {
          //tableRef.current?.reload();
          getTableData(`${currentTabKey}`);
          message.success('操作成功！');
        }
        set_currentEditRow(undefined);
      } catch (error) {
        console.log('编辑保存：', error);
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
    currentTabKey,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
    currentTabKey: number;
  }) => {
    const [cascaderData, set_cascaderData] = useState<any[]>([]);
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}${
          currentTabKey == 1
            ? '参与人员'
            : currentTabKey == 2
            ? '使用设备'
            : '使用空间'
        }`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                empType: record.empTypeCode,
                space: record.spaceCodePath
                  ? record.spaceCodePath.split(',')
                  : [],
              }
            : {
                kcClassCode: '',
                kcClassName: '',
                kcClassPath: '',
                executeTime: record.executeTime,
              }
        }
        trigger={
          type == 'EDIT' ? <a key="edit">编辑</a> : <a className="add">新增</a>
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
            currentTabKey,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        {/* <ProFormSelect
                    name="departmentCode"
                    label="科室："
                    placeholder="请输入"
                    request={fetchAllDepartments}
                    fieldProps={{labelInValue:false}}
                    rules={[{ required: false, message: '科室不能为空!' }]}
                /> */}
        {currentTabKey == 1 && (
          <ProFormSelect
            name="empType"
            label="人员类别："
            placeholder="请选择"
            showSearch
            fieldProps={{ labelInValue: true }}
            request={async () => {
              const resp = await getLeftList();
              if (resp) {
                return resp.map((a: any) => ({
                  label: a.costTypeName,
                  value: a.costTypeCode,
                }));
              } else {
                return [];
              }
            }}
            rules={[{ required: true, message: '人员类别不能为空!' }]}
          />
        )}
        {currentTabKey == 2 && (
          <ProFormSelect
            name="equipmentCode"
            label="设备名称："
            placeholder="请选择"
            showSearch
            request={async ({ keyWords }) => {
              const resp = await getEquipTableData({
                name: keyWords,
                pageSize: 500,
                current: 1,
              });
              if (resp) {
                return resp.list.map((a: any) => ({
                  label: a.name,
                  value: a.code,
                }));
              } else {
                return [];
              }
            }}
            rules={[{ required: true, message: '设备名称不能为空!' }]}
          />
        )}
        {currentTabKey == 3 && (
          <>
            <ProFormText name="spaceCodePath" hidden />
            <ProFormText name="spaceCode" hidden />
            <ProFormCascader
              name="space"
              label="空间名称："
              rules={[{ required: true, message: '空间名称不能为空!' }]}
              request={async () => {
                const resp = await getSpaceCostTableData();
                if (resp) {
                  set_cascaderData(resp);
                  return resp;
                }
              }}
              fieldProps={{
                fieldNames: {
                  label: 'name',
                  value: 'code',
                  children: 'childList',
                },
                onChange: async (value: any) => {
                  // const a = findAllParents(cascaderData, value[value.length - 1]);
                  // console.log({a});
                  if (value.length > 0) {
                    formRef.current?.setFieldsValue({
                      spaceCodePath: value.join(','),
                      spaceCode: value[value.length - 1],
                    });
                  }
                },
              }}
            />
          </>
        )}

        <ProFormDigit
          name="num"
          label="数量："
          placeholder="请输入"
          rules={[{ required: true, message: '数量不能为空!' }]}
        />
        <ProFormDigit
          name="executeTime"
          label="执行时间（min）："
          placeholder="请输入"
          rules={[{ required: true, message: '执行时间不能为空!' }]}
        />
      </ModalForm>
    );
  };

  const tableSelecterCommit = async (keys: Key[], rows: any[]) => {
    //   console.log({keys,rows});
    set_tableSelecterVisible(false);
    const result = {
      itemCode: record.code,
      items: rows,
    };
    const resp = await addDrugTableData(result, Number(currentTabKey));
    if (resp) {
      getTableData(`${currentTabKey}`);
    }
  };

  const onSelectChange = (
    newSelectedRowKeys: React.Key[],
    selectedRows: any,
  ) => {
    setSelectedKeys([...newSelectedRowKeys]);
    set_selectedRows([...selectedRows]);
  };

  const batchDelTableData = async () => {
    const resp = await batchDelDrugTableData(
      selectedRows.map((a) => a.id),
      Number(currentTabKey),
    );
    if (resp) {
      getTableData(`${currentTabKey}`);
      setSelectedKeys([]);
      set_selectedRows([]);
    }
  };

  useEffect(() => {
    getTableData(currentTabKey);
    set_currentEditRow(undefined);
    if (currentTabKey == '1') {
      set_columns([...empColumns, ...columnsData(Number(currentTabKey))]);
    }
    if (currentTabKey == '2') {
      set_columns([...equipColumns, ...columnsData(Number(currentTabKey))]);
    }
    if (currentTabKey == '3') {
      set_columns([...spaceColumns, ...columnsData(Number(currentTabKey))]);
    }
    if (currentTabKey == '4') {
      set_columns([
        ...valuationColumns,
        {
          title: '操作',
          key: 'option',
          width: 80,
          valueType: 'option',
          render: (_: any, record: any) => {
            return [
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
            ];
          },
        },
      ]);
    }
    if (currentTabKey == '5') {
      set_columns([
        ...valuationColumns,
        {
          title: '操作',
          key: 'option',
          width: 80,
          valueType: 'option',
          render: (_: any, record: any) => {
            return [
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
            ];
          },
        },
      ]);
    }

    setSelectedKeys([]);
    set_selectedRows([]);
  }, [currentTabKey]);

  useEffect(() => {
    if (currentTabKey == '4' || currentTabKey == '5')
      set_columns([
        ...valuationColumns,
        {
          title: '操作',
          key: 'option',
          width: 80,
          valueType: 'option',
          render: (_: any, record: any) => {
            return [
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
            ];
          },
        },
      ]);
  }, [currentEditRow]);

  return (
    <div className="settingDrawer">
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="添加"
        rowKey={'code'}
        defaultSelectedKeys={dataSource.map((a: any) => a.code)}
        record={record}
        open={tableSelecterVisible}
        onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
      />
      <div className="header">
        <div className="title">
          {record ? `${record.name}(${record.departmentName})` : '项目'}
        </div>
        <div className="btnGroup">
          <a className="back" onClick={() => onVisibleChange(false)}>
            返回
          </a>
          {currentTabKey != '4' && currentTabKey != '5' && (
            <UpDataActBtn
              key={'act'}
              record={record}
              type="ADD"
              currentTabKey={Number(currentTabKey)}
            />
          )}
          {(currentTabKey == '4' || currentTabKey == '5') && (
            <a className="add" onClick={() => set_tableSelecterVisible(true)}>
              添加
            </a>
          )}
        </div>
      </div>

      <div style={{ padding: '0 16px' }}>
        <Tabs
          defaultActiveKey={`${currentTabKey}`}
          onChange={(key) => set_currentTabKey(key)}
          items={[
            {
              label: '参与人员',
              key: '1',
            },
            {
              label: '使用设备',
              key: '2',
            },
            {
              label: '使用空间',
              key: '3',
            },
            {
              label: '计价药材',
              key: '4',
            },
            {
              label: '不计价药材',
              key: '5',
            },
          ]}
        />
        <KCIMTable
          rowSelection={
            currentTabKey == '4' || currentTabKey == '5'
              ? {
                  alwaysShowAlert: false,
                  selectedRowKeys: selectedKeys,
                  onChange: onSelectChange,
                }
              : false
          }
          tableAlertRender={false}
          columns={[...columns]}
          actionRef={tableRef}
          rowKey="id"
          dataSource={dataSource}
        />
      </div>
      {selectedKeys.length > 0 && (
        <div className="footer">
          <div className="count">{`已选择${selectedKeys.length}`}</div>
          <div className="btngroup">
            <a
              className="cancel"
              onClick={() => {
                setSelectedKeys([]);
                set_selectedRows([]);
              }}
            >
              取消
            </a>
            <a className="confirm" onClick={() => batchDelTableData()}>
              批量删除
            </a>
          </div>
        </div>
      )}
    </div>
  );
};
