import React, { useEffect, useState } from 'react';
import { Button, message, Table } from 'antd';
import {
  getOrderAmountDetailsType,
  serviceOrderFormDetailsType,
} from '~/api/interface/orderManageType';
import { InterDataType } from '~/api/interface';
import { ColumnsType } from 'antd/es/table/InternalTable';
import { PlusOutlined } from '@ant-design/icons';
import OrderSettleModal from '~/pages/orderManage/demandOrder/orderDetail/comp/orderSettleModal';
import { OrderManageAPI } from '~/api';
import dayjs from 'dayjs';

// 详情返回类型
type DetailType = InterDataType<serviceOrderFormDetailsType>;
// 列表类型
type ListType = InterDataType<getOrderAmountDetailsType>;

const OrderSettleView: React.FC<{ detail: DetailType; onRefresh: () => void }> = ({
  detail,
  onRefresh,
}) => {
  // 表格列表
  const [tableData, setTableData] = useState<ListType>([]);
  // 新增弹窗是否开启
  const [addEditVisible, setAddEditVisible] = useState<boolean>(false);
  // 编辑文件
  const [recordData, setRecordData] = useState<ListType[0]>();
  // 获取列表数据
  const getTableData = async () => {
    const res = await OrderManageAPI.getOrderAmountDetails({
      requirementsInfoId: detail?.serviceOrderFormDetailsDTO?.id,
    });
    if (res && res.code === '200') {
      const list = res.result || [];
      // console.log('获取列表数据 --->', getTableTotal(list));
      setTableData(getTableTotal(list));
    }
  };
  // 计算合计数据
  const getTableTotal = (list: ListType) => {
    // 如果一条数据都没有就返回一条默认数据
    if (list?.length === 0)
      return [
        {
          dailyWage: 0,
          highTemperatureSubsidy: 0,
          id: 0,
          realWages: 0,
          rentalSubsidy: 0,
          requirementsInfoId: 0,
          settleAccountsProportion: 0,
          subsidyFestival: 0,
          trafficSubsidy: 0,
          workDate: '合计',
        },
      ];
    // 获取表格数据的列名
    const keys = Object.keys(list?.[0] ?? {});
    // 使用 reduce () 函数计算每一列的总和
    const data = keys.reduce((acc, key) => {
      // 将字符串转换为数字并累加
      const total = list.reduce((sum, row: any) => sum + (+row[key] ?? 0), 0);
      // 返回累加器对象
      return { ...acc, [key]: total };
    }, {});
    // 返回结果对象
    return [
      ...list,
      {
        ...data,
        workDate: '合计',
        id: new Date().getTime(),
        settleAccountsProportion: undefined,
      },
    ] as ListType;
  };
  // 删除数据
  const handleDelete = (record: ListType[0]) => {
    // 至少需要一行数据
    if (tableData.length === 2) {
      message.warning('至少需要一行数据').then();
      return;
    }
    // 删除数据并去掉最后一行合计数据
    const list = tableData.filter((v) => v.id !== record.id).slice(0, -1);
    // 重新计算合计数据
    setTableData(getTableTotal(list));
  };
  // 添加数据
  const handleAdd = (data: ListType[0]) => {
    // 如果有id就是修改，否则就是添加
    const list = data?.id
      ? tableData?.map((v) => (v.id === data.id ? data : v))?.slice(0, -1)
      : [...tableData.slice(0, -1), { ...data, id: dayjs(data?.workDate).valueOf() }];
    // 日期排序
    const arr = list?.sort((a, b) => dayjs(a.workDate).valueOf() - dayjs(b.workDate).valueOf());
    setTableData(getTableTotal(arr));
    setAddEditVisible(false);
    setRecordData(undefined);
    // console.log('添加数据 --->', data);
  };
  // 提交数据
  const handleSubmit = async () => {
    const res = await OrderManageAPI.updateOrderAmountDetails(
      tableData.slice(0, -1)?.map((i) => ({
        ...i,
        requirementsInfoId: detail?.serviceOrderFormDetailsDTO?.id,
        id: undefined,
      })),
    );
    if (res && res.code === '200') {
      message.success('操作成功');
      await getTableData();
      onRefresh();
    }
  };
  // 组件挂载
  useEffect(() => {
    if (!detail) return;
    getTableData().then();
    // console.log('订单结算 --->', detail);
  }, [detail]);
  // 表格列
  const columns: ColumnsType<ListType[0]> = [
    { title: '日期', dataIndex: 'workDate', align: 'center' },
    { title: '结算标准(元/天)', dataIndex: 'dailyWage', align: 'center' },
    { title: '节日补贴(元/天)', dataIndex: 'subsidyFestival', align: 'center' },
    { title: '出差租房补贴', dataIndex: 'rentalSubsidy', align: 'center' },
    { title: '交通补贴', dataIndex: 'trafficSubsidy', align: 'center' },
    { title: '高温补贴', dataIndex: 'highTemperatureSubsidy', align: 'center' },
    { title: '结算比例', dataIndex: 'settleAccountsProportion', align: 'center' },
    { title: '应结工资(元)', dataIndex: 'realWages', align: 'center' },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      render: (_value, record, index) =>
        index !== tableData.length - 1 &&
        detail?.serviceOrderFormDetailsDTO?.orderStatus === '400' && (
          <>
            <Button
              type='link'
              onClick={() => {
                setRecordData(record);
                setAddEditVisible(true);
              }}
            >
              修改
            </Button>
            <Button type='link' danger onClick={() => handleDelete(record)}>
              删除
            </Button>
          </>
        ),
    },
  ];
  return (
    <>
      <div className='order-settle'>
        <div className='settle-title'>订单结算</div>
        {detail?.serviceOrderFormDetailsDTO?.orderStatus === '400' && (
          <Button
            size='middle'
            type='primary'
            icon={<PlusOutlined />}
            style={{ marginBottom: '10px' }}
            onClick={() => setAddEditVisible(true)}
          >
            添加
          </Button>
        )}
        <Table size='small' rowKey='id' bordered columns={columns} dataSource={tableData} />
        {detail?.serviceOrderFormDetailsDTO?.orderStatus === '400' && (
          <div className='settle-action'>
            <Button size='middle' type='primary' onClick={handleSubmit}>
              确认修改
            </Button>
            <Button size='middle' onClick={getTableData}>
              重置
            </Button>
          </div>
        )}
      </div>
      <OrderSettleModal
        open={addEditVisible}
        title={recordData ? '修改结算' : '添加结算'}
        data={recordData}
        list={tableData}
        onCancel={() => {
          setAddEditVisible(false);
          setRecordData(undefined);
        }}
        onSubmit={handleAdd}
      />
    </>
  );
};

export default OrderSettleView;
