/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-11-15 15:34:36
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-01-08 16:42:17
 * @FilePath: /CostAccountingSys/src/pages/costLibraryManagement/projectCostManagement/standardProjectMana/drawer.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { KCIMTable } from '@/components/KCIMTable';
import {
  ActionType,
  DrawerForm,
  ModalForm,
  ProColumns,
  ProFormCascader,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { useEffect, useRef, useState } from 'react';
import { Tabs, Popconfirm, message } from 'antd';
import './style.less';
import {
  addDrawerTableData,
  delDrawerTableData,
  editData,
  editDrawerTableData,
  getStandItemEmpMap,
  getStandItemEquipmentMap,
  getStandItemSpaceMap,
} from './service';
import { getTargetDic } from '@/services/auth';
import { getLeftList } from '../../basicCostManagement/personnelClassificationMana/service';
import { getEquipTableData } from '../../basicCostManagement/equipmentCostManagement/service';
import { getSpaceCostTableData } from '../../basicCostManagement/spaceCostManagement/service';
import { findAllParents } from '@/utils/tooljs';

const columns_emp: ProColumns[] = [
  {
    title: '人员类别',
    dataIndex: 'empTypeCodeName',
  },
  {
    title: '数量',
    align: 'right',
    dataIndex: 'num',
  },
  {
    title: '执行时间（min）',
    dataIndex: 'executeTime',
  },
];

const columns_equip: ProColumns[] = [
  {
    title: '设备编码',
    dataIndex: 'equipmentCode',
  },
  {
    title: '设备名称',
    dataIndex: 'equipmentCodeName',
  },
  {
    title: '数量',
    align: 'right',
    dataIndex: 'num',
  },
  {
    title: '执行时间（min）',
    dataIndex: 'executeTime',
  },
];
const columns_space: ProColumns[] = [
  {
    title: '空间编码',
    dataIndex: 'spaceCode',
  },
  {
    title: '空间名称',
    dataIndex: 'spaceCodeName',
  },
  {
    title: '数量',
    align: 'right',
    dataIndex: 'num',
  },
  {
    title: '执行时间（min）',
    dataIndex: 'executeTime',
  },
];

let _currentTabKey = 1;

const DrawerActBtn = ({
  record,
  onVisibleChange,
}: {
  record: any;
  onVisibleChange?: (bool: boolean) => void;
}) => {
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [drawerTablereload, set_drawerTablereload] = useState(false);
  const [drawerVisible, set_drawerVisible] = useState(false);
  const [tabs, set_tabs] = useState<any[]>([]);
  const [currentTabKey, set_currentTabKey] = useState<number>(1);
  const [columns, set_columns] = useState<any[]>([]);

  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 (params: any, sort: any, filter: any) => {
    if (currentTabKey == 1) {
      const resp = await getStandItemEmpMap(record.code);
      if (resp) {
        return {
          data: resp,
          success: true,
        };
      }
    }
    if (currentTabKey == 2) {
      const resp = await getStandItemEquipmentMap(record.code);
      if (resp) {
        return {
          data: resp,
          success: true,
        };
      }
    }
    if (currentTabKey == 3) {
      const resp = await getStandItemSpaceMap(record.code);
      if (resp) {
        return {
          data: resp,
          success: true,
        };
      }
    }
    return [];
  };

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

    if (type == 'ADD') {
      if (_currentTabKey == 1) {
        result = {
          standItemCode: record.code,
          empTypeCode: formVal.empType.value,
          empTypeCodeName: formVal.empType.label,
          num: formVal.num,
          executeTime: formVal.executeTime,
        };
      }
      if (_currentTabKey == 2) {
        result = {
          standItemCode: record.code,
          equipmentCode: formVal.equipmentCode,
          num: formVal.num,
          executeTime: formVal.executeTime,
        };
      }
      if (_currentTabKey == 3) {
        result = {
          standItemCode: record.code,
          spaceCode: formVal.space[formVal.space.length - 1],
          num: formVal.num,
          spaceCodePath: formVal.spaceCodePath,
          executeTime: formVal.executeTime,
        };
      }
      const resp = await addDrawerTableData(result, _currentTabKey as number);
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      try {
        if (_currentTabKey == 1) {
          result = {
            standItemCode: record.code,
            empTypeCode: formVal.empType.value,
            empTypeCodeName: formVal.empType.label,
            num: formVal.num,
            executeTime: formVal.executeTime,
          };
        }
        if (_currentTabKey == 2) {
          result = {
            standItemCode: record.code,
            equipmentCode: formVal.equipmentCode,
            num: formVal.num,
            executeTime: formVal.executeTime,
          };
        }
        if (_currentTabKey == 3) {
          result = {
            standItemCode: record.code,
            spaceCode: formVal.spaceCode,
            num: formVal.num,
            spaceCodePath: formVal.spaceCodePath,
            executeTime: formVal.executeTime,
          };
        }

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

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

  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>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        {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 saveResult = async () => {};

  const onCancel = () => {
    set_drawerVisible(false);
  };

  const onTabChanged = (key: string) => {
    // console.log({key})
    if (Number(key) == 1) {
      set_columns([...columns_emp, ...columnsData(Number(key))]);
    }
    if (Number(key) == 2) {
      set_columns([...columns_equip, ...columnsData(Number(key))]);
    }
    if (Number(key) == 3) {
      set_columns([...columns_space, ...columnsData(Number(key))]);
    }
    set_currentTabKey(Number(key));
    tableRef.current?.reload();
  };

  useEffect(() => {
    _currentTabKey = currentTabKey;
  }, [currentTabKey]);

  useEffect(() => {
    onVisibleChange && onVisibleChange(drawerVisible);
  }, [drawerVisible]);

  useEffect(() => {
    set_tabs([
      {
        label: '参与人员',
        key: 1,
      },
      {
        label: '使用设备',
        key: 2,
      },
      {
        label: '使用空间',
        key: 3,
      },
    ]);
    set_currentTabKey(1);
    set_columns([...columns_emp, ...columnsData(Number(currentTabKey))]);
  }, []);

  return (
    <DrawerForm
      open={drawerVisible}
      trigger={
        <a
          key="set"
          onClick={(e) => {
            e.stopPropagation();
            set_drawerVisible(true);
          }}
        >
          成本设置
        </a>
      }
      drawerProps={{
        closable: false,
        extra: null,
      }}
      width={908}
      submitter={false}
    >
      <div className="standardProjectMana_drawer">
        <div className="topbar">
          <div className="title">{record?.name}</div>
          <div className="btnGroup">
            <span className="cancel" onClick={() => onCancel()}>
              返回
            </span>
            <UpDataActBtn
              key={'act'}
              record={record}
              type="ADD"
              currentTabKey={currentTabKey}
            />
          </div>
        </div>
        <Tabs
          defaultActiveKey={`${currentTabKey}`}
          items={tabs}
          key={'key'}
          onChange={(key) => onTabChanged(key)}
        />
        <div className="content">
          <div className="rightContent">
            <KCIMTable
              tableAlertRender={false}
              actionRef={tableRef}
              rowKey="id"
              columns={columns}
              request={(params: any, sort: any, filter: any) =>
                getTableData(params, sort, filter)
              }
            />
          </div>
        </div>
      </div>
    </DrawerForm>
  );
};

export default DrawerActBtn;
