import React, { useState, useEffect, useMemo, memo, useRef } from 'react';
import { Modal } from '@easyv/react-gui';
import { RightOutlined } from '@ant-design/icons';
import styles from './index.less';
import { Radio, Select } from '@easyv/antd';
import Item from './item';
import { connect } from 'react-redux';
import { getMaterialCenter, getUserCategory, addUserStaticMaterical, designResourceType } from 'models/material-lib';
import { uploadAssets } from 'utils/upload';
import message from 'components/message';
import { Link } from 'react-router-dom';
import NoData from '../ScreenHeader/resource/NoData';
const { Option, OptGroup } = Select;

function MaterialModal({
  visible = false,
  onChange,
  loading,
  getMaterialCenter,
  officialMaterial,
  designMaterial,
  getUserCategory,
  tenantId,
  userId,
  type,
  addUserStaticMaterical
}: {
  getUserCategory: any;
  officialMaterial: any;
  designMaterial: any;
  loading: boolean;
  userId: number;
  type: string;
  tenantId: number;
  getMaterialCenter: () => any;
  visible: boolean;
  onChange: (x: any) => void;
  addUserStaticMaterical: (x: any) => any;
}) {
  const ref = useRef<any>(null);
  const [radio, setRadio] = useState(1);
  const [selectId, setSelect] = useState(0);
  const [active, setActive] = useState<number>(-1);
  const handleModeChange = (e) => {
    const { value } = e.target;
    setRadio(value);
    setSelect(0);
  };

  const fileType = ['video', 'mp4'].some((d) => type.includes(d)) ? designResourceType.VIDEO : designResourceType.IMAGE;
  const isOfficialSelected = radio === 1;
  const resources = useMemo(() => {
    return isOfficialSelected ? officialMaterial : designMaterial;
  }, [officialMaterial, designMaterial, isOfficialSelected]);

  useEffect(() => {
    getData();
  }, [radio, visible]);

  useEffect(() => {
    setActive(-1);
  }, [selectId, radio]);

  const optGroup = isOfficialSelected ? resources?.category.filter((d) => !d.parentId) : resources?.category;

  useEffect(() => {
    const [firstItem] = resources?.category;
    if (firstItem && !selectId) {
      if (isOfficialSelected) {
        const [firstGroup] = optGroup;
        const filterList = firstGroup ? resources?.category.filter((d) => d.parentId === firstGroup.id) : [];
        filterList?.length && setSelect(filterList[0].id);
      } else {
        setSelect(firstItem.id);
      }
    }
  }, [optGroup]);

  const getData = async () => {
    if (visible) {
      if (isOfficialSelected) {
        await getMaterialCenter();
      } else {
        await getUserCategory();
      }
    }
  };

  const handleChange = (value) => {
    setSelect(value);
  };
  const onCancel = ({ content = '' }) => {
    setActive(-1);
    onChange({
      visible: false,
      content
    });
  };
  const onOk = () => {
    const item = resourceList.find((d) => d.id === active);
    onCancel({
      content: item.content
    });
  };
  const getKey = (file, type) => {
    return `data/${tenantId}/${userId}/${type}/${file.name}`;
  };
  const onUpload = async (e) => {
    const file = e.target.files[0];
    const type = file.type.split('/')[0];
    const hide = message.loading('上传资源中...', 0);
    const result = await uploadAssets({
      path: file && getKey(file, type),
      file
    });

    if (result) {
      const addResult = await addUserStaticMaterical({
        type: fileType,
        content: result,
        thumb: result,
        name: file.name,
        preview: result,
        userCategoryId: selectId
      });
      ref.current.value = '';

      addResult && getData();
    }
    hide();
  };
  const onActive = (s) => {
    s && setActive(s);
  };

  const resourceList = useMemo(() => {
    return resources.list.filter((d) => selectId === (isOfficialSelected ? d.platformCategory.id : d.userCategoryId));
  }, [resources, selectId]);

  return (
    <Modal
      width={652}
      onCancel={onCancel}
      onOk={onOk}
      wrapClassName={styles.wrapClassName}
      visible={visible}
      title="选择需要更改的内容"
      okText="确认"
      cancelText="取消">
      <input type="file" accept="image/*,video/*" ref={ref} onChange={onUpload} className={styles.file} />
      <div className={styles.groupButton}>
        <Radio.Group onChange={handleModeChange} value={radio} style={{ marginBottom: 8 }}>
          <Radio.Button value={1}>官方素材</Radio.Button>
          <Radio.Button value={2}>我的收藏</Radio.Button>
        </Radio.Group>
        <Link to={'/resource'}>
          <span>资源中心</span>
          <RightOutlined />
        </Link>
      </div>
      <div className={styles.dropdown}>
        <Select dropdownClassName={styles.select} value={selectId} style={{ width: 210 }} onChange={handleChange}>
          {isOfficialSelected ? (
            optGroup.length ? (
              optGroup.map((d) => {
                return (
                  <OptGroup label={d.name} key={d.id}>
                    {resources?.category
                      .filter((x) => x.parentId && x.parentId === d.id)
                      .map((item) => {
                        return (
                          <Option value={item.id} key={item.id}>
                            {item.name}
                          </Option>
                        );
                      })}
                  </OptGroup>
                );
              })
            ) : (
              <Option key={-1} value={0}>
                未分组
              </Option>
            )
          ) : (
            <>
              {resources?.category.map((item) => {
                return (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                );
              })}
              {/* <Option key={-1} value={0}>
                未分组
              </Option> */}
            </>
          )}
        </Select>
      </div>

      <div className={styles.card}>
        <div className={styles.cardBox}>
          {loading ? (
            'loading...'
          ) : (
            <>
              {radio === 2 ? (
                <Item
                  onUpload={() => {
                    ref.current?.click();
                  }}
                  type="upload"
                />
              ) : null}
              {resourceList.length ? (
                resourceList
                  .filter((d) => ![designResourceType.MODEL].includes(d.type))
                  .map((d) => (
                    <Item
                      disabled={!(fileType === d.type)}
                      value={active}
                      type={d.type}
                      id={d.id}
                      thumb={d.thumb}
                      key={d.id}
                      name={d.name}
                      onActive={onActive}
                    />
                  ))
              ) : radio === 1 ? (
                <NoData />
              ) : null}
            </>
          )}
        </div>
      </div>
    </Modal>
  );
}
function mapStateToProps({ materialLib, user }) {
  const { userInfo } = user;
  const { loading, designMaterial, myFavorite } = materialLib;
  const { tenantId, userId } = userInfo;
  return {
    designMaterial: myFavorite.designMaterial,
    officialMaterial: designMaterial,
    loading,
    tenantId,
    userId
  };
}
export default connect(mapStateToProps, {
  getMaterialCenter,
  getUserCategory,
  addUserStaticMaterical
})(memo(MaterialModal));
