import './index.scss';
import { Button, Form, Select, Table } from 'antd';
import EditableCell from '~/components/EditableCell';
import React, { forwardRef, useEffect, useImperativeHandle, 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';
import deletePng from '~/assets/image/delete.png';
import { InterDataType } from '~/api/interface';
import { leaseGoodsDetailsType } from '~/api/interface/rentManageType';

//租赁商品详情返回类型
type rentGoodsDetailType = InterDataType<leaseGoodsDetailsType>;
type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

type RentAttrFormType = {
  productTypeId: number;
  brandInfoId: number;
  deviceModeId: number;
  mainImage: string;
  subImage: string[];
  goodsVideo: string;
  productDetails: string;
};
//商品参数表格类型
type productParamType = {
  id: number;
  productParamName: string;
  productParamValue: string;
};
interface selfProps {
  ref: any;
  rentGoodsDetails: rentGoodsDetailType | undefined;
}

const RentAttr = forwardRef<any, selfProps>(({ rentGoodsDetails }, ref) => {
  //商品属性表单
  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 [mainImgFileList, setMainImgFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  //商品副图文件列表
  const [subImgFileList, setSubImgFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);

  //商品视频文件列表
  const [videoFileList, setVideoFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);

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

  //商品参数新增
  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;
    }[],
    type: string,
  ) => {
    switch (type) {
      case 'mainImage':
        rentAttrForm.setFieldValue('mainImage', value[0].url);
        setMainImgFileList(value);
        break;
      case 'subImage':
        rentAttrForm.setFieldValue(
          'subImage',
          value.map((v) => v.url),
        );
        setSubImgFileList(value);
        break;
      default:
    }
  };
  //商品视频上传成功
  const videoUploadSuccess = (
    value: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
  ) => {
    rentAttrForm.setFieldValue('goodsVideo', value[0].url);
    setVideoFileList(value);
  };
  //商品视频删除
  const deleteVideo = () => {
    setVideoFileList([]);
  };

  //商品参数表单验证
  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);
              if (values['productParamName' + cur.id] && values['productParamValue' + cur.id]) {
                Obj[values['productParamName' + cur.id]] = values['productParamValue' + cur.id];
                pre.push(Obj);
              }
              return pre;
            },
            [],
          );
          resolve(productParamList);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };

  const submitAttrForm = async () => {
    try {
      const values: any[] = await Promise.all([
        rentAttrForm.validateFields(),
        productParamFormSubmit(),
      ]);
      return Promise.resolve({
        ...values[0],
        productParam: values[1].length ? JSON.stringify(values[1]) : undefined,
      });
    } catch (e) {
      return Promise.reject(e);
    }
  };

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

  //编辑回显
  useEffect(() => {
    if (rentGoodsDetails) {
      rentAttrForm.setFieldsValue({
        productTypeId: rentGoodsDetails.productTypeId,
        brandInfoId: rentGoodsDetails.brandInfoId,
        deviceModeId: rentGoodsDetails.deviceModeId,
        mainImage: rentGoodsDetails.resourcesList.filter((v) => v.type === 0)[0].url,
        subImage: rentGoodsDetails.resourcesList.filter((v) => v.type === 1).length
          ? rentGoodsDetails.resourcesList.filter((v) => v.type === 1).map((v) => v.url)
          : undefined,
        goodsVideo: rentGoodsDetails.resourcesList.filter((v) => v.type === 2).length
          ? rentGoodsDetails.resourcesList.filter((v) => v.type === 2)[0].url
          : undefined,
      });
      getRentModelList(rentGoodsDetails.brandInfoId, rentGoodsDetails.productTypeId);
      if (rentGoodsDetails.productParam) {
        const tableData: productParamType[] = JSON.parse(rentGoodsDetails.productParam).map(
          (v: { [x: string]: string }) => ({
            productParamName: Object.getOwnPropertyNames(v)[0],
            productParamValue: v[Object.getOwnPropertyNames(v)[0]],
            id: Math.random(),
          }),
        );
        setParameterTableData(tableData);
        const defaultFormValue: { [x: string]: string } = tableData.reduce(
          (pre: { [x: string]: string }, cur) => {
            pre['productParamName' + cur.id] = cur.productParamName;
            pre['productParamValue' + cur.id] = cur.productParamValue;
            return pre;
          },
          {},
        );
        productParamForm.setFieldsValue(defaultFormValue);
      }
      setMainImgFileList(
        rentGoodsDetails.resourcesList
          .filter((v) => v.type === 0)
          .map((v) => ({ id: Math.random(), uid: Math.random(), name: '主图', url: v.url })),
      );
      setSubImgFileList(
        rentGoodsDetails.resourcesList
          .filter((v) => v.type === 1)
          .map((v) => ({ id: Math.random(), uid: Math.random(), name: '主图', url: v.url })),
      );
      setVideoFileList(
        rentGoodsDetails.resourcesList
          .filter((v) => v.type === 2)
          .map((v) => ({ id: Math.random(), uid: Math.random(), name: '主图', url: v.url })),
      );
    }
  }, [rentGoodsDetails]);

  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='mainImage'
          rules={[{ required: true, message: '请上传商品主图' }]}
        >
          <Uploader
            fileUpload
            listType='picture-card'
            onChange={(fileList) => imgUploadSuccess(fileList, 'mainImage')}
            defaultFileList={mainImgFileList}
            fileSize={2}
            fileLength={1}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item label='商品副图' name='subImage'>
          <Uploader
            fileUpload
            listType='picture-card'
            onChange={(fileList) => imgUploadSuccess(fileList, 'subImage')}
            defaultFileList={subImgFileList}
            fileSize={2}
            fileLength={4}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item label='商品视频' name='goodsVideo'>
          {videoFileList.length ? (
            <div className='rent-goods-video-wrap'>
              <video
                src={videoFileList[0].url}
                style={{ width: '200px', height: '200px' }}
                controls
              />
              <img src={deletePng} alt='删除' onClick={deleteVideo} />
            </div>
          ) : (
            <Uploader
              fileUpload
              listType='picture-card'
              onChange={videoUploadSuccess}
              defaultFileList={videoFileList}
              fileSize={30}
              fileLength={1}
              fileType={['video/mp4', 'video/avi', 'video/wmv', 'video/rmvb']}
            >
              <UploadOutlined />
            </Uploader>
          )}
        </Form.Item>
        <Form.Item label='商品详情页' name='productDetails'>
          <RichText richTextContent={rentGoodsDetails?.productDetails} />
        </Form.Item>
      </Form>
    </div>
  );
});
export default RentAttr;
