import './index.scss';
import { Button, Form, Select, Table } from 'antd';
import EditableCell from '~/components/EditableCell';
import { useEffect, useState } from 'react';
import { MinusOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Uploader } from '~/components/uploader';
import RichText from '~/components/richText';
import { RentManageAPI } from '../../../../../../api';
type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

type RentAttrFormType = {
  productTypeId: number;
  brandInfoId: number;
  deviceModeId: number;
  goodsImage: string[];
  goodsVideo: string;
  productDetails: string;
};
//商品参数表格类型
type productParamType = {
  id: number;
  productParamName: string;
  productParamValue: string;
};

const RentAttr = () => {
  //商品属性表单
  const [rentAttrForm] = Form.useForm<RentAttrFormType>();
  //商品参数表单
  const [productParamForm] = Form.useForm<{ [key: string]: string }>();

  const attrTableColumns: (ColumnTypes[number] & {
    editable?: boolean;
    dataIndex?: string;
    inputType?: string;
    rules?: any;
    maxLength?: number;
  })[] = [
    {
      title: '参数名称',
      dataIndex: 'productParamName',
      editable: true,
      align: 'center',
    },
    {
      title: '参数值',
      dataIndex: 'productParamValue',
      editable: true,
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: '',
      render: (_text: string, _record: any, index: number) => (
        <>
          {index === parameterTableData.length - 1 ? (
            <Button
              icon={<PlusOutlined />}
              type='primary'
              onClick={addParameterDataEvent}
              style={{ marginRight: '10px' }}
            ></Button>
          ) : (
            ''
          )}
          {index ? (
            <Button
              type='primary'
              icon={<MinusOutlined />}
              onClick={() => deleteParameterDataEvent(index)}
            ></Button>
          ) : (
            ''
          )}
        </>
      ),
    },
  ];
  const columns = attrTableColumns.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 [parameterTableData, setParameterTableData] = useState<productParamType[]>([
    { id: Math.random(), productParamName: '', productParamValue: '' },
  ]);

  //类型下拉列表
  const [rentTypeList, setTypeList] = useState<{ label: string; value: number }[]>([]);
  //品牌下拉列表
  const [brandInfoList, setBrandInfoList] = useState<{ label: string; value: number }[]>([]);
  //型号下拉列表
  const [modeTypeList, setModeTypeList] = useState<{ label: string; value: number }[]>([]);
  //商品图片文件列表
  const [imgFileList, setImgFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  //商品视频文件列表
  const [videoFileList, setVideoFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);

  //商品参数新增
  const addParameterDataEvent = () => {
    setParameterTableData([
      ...parameterTableData,
      { id: Math.random(), productParamName: '', productParamValue: '' },
    ]);
  };
  //商品参数删除
  const deleteParameterDataEvent = (index: number) => {
    parameterTableData.splice(index, 1);
    setParameterTableData(parameterTableData);
  };

  //类型列表
  const getRentTypeList = () => {
    RentManageAPI.getTypeList({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      if (result.list) {
        const optionList = result.list.map((v) => ({ label: v.name, value: v.id }));
        setTypeList(optionList);
      }
    });
  };
  //品牌列表
  const getRentMakeList = () => {
    RentManageAPI.getListBrandInfo({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      if (result.list) {
        const optionList = result.list.map((v) => ({ label: v.brandName, value: v.id }));
        setBrandInfoList(optionList);
      }
    });
  };
  //型号列表
  const getRentModelList = (brandInfoId?: number, productTypeId?: number) => {
    RentManageAPI.getRentModeList({ pageNo: 1, pageSize: 99999, brandInfoId, productTypeId }).then(
      ({ result }) => {
        if (result.list) {
          const optionList = result.list.map((v) => ({ label: v.modeName, value: v.id }));
          setModeTypeList(optionList);
        }
      },
    );
  };

  //类型选中
  const rentTypeOnSelect = (value: number) => {
    getRentModelList(rentAttrForm.getFieldValue('brandInfoId') || undefined, value);
  };
  //品牌选中
  const brandInfoOnSelect = (value: number) => {
    getRentModelList(value, rentAttrForm.getFieldValue('productTypeId') || undefined);
  };
  //商品图片上传成功
  const imgUploadSuccess = (
    value: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
  ) => {
    rentAttrForm.setFieldValue(
      'goodsImage',
      value.map((v) => v.url),
    );
    setImgFileList(value);
  };
  //商品视频上传成功
  const videoUploadSuccess = (
    value: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
  ) => {
    rentAttrForm.setFieldValue('goodsVideo', value[0].url);
    setVideoFileList(value);
  };
  //商品参数表单验证
  const productParamFormSubmit = () => {
    return new Promise((resolve, reject) => {
      productParamForm
        .validateFields()
        .then((values) => {
          const productParamList = parameterTableData.reduce(
            (pre: { [key: string]: string }[], cur) => {
              const Obj = Object.create(null);
              Obj[values['productParamName' + cur.id]] = values['productParamValue' + cur.id];
              pre.push(Obj);
              return pre;
            },
            [],
          );
          resolve(productParamList);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };

  useEffect(() => {
    getRentTypeList();
    getRentMakeList();
  }, []);

  return (
    <div className='rent-attr'>
      <div className='rent-attr-title'>商品属性</div>
      <Form labelCol={{ span: 2 }} wrapperCol={{ span: 10 }} form={rentAttrForm}>
        <Form.Item
          label='商品类型'
          name='productTypeId'
          rules={[{ required: true, message: '请选择商品类型' }]}
        >
          <Select
            placeholder='请选择商品类型'
            options={rentTypeList}
            onSelect={rentTypeOnSelect}
          ></Select>
        </Form.Item>
        <Form.Item
          label='商品品牌'
          name='brandInfoId'
          rules={[{ required: true, message: '请选择商品品牌' }]}
        >
          <Select
            placeholder='请选择商品品牌'
            options={brandInfoList}
            onSelect={brandInfoOnSelect}
          ></Select>
        </Form.Item>
        <Form.Item
          label='商品型号'
          name='deviceModeId'
          rules={[{ required: true, message: '请选择商品型号' }]}
        >
          <Select placeholder='请选择商品型号' options={modeTypeList}></Select>
        </Form.Item>
        <Form.Item label='商品参数'>
          <Form form={productParamForm}>
            <Table
              columns={columns as ColumnTypes}
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              dataSource={parameterTableData}
              bordered
              rowKey='id'
              pagination={false}
            ></Table>
          </Form>
        </Form.Item>
        <Form.Item
          label='商品图片'
          name='goodsImage'
          rules={[{ required: true, message: '请选择商品图片' }]}
        >
          <Uploader
            fileUpload
            listType='picture-card'
            onChange={imgUploadSuccess}
            defaultFileList={imgFileList}
            fileSize={3}
            fileLength={5}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item label='商品视频' name='goodsVideo'>
          <Uploader
            fileUpload
            listType='picture-card'
            onChange={videoUploadSuccess}
            defaultFileList={videoFileList}
            fileSize={30}
            fileLength={1}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='商品详情页'
          name='productDetails'
          rules={[{ required: true, message: '请输入商品详情页' }]}
        >
          <RichText richTextContent='' />
        </Form.Item>
      </Form>
    </div>
  );
};
export default RentAttr;
