import React, { forwardRef, useEffect, useState, useImperativeHandle } from 'react';
import { Button, Form, Input, Radio, Select, Cascader } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { Uploader } from '~/components/uploader';
import './index.scss';
import { BaseInfoType, detailGoodsType } from '~/api/interface/goodsType';
import { CategoryManageAPI } from '~/api';
import { InterDataType } from '~/api/interface';
import { categoryListType, directoryPageListType } from '~/api/interface/categoryManage';
import deletePng from '~/assets/image/delete.png';

//目录返回类型
type directoryType = InterDataType<directoryPageListType>['list'];
//分类返回类型
type categoryType = InterDataType<categoryListType>['list'];
//商品返回类型
type goodsDetailType = InterDataType<detailGoodsType>;

interface selfProps {
  getCategoryList: (id: number) => void;
  categoryList: categoryType;
  ref: any;
  goodsDetail: goodsDetailType | undefined;
  isDetail: boolean; //是否详情
  goodsType: number; //0：销售，1：租赁
}

const BaseInfo: React.FC<selfProps> = forwardRef(
  ({ getCategoryList, categoryList, goodsDetail, isDetail, goodsType }: selfProps, ref) => {
    const [form] = Form.useForm<
      BaseInfoType & {
        mainImg: {
          id: number;
          name: string;
          uid: number;
          url: string;
        }[];
        subImg: {
          id: number;
          name: string;
          uid: number;
          url: string;
        }[];
        masterTypeId: number[];
      }
    >();
    //目录
    const [directoryList, setDirectoryList] = useState<directoryType>([]);
    //是否添加标签
    const [isAddTag, setIsAddTag] = useState<boolean>(false);
    //主图文件列表
    const [mainImgList, setMainImgList] = useState<
      {
        id: number;
        name: string;
        uid: number;
        url: string;
      }[]
    >([]);
    //副图文件列表
    const [subImgList, setSubImgList] = useState<
      {
        id: number;
        name: string;
        uid: number;
        url: string;
      }[]
    >([]);
    //视频文件列表
    const [videoList, setVideoList] = useState<
      {
        id: number;
        name: string;
        uid: number;
        url: string;
      }[]
    >([]);

    useImperativeHandle(ref, () => ({
      baseInform: form,
    }));

    //获取目录列表
    const getDirectoryList = () => {
      CategoryManageAPI.getDirectoryListClone({ type: goodsType ? 2 : 4 }).then(({ result }) => {
        setDirectoryList(result || []);
      });
    };
    const directorySelectChange = (value: number) => {
      getCategoryList(value);
    };
    //商品标签
    const radioChangeEvent = (e: any) => {
      setIsAddTag(e.target.value);
    };
    //主图上传
    const mainImgUploadSuccess = (
      fileList: {
        id: number;
        name: string;
        uid: number;
        url: string;
      }[],
    ) => {
      setMainImgList(fileList);
      form.setFieldsValue({
        mainImg: fileList,
      });
    };
    //副图上传
    const subImgUploadSuccess = (
      fileList: {
        id: number;
        name: string;
        uid: number;
        url: string;
      }[],
    ) => {
      setSubImgList(fileList);
      form.setFieldsValue({
        subImg: fileList,
      });
    };
    //视频上传
    const videoUploadSuccess = (
      fileList: {
        id: number;
        name: string;
        uid: number;
        url: string;
      }[],
    ) => {
      setVideoList(fileList);
      form.setFieldsValue({
        goodsVideo: fileList[0].url,
      });
    };
    //视频移除
    const deleteVideo = () => {
      setVideoList([]);
      form.setFieldsValue({
        goodsVideo: undefined,
      });
    };
    useEffect(() => {
      getDirectoryList();
    }, []);
    useEffect(() => {
      if (goodsDetail) {
        const goodsMainImg = goodsDetail.images
          .filter((v) => v.imgType === 0)
          .map((v) => ({
            id: v.id,
            name: 'mainImg',
            uid: v.id,
            url: v.imgUrl,
          }));
        setMainImgList(goodsMainImg);
        const goodsSubImg = goodsDetail.images
          .filter((v) => v.imgType === 1)
          .map((v) => ({
            id: v.id,
            name: 'sunImg',
            uid: v.id,
            url: v.imgUrl,
          }));
        setSubImgList(goodsSubImg);
        if (goodsDetail.goodsVideo) {
          setVideoList([
            {
              id: goodsDetail.goodsVideoId || Math.random(),
              name: 'video',
              uid: goodsDetail.goodsVideoId || Math.random(),
              url: goodsDetail.goodsVideo,
            },
          ]);
        }
        form.setFieldsValue({
          mainImg: goodsMainImg,
          subImg: goodsSubImg.length ? goodsSubImg : undefined,
          goodsVideo: goodsDetail.goodsVideo || undefined,
          goodsName: goodsDetail.goodsName,
          goodsDesc: goodsDetail.goodsDetail.goodsDesc,
          masterTypeId: [goodsDetail.categoryByOne, goodsDetail.categoryByTwo],
          directoryId: goodsDetail.directoryId,
          shelfStatus: goodsDetail.shelfStatus,
          tag: goodsDetail.tag || undefined,
        });
        setIsAddTag(!!goodsDetail.tag);
      }
    }, [goodsDetail]);
    return (
      <div className='base-info'>
        <div className='base-info-title'>基本信息</div>
        <div className='base-info-form'>
          <Form
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ shelfStatus: 1 }}
            form={form}
            disabled={isDetail}
          >
            <Form.Item
              name='mainImg'
              label='商品主图'
              rules={[{ required: true, message: '请上传商品主图' }]}
            >
              <Uploader
                listType='picture-card'
                fileUpload
                onChange={mainImgUploadSuccess}
                defaultFileList={mainImgList}
              >
                <UploadOutlined />
              </Uploader>
            </Form.Item>
            <Form.Item label='商品副图' name='subImg'>
              <Uploader
                listType={isDetail && subImgList.length === 0 ? 'text' : 'picture-card'}
                fileUpload
                onChange={subImgUploadSuccess}
                fileLength={3}
                defaultFileList={subImgList}
              >
                {isDetail ? subImgList.length ? '' : '暂无' : <UploadOutlined />}
              </Uploader>
            </Form.Item>
            <Form.Item label='商品视频' name='goodsVideo'>
              {videoList.length ? (
                <div className='goods-video-wrap'>
                  <video
                    src={videoList[0].url}
                    style={{ width: '200px', height: '200px' }}
                    controls
                  />
                  {!isDetail && <img src={deletePng} alt='删除' onClick={deleteVideo} />}
                </div>
              ) : (
                <Uploader
                  listType='text'
                  fileUpload
                  onChange={videoUploadSuccess}
                  defaultFileList={videoList}
                >
                  {isDetail ? (
                    videoList.length ? (
                      ''
                    ) : (
                      '暂无'
                    )
                  ) : (
                    <Button icon={<UploadOutlined />}>上传视频</Button>
                  )}
                </Uploader>
              )}
            </Form.Item>
            <Form.Item
              name='goodsName'
              label='商品名称'
              rules={[{ required: true, message: '请输入商品名称' }]}
            >
              <Input placeholder='请输入商品名称' maxLength={50} style={{ width: '400px' }} />
            </Form.Item>
            <Form.Item
              name='goodsDesc'
              label='商品描述'
              rules={[{ required: true, message: '请输入商品描述' }]}
            >
              <Input.TextArea
                placeholder='请输入商品描述'
                maxLength={70}
                style={{ width: '400px' }}
                rows={4}
                showCount
              />
            </Form.Item>
            <Form.Item
              name='directoryId'
              label='所属目录'
              rules={[{ required: true, message: '请选择所属目录' }]}
            >
              <Select
                placeholder='请选择所属目录'
                style={{ width: '400px' }}
                onChange={directorySelectChange}
              >
                {directoryList.map((v) => (
                  <Select.Option value={v.id} key={v.id}>
                    {v.directoryName}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              name='masterTypeId'
              label='商品分类'
              rules={[{ required: true, message: '请选择商品分类' }]}
            >
              <Cascader
                style={{ width: '400px' }}
                options={categoryList}
                fieldNames={{
                  label: 'classifyName',
                  value: 'id',
                  children: 'children',
                }}
                placeholder='请选择商品分类'
                allowClear
              />
            </Form.Item>
            <Form.Item label='商品标签'>
              <Radio.Group onChange={radioChangeEvent} value={isAddTag}>
                <Radio value={false}>不加</Radio>
                <Radio value={true}>加</Radio>
              </Radio.Group>
            </Form.Item>
            {isAddTag && (
              <Form.Item
                name='tag'
                label='标签名称'
                rules={[{ required: true, message: '请输入标签名称' }]}
              >
                <Input placeholder='请输入标签名称' style={{ width: '400px' }} maxLength={5} />
              </Form.Item>
            )}

            <Form.Item
              label='商品状态'
              name='shelfStatus'
              rules={[{ required: true, message: '请选择商品状态' }]}
            >
              <Select placeholder='请选择商品状态' style={{ width: '400px' }}>
                <Select.Option value={1}>上架</Select.Option>
                <Select.Option value={0}>下架</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  },
);

export default BaseInfo;
