import { Button, Col, Form, Input, message, Modal, ModalProps, Row, Select } from 'antd';
import { FC, useEffect, useState } from 'react';
import { InterDataType, InterReqType } from '~/api/interface';
import { addRentModeType, getTypeListType, rentModeListType } from '~/api/interface/rentManageType';
import { RentManageAPI } from '~/api';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';

interface selfProps {
  onOk: () => void;
  onCancel: () => void;
  brandInfoId: number;
  rentTypeList: rentTypeListType;
  currentRentMode: modeListType[0] | undefined;
}
//型号新增参数类型
type addRentParameterType = Exclude<InterReqType<addRentModeType>, undefined>;
//类型类别返回类型
type rentTypeListType = InterDataType<getTypeListType>['list'];
//型号返回类型
type modeListType = InterDataType<rentModeListType>['list'];

const AddOrEditRentModeModal: FC<ModalProps & selfProps> = ({
  open,
  onOk,
  onCancel,
  brandInfoId,
  rentTypeList,
  currentRentMode,
}) => {
  const [form] = Form.useForm<addRentParameterType>();

  //标签数组
  const [tagList, setTagList] = useState<{ id: number; tagName: string }[]>([
    { id: Math.random(), tagName: 'tag1' },
  ]);

  const handleOk = () => {
    form.validateFields().then((values: any) => {
      const covertTagList = tagList.reduce((pre: string[], cur) => {
        const tagKeyItem: string | undefined = Object.keys(values).find(
          (key: string) => key === cur.tagName,
        );
        if (tagKeyItem && values[tagKeyItem]) {
          pre.push(values[tagKeyItem]);
        }
        return pre;
      }, []);
      RentManageAPI[currentRentMode ? 'editRentMode' : 'addRentMode']({
        productTypeId: values.productTypeId,
        modeName: values.modeName,
        tag: covertTagList.length ? covertTagList.join(',') : undefined,
        brandInfoId,
        id: currentRentMode ? currentRentMode.id : undefined,
      }).then(({ code }) => {
        if (code === '200') {
          message.success(currentRentMode ? '编辑成功' : '新增成功');
          form.resetFields();
          setTagList([{ id: Math.random(), tagName: 'tag1' }]);
          onOk();
        }
      });
    });
  };

  const handleCancel = () => {
    form.resetFields();
    setTagList([{ id: Math.random(), tagName: 'tag1' }]);
    onCancel();
  };

  //新增标签
  const addTagClick = () => {
    setTagList([...tagList, { id: Math.random(), tagName: `tag${tagList.length + 1}` }]);
  };
  //删除标签
  const deleteTagClick = (index: number) => {
    form.setFieldValue(tagList[index].tagName, undefined);
    tagList.splice(index, 1);
    setTagList([...tagList]);
  };

  useEffect(() => {
    if (currentRentMode) {
      form.setFieldsValue({
        productTypeId: currentRentMode.productTypeId,
        modeName: currentRentMode.modeName,
        ...currentRentMode.tag?.split(',').reduce((pre: any, cur, currentIndex) => {
          pre['tag' + (currentIndex + 1)] = cur;
          return pre;
        }, {}),
      });
      setTagList(
        currentRentMode.tag
          ?.split(',')
          .map((_v, index) => ({ id: Math.random(), tagName: `tag${index + 1}` })) || [
          { id: Math.random(), tagName: 'tag1' },
        ],
      );
    }
  }, [currentRentMode]);

  return (
    <Modal
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
      title={currentRentMode ? '编辑型号' : '新增型号'}
    >
      <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
        <Form.Item
          label='所属类别'
          name='productTypeId'
          rules={[{ required: true, message: '请选择所属类别' }]}
        >
          <Select placeholder='请选择所属类别'>
            {rentTypeList.map((v) => (
              <Select.Option key={v.id} value={v.id}>
                {v.name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label='型号名称'
          name='modeName'
          rules={[{ required: true, message: '请输入型号名称' }]}
        >
          <Input placeholder='请输入型号名称' maxLength={30} />
        </Form.Item>
        {tagList.map((v, index) => (
          <Row key={v.id}>
            <Col span={20}>
              <Form.Item
                label={index ? '' : '标签'}
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19, offset: index ? 5 : 0 }}
                name={v.tagName}
              >
                <Input placeholder='请输入标签名称' maxLength={30} />
              </Form.Item>
            </Col>
            <Col span={3} offset={1}>
              {index === tagList.length - 1 ? (
                <Button
                  type='primary'
                  icon={<PlusOutlined />}
                  style={{ marginRight: '5px' }}
                  onClick={addTagClick}
                ></Button>
              ) : (
                ''
              )}

              {index ? (
                <Button
                  type='primary'
                  icon={<MinusOutlined />}
                  onClick={() => deleteTagClick(index)}
                ></Button>
              ) : (
                ''
              )}
            </Col>
          </Row>
        ))}
      </Form>
    </Modal>
  );
};
export default AddOrEditRentModeModal;
