import { Button, Cascader, Form, Input, Radio, Select } from 'antd';
import { Uploader } from '~/components/uploader';
import type { RadioChangeEvent } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { InterDataType, InterListType } from '~/api/interface';
import { categoryListRespType } from '~/api/interface/categoryManage';
import { CategoryManageAPI, ForumManageAPI, MallManageAPI } from '~/api';
import deletePng from '~/assets/image/delete.png';
import './index.scss';
import { useSelector } from 'react-redux';
import AddTopicModal from '~/pages/forumManage/topicList/components/addTopicModal';
import { listGambitType } from '~/api/interface/forumManageType';

//分类返回类型
type categoryType = InterDataType<categoryListRespType>['list'];
// 话题列表返回类型
type topicListType = InterListType<listGambitType>;
interface selfProps {
  ref: any;
}
//基本信息表单类型
export type baseInfoType = {
  tradeName: string;
  description: string;
  mainImgList: {
    id: number;
    name: string;
    uid: number;
    url: string;
  }[];
  subImgList: {
    id: number;
    name: string;
    uid: number;
    url: string;
  }[];
  videoList: {
    id: number;
    name: string;
    uid: number;
    url: string;
  }[];
  curriculumIds: {
    id: number;
  }[];
  instructionsUrl: string;
  gambitId: number;
  categoryId: number[];
  shelfStatus: number;
  labelShow: number;
  goodsLabel: string;
};
const { Option } = Select;
const BaseInfo = forwardRef<any, selfProps>((_props, ref) => {
  const { userInfo } = useSelector((state: any) => state.UserInfo);
  const [baseInfoForm] = Form.useForm<baseInfoType>();
  const [labelShow, setLabelShow] = useState<boolean>(false);
  //分类列表
  const [categoryList, setCategoryList] = useState<categoryType>([]);
  const [addTopicModalShow, setAddTopicModalShow] = useState<boolean>(false);
  const [currentTopicItem, setCurrentTopicItem] = useState<topicListType[0]>();
  // 文件列表
  const [suggestFileList, setSuggestFileList] = useState<{ url: string }[]>();
  const [gambitList, setGambitList] = useState<
    {
      id: number;
      name: string;
    }[]
  >([]);
  const [curriculumList, setCurriculumList] = useState<
    {
      id: number;
      name: string;
    }[]
  >([]);
  //主图
  const [mainFileList, setMainFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  //副图
  const [subFileList, setSubFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  //视频
  const [videoFileList, setVideoFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);

  useImperativeHandle(ref, () => ({
    getForm: () => baseInfoForm,
    setLabelShow: (value: boolean) => setLabelShow(value),
    mediaData: {
      setMainFileList,
      setSubFileList,
      setVideoFileList,
    },
  }));

  //标签选中监听
  const labelRadioChange = (e: RadioChangeEvent) => {
    setLabelShow(!!e.target.value);
  };
  //上传结果
  const uploadSuccess = (
    fileList: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
    type: string,
  ) => {
    switch (type) {
      case 'mainImgList':
        setMainFileList(fileList);
        baseInfoForm.setFieldValue('mainImgList', fileList);
        break;
      case 'subImgList':
        setSubFileList(fileList);
        baseInfoForm.setFieldValue('subImgList', fileList);
        break;
      case 'videoList':
        setVideoFileList(fileList);
        baseInfoForm.setFieldValue('videoList', fileList);
        break;
      default:
        break;
    }
  };
  //分类列表
  const getCategoryList = () => {
    CategoryManageAPI.getCategoryRespList({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      setCategoryList(result.list || []);
    });
  };

  const getGambitList = () => {
    ForumManageAPI.getTopicList({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      // 使用map方法创建新的数组，仅包含id和gambitName字段
      const gambitTempList = result.list.map((item) => ({
        id: item.id,
        name: item.gambitName,
      }));
      const gambitListWithDefinedNames = gambitTempList.map((item) => ({
        ...item,
        name: item.name || '',
      }));
      setGambitList(gambitListWithDefinedNames);
    });
  };

  const getCurriculumList = () => {
    MallManageAPI.queryCurriculumInfoList({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      const curriculumListTemp = result.list.map((item) => ({
        id: item.id,
        name: item.curriculumName,
      }));
      setCurriculumList(curriculumListTemp);
    });
  };

  const suggestFileChange = (e: { url: string }[]) => {
    setSuggestFileList(e);
    baseInfoForm.setFieldValue('instructionsUrl', e[0].url);
    // console.log('方案文件回调 --->', e);
  };
  const addTopicModalShowOk = () => {
    setAddTopicModalShow(false);
  };
  const addTopicModalCancel = () => {
    setAddTopicModalShow(false);
  };
  const addTopicModalShowClick = (record?: topicListType[0]) => {
    setCurrentTopicItem(record ? { ...record } : undefined);
    setAddTopicModalShow(true);
  };

  //视频删除
  const deleteVideo = () => {
    setVideoFileList([]);
    baseInfoForm.setFieldValue('videoList', undefined);
  };

  useEffect(() => {
    getCategoryList();
    getGambitList();
    getCurriculumList();
    setSuggestFileList([{ url: baseInfoForm.getFieldValue('instructionsUrl') }]);
  }, []);
  return (
    <div className='base-info'>
      <Form
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 8 }}
        form={baseInfoForm}
        initialValues={{ labelShow: 0, shelfStatus: 1, priceShow: 1, recommend: 0 }}
      >
        <Form.Item
          label='商品名称'
          name='tradeName'
          rules={[{ required: true, message: '请输入商品名称' }]}
        >
          <Input placeholder='请输入商品名称' maxLength={50} />
        </Form.Item>
        <Form.Item
          label='商品描述'
          name='description'
          rules={[{ required: true, message: '请输入商品描述' }]}
        >
          <Input.TextArea rows={4} placeholder='请输入商品描述' maxLength={70} showCount />
        </Form.Item>
        <Form.Item
          label='商品主图'
          name='mainImgList'
          rules={[{ required: true, message: '请上传商品主图' }]}
        >
          <Uploader
            fileUpload
            listType='picture-card'
            onChange={(fileList) => uploadSuccess(fileList, 'mainImgList')}
            defaultFileList={mainFileList}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item label='商品副图' name='subImgList'>
          <Uploader
            fileUpload
            listType='picture-card'
            onChange={(fileList) => uploadSuccess(fileList, 'subImgList')}
            defaultFileList={subFileList}
            fileLength={4}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item label='商品视频' name='videoList'>
          {videoFileList.length ? (
            <div className='goods-video-wrap'>
              {/* eslint-disable-next-line jsx-a11y/media-has-caption */}
              <video
                src={videoFileList[0].url}
                style={{ width: '200px', height: '200px' }}
                controls
              />
              <img src={deletePng} alt='删除' onClick={deleteVideo} />
            </div>
          ) : (
            <Uploader
              fileUpload
              listType='text'
              onChange={(fileList) => uploadSuccess(fileList, 'videoList')}
              defaultFileList={videoFileList}
              fileType={['video/mp4', 'video/avi', 'video/wmv', 'video/rmvb']}
              fileSize={50}
            >
              <Button icon={<UploadOutlined />}>上传视频</Button>
            </Uploader>
          )}
        </Form.Item>
        <Form.Item
          label='商品分类'
          name='categoryId'
          rules={[{ required: true, message: '请选择商品分类' }]}
        >
          <Cascader
            placeholder='请选择商品分类'
            options={categoryList}
            fieldNames={{ label: 'name', value: 'id', children: 'subDTOList' }}
          />
        </Form.Item>
        <Form.Item
          label='商品状态'
          name='shelfStatus'
          rules={[{ required: true, message: '请选择商品状态' }]}
        >
          <Select placeholder='请选择商品状态'>
            <Select.Option value={1}>上架</Select.Option>
            <Select.Option value={0}>下架</Select.Option>
          </Select>
        </Form.Item>
        {userInfo.roleInfo.superAdmin ? (
          <Form.Item label='商品推荐' name='recommend'>
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
        ) : (
          ''
        )}
        <Form.Item label='显示价格' name='priceShow'>
          <Radio.Group>
            <Radio value={1}>显示</Radio>
            <Radio value={0}>不显示</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label='显示标签' name='labelShow'>
          <Radio.Group onChange={labelRadioChange}>
            <Radio value={1}>显示</Radio>
            <Radio value={0}>不显示</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label='关联教程' name='curriculumIds'>
          <Select
            mode='multiple'
            placeholder='请选择关联课程'
            value={baseInfoForm.getFieldValue('curriculumIds')} // 使用defaultCourseIds作为初始值
            showSearch
            optionFilterProp='children'
            filterOption={(input, option) =>
              (option?.children as unknown as string)?.toLowerCase().includes(input.toLowerCase())
            }
          >
            {curriculumList.map((item) => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label='产品说明书'
          name='instructionsUrl'
          rules={[{ required: true, message: '请上传产品说明书' }]}
        >
          <Uploader
            fileUpload
            listType='picture-card'
            defaultFileList={suggestFileList}
            onChange={suggestFileChange}
            fileType={['application/pdf']}
            fileLength={1}
            fileSize={100}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <div className='flex-start gambit-item'>
          <Form.Item
            label='关联话题'
            name='gambitId'
            rules={[{ required: false, message: '请选择话题' }]}
            style={{ width: '100%' }}
          >
            <Select
              placeholder='请选择话题'
              showSearch
              optionFilterProp='children' // 指定筛选的字段
              filterOption={(input, option) =>
                (option?.children as unknown as string)?.toLowerCase().includes(input.toLowerCase())
              }
              style={{ width: '380px' }}
            >
              {gambitList.map((i, j) => (
                <Option key={j} value={i.id}>
                  {i.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Button
            type='primary'
            onClick={() => addTopicModalShowClick()}
            className={'button'}
            icon={<PlusOutlined />}
          >
            新建
          </Button>
        </div>
        {labelShow ? (
          <Form.Item
            label='商品标签'
            name='goodsLabel'
            rules={[{ required: true, message: '请输入商品标签' }]}
          >
            <Input placeholder='请输入商品标签' maxLength={10} />
          </Form.Item>
        ) : (
          ''
        )}
        <AddTopicModal
          open={addTopicModalShow}
          onCancel={addTopicModalCancel}
          onOk={addTopicModalShowOk}
          currentTopicItem={currentTopicItem}
          showProperty={false}
        />
      </Form>
    </div>
  );
});
export default BaseInfo;
