import './index.scss';
import { Button, Col, Form, Row, Table } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { InterDataType, InterReqType } from '~/api/interface';
import { addRentGoodsType, leaseGoodsDetailsType } from '~/api/interface/rentManageType';
import EditableCell from '~/components/EditableCell';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';

//租赁商品详情返回类型
type rentGoodsDetailType = InterDataType<leaseGoodsDetailsType>;
//租赁-清单类型
type leasePartsListType = Exclude<
  InterReqType<addRentGoodsType>,
  undefined
>['leasePartsList'][0] & { id?: number };

type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

interface selfProps {
  ref: any;
  rentGoodsDetails: rentGoodsDetailType | undefined;
}

const AccessoryList = forwardRef<any, selfProps>(({ rentGoodsDetails }, ref) => {
  const [accessoryTableForm] = Form.useForm<{ [x: string]: string | number }>();

  const accessoryTableDefaultColumns: (ColumnTypes[number] & {
    editable?: boolean;
    dataIndex?: string;
    inputType?: string;
    rules?: any;
    maxLength?: number;
  })[] = [
    {
      title: '序号',
      align: 'center',
      render: (_: any, _record: any, index: number) => index + 1,
    },
    {
      title: '名称',
      editable: true,
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '数量',
      editable: true,
      dataIndex: 'number',
      align: 'center',
      inputType: 'number',
    },
    {
      title: '参考价格',
      editable: true,
      dataIndex: 'price',
      align: 'center',
      inputType: 'number',
    },
    {
      title: '操作',
      align: 'center',
      render: (_: any, _record: any, index: number) => (
        <>
          {index === accessoryTableData.length - 1 ? (
            <Button
              type='primary'
              icon={<PlusOutlined />}
              style={{ marginRight: '5px' }}
              onClick={addAccessoryTableClick}
            ></Button>
          ) : (
            ''
          )}
          {index ? (
            <Button
              type='primary'
              icon={<MinusOutlined />}
              onClick={() => deleteAccessoryTableClick(index)}
            ></Button>
          ) : (
            ''
          )}
        </>
      ),
    },
  ];
  const accessoryTableColumns = accessoryTableDefaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: col.editable,
        inputType: col.inputType,
        rules: col.rules,
      }),
    };
  });
  const [accessoryTableData, setAccessoryTableData] = useState<leasePartsListType[]>([
    { id: Math.random(), name: '', number: 0, price: 0 },
  ]);

  useImperativeHandle(ref, () => ({
    accessoryTableFormSubmit,
  }));

  //新加一行
  const addAccessoryTableClick = () => {
    setAccessoryTableData([
      ...accessoryTableData,
      { id: Math.random(), name: '', number: 0, price: 0 },
    ]);
  };
  //删除一行
  const deleteAccessoryTableClick = (index: number) => {
    accessoryTableData.splice(index, 1);
    setAccessoryTableData([...accessoryTableData]);
  };
  //配件清单表单提交
  const accessoryTableFormSubmit = () => {
    return new Promise((resolve, reject) => {
      accessoryTableForm
        .validateFields()
        .then((value: any) => {
          resolve(
            accessoryTableData.reduce((pre: leasePartsListType[], cur) => {
              if (value['name' + cur.id] || value['price' + cur.id] || value['number' + cur.id]) {
                pre.push({
                  name: value['name' + cur.id],
                  price: value['price' + cur.id],
                  number: value['number' + cur.id],
                  id: rentGoodsDetails
                    ? rentGoodsDetails.leasePartsList.some((v) => v.id === cur.id)
                      ? cur.id
                      : undefined
                    : undefined,
                });
              }

              return pre;
            }, []),
          );
        })
        .catch((err) => {
          reject(err);
        });
    });
  };

  useEffect(() => {
    if (rentGoodsDetails) {
      if (rentGoodsDetails.leasePartsList) {
        setAccessoryTableData(rentGoodsDetails.leasePartsList);
        const defaultFormValue: { [x: string]: string | undefined | number } =
          rentGoodsDetails.leasePartsList.reduce(
            (pre: { [x: string]: string | undefined | number }, cur) => {
              pre['name' + cur.id] = cur.name || undefined;
              pre['number' + cur.id] = cur.number || undefined;
              pre['price' + cur.id] = cur.price || undefined;
              return pre;
            },
            {},
          );
        accessoryTableForm.setFieldsValue(defaultFormValue);
      }
    }
  }, [rentGoodsDetails]);

  return (
    <div className='accessory-list'>
      <div className='accessory-list-title'>配件清单</div>
      <Row>
        <Col span={2}></Col>
        <Col span={11}>
          <Form form={accessoryTableForm}>
            <Table
              columns={accessoryTableColumns as ColumnTypes}
              bordered
              dataSource={accessoryTableData}
              rowKey='id'
              pagination={false}
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
            />
          </Form>
        </Col>
      </Row>
    </div>
  );
});
export default AccessoryList;
