import React, { useState, useEffect, useRef } from 'react';
import { Modal } from '@easyv/react-gui';
import { RightOutlined } from '@ant-design/icons';
import styles from './index.less';
import { Radio, Select, Spin } from '@easyv/antd';
import { LoadingOutlined } from '@ant-design/icons';
import Item from './item';
import { connect } from 'react-redux';
import {
  getResourceUserCategory,
  getResourceUserMaterical,
  getDesignMaterial,
  getPlatformCategory,
  designResourceType,
  addUserStaticMaterical,
} 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;
const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;

function ModelToReplace({
  visible = false,
  tenantId,
  onChange,
  userId,
  accept,
  addUserStaticMaterical,
  getResourceUserMaterical, // 用户素材资源
  getResourceUserCategory, // 用户素材分类
  getPlatformCategory, // 官方素材分类
}: {
  userId: number;
  tenantId: number;
  accept: string;
  visible: boolean;
  onChange?: (x: any) => void;
  getResourceUserMaterical: (x?: designResourceType) => any;
  getResourceUserCategory: (x?: designResourceType) => any;
  getPlatformCategory: (x?: designResourceType) => any;
  addUserStaticMaterical: (x: any) => any;
}) {
  const ref = useRef<any>(null);
  const [radio, setRadio] = useState(1);
  const [selectId, setSelect] = useState(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [active, setActive] = useState<number>(-1);
  const [category, setCategory] = useState<
    {
      parentId: number;
      id: number;
      name: string;
    }[]
  >([]);
  const [material, setMaterial] = useState<
    {
      parentId: number;
      id: number;
      content: string;
      thumb?: string;
      type: designResourceType;
      name: string;
    }[]
  >([]);
  const isOfficialSelected = radio === 1; // 官方分类

  const handleModeChange = (e) => {
    const { value } = e.target;
    setRadio(value);
    setSelect(0);
    setCategory([]);
    setMaterial([]);
  };
  useEffect(() => {
    getData();
  }, [radio, visible]);

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

  const getData = async () => {
    if (visible) {
      setLoading(true);
      let _category = [],
        _material = [];
      if (radio === 1) {
        _category = await getPlatformCategory(3);
        _material = await getDesignMaterial('3');
      } else if (radio === 2) {
        _material = await getResourceUserMaterical(3);
        _category = await getResourceUserCategory(3);
      }
      setLoading(false);
      setCategory(_category ?? []);
      setMaterial(_material ?? []);
      if (!selectId) {
        const initSelectId = getInitSelectId(_category);
        initSelectId && setSelect(initSelectId);
      }
    }
  };

  const getInitSelectId = (category): number => {
    if (isOfficialSelected) {
      const groups = category.filter((d) => !d.parentId);
      let id = 0;
      groups.map((d) => {
        d.list = category.filter((x) => x.parentId === d.id);
        if (d.list.length && !id) {
          id = d.list[0].id;
        }
        return d;
      });
      return id;
    } else {
      return category.length && category[0].id;
    }
  };

  const handleChange = (value) => {
    setSelect(value);
  };
  const onCancel = ({ content = '' }) => {
    setActive(-1);
    onChange?.({
      visible: false,
      content,
    });
  };
  const onOk = () => {
    const item:
      | {
          content: string;
          parentId: number;
          id: number;
          thumb?: string;
          type: designResourceType;
          name: string;
        }
      | undefined = material?.find((d) => d.id === active);
    item
      ? onChange?.({
          visible: false,
          content: item.content,
        })
      : message.error('保存失败');
  };
  const getKey = (file, type) => {
    return `data/${tenantId}/${userId}/${type}/${file.name}`;
  };
  const onUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) {
      message.error('文件上传解析异常!');
      return false;
    }
    const hide = message.loading('上传资源中...', 0);
    const result = await uploadAssets({
      path: file && getKey(file, 'model'),
      file,
    });
    if (result) {
      const addResult = await addUserStaticMaterical({
        type: 3,
        content: result,
        name: file.name,
        thumb: result,
        preview: result,
        userCategoryId: selectId,
      });
      ref.current.value = '';
      addResult && getData();
    }
    hide();
  };
  const onActive = (s) => {
    s && setActive(s);
  };

  const optGroup = category?.filter((d) => !d.parentId),
    filterMaterial = (material || []).filter((d) => d.type === 3),
    resources = isOfficialSelected
      ? filterMaterial.filter((d: any) => d.platformCategory.id === selectId)
      : filterMaterial.filter((d: any) => d.userCategoryId === selectId);

  const accepts: string[] = accept ? accept.split(',') : [];

  return (
    <Modal
      width={652}
      onCancel={onCancel}
      onOk={onOk}
      wrapClassName={styles.wrapClassName}
      visible={visible}
      title="选择需要更改的内容"
      okButtonProps={{
        disabled: !(active > 0),
      }}
      okText="确认"
      cancelText="取消">
      <input type="file" accept={accept} 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}>
                    {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>
            )
          ) : (
            <>
              {category?.map((item) => {
                return (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                );
              })}
              {/* <Option key={-1} value={0}>
                未分组
              </Option> */}
            </>
          )}
        </Select>
      </div>

      <Spin spinning={loading} indicator={antIcon}>
        <div className={styles.card}>
          <div className={styles.cardBox}>
            {
              <>
                {radio === 2 ? (
                  <Item
                    onUpload={() => {
                      ref.current?.click();
                    }}
                    type="upload"
                  />
                ) : null}
                {resources?.length ? (
                  resources.map((d: any) => (
                    <Item
                      disabled={!accepts.some((v) => d.content.includes(v))}
                      value={active}
                      id={d.id}
                      thumb={d.thumb}
                      key={d.id}
                      name={d.name}
                      onActive={onActive}
                    />
                  ))
                ) : radio === 1 ? (
                  <NoData />
                ) : null}
              </>
            }
          </div>
        </div>
      </Spin>
    </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, {
  getResourceUserCategory,
  getPlatformCategory,
  getResourceUserMaterical,
  addUserStaticMaterical,
})(ModelToReplace);
