import './index.scss';
import { Button, Col, Form, Row, Table, Tooltip } 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';
import { isEmptyBol, regPriceNumber } from '~/utils/validateUtils';

//租赁商品详情返回类型
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 stockValidator = (_rules: any, value: number) => {
    if (!isEmptyBol(value)) {
      if (/^[+]{0,1}(\d+)$/.test(value.toString())) {
        if (value > 99999999 || value < 0) {
          return Promise.reject(new Error('库存最大为99999999且大于0'));
        }
        return Promise.resolve();
      } else {
        return Promise.reject(new Error('请输入正整数'));
      }
    } else {
      return Promise.resolve();
    }
  };
  //价格正则校验
  const priceValidator = (_rules: any, value: number) => {
    if (!isEmptyBol(value)) {
      if (regPriceNumber(value.toString())) {
        if (value > 99999999 || value < 0) {
          return Promise.reject(new Error('价格最大为99999999且大于0'));
        }
        return Promise.resolve();
      } else {
        return Promise.reject(new Error('为整数且最多保留两位小数'));
      }
    } else {
      return Promise.resolve();
    }
  };
  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',
      width: '30%',
      maxLength: 30,
    },
    {
      title: '数量',
      editable: true,
      dataIndex: 'number',
      align: 'center',
      inputType: 'number',
      width: '15%',
      rules: [{ required: false, validator: stockValidator }],
    },
    {
      title: '参考价格',
      editable: true,
      dataIndex: 'price',
      align: 'center',
      inputType: 'number',
      rules: [{ required: false, validator: priceValidator }],
    },
    {
      title: '操作',
      align: 'center',
      render: (_: any, _record: any, index: number) => (
        <>
          {index === accessoryTableData.length - 1 ? (
            <Tooltip placement='top' title='添加一行'>
              <Button
                type='primary'
                icon={<PlusOutlined />}
                style={{ marginRight: '5px' }}
                onClick={addAccessoryTableClick}
              ></Button>
            </Tooltip>
          ) : (
            ''
          )}
          {index ? (
            <Tooltip placement='top' title='删除一行'>
              <Button
                type='primary'
                icon={<MinusOutlined />}
                onClick={() => deleteAccessoryTableClick(index)}
              ></Button>
            </Tooltip>
          ) : (
            ''
          )}
        </>
      ),
    },
  ];
  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,
        maxLength: col.maxLength,
      }),
    };
  });
  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;
