import React, { useCallback, useState, useEffect, useRef } from 'react';
import { Form, Input, Switch, Select, Radio } from '@easyv/antd';
import ConfirmModal from 'components/ConfirmModal';
import UploadThumb from 'components/NewUploadThumb';
import { useMousetrapPause } from 'components/easyUse';
import styles from './EditModal.less';
import { connect } from 'react-redux';
import { getPlatformCategory } from 'models/material-lib';
import { getGroupedCategorys ,priceConvert} from 'utils/utils';
import { getModules } from 'models/module';
import { getAssetsUrl } from 'utils/utils';
import PriceTages from '@/components/PriceTages';
import message from '@/components/message';
import { adminPanelAuthorityConfig, adminPanelTypeOptions } from '@/constants/config';

const { Option } = Select;

function EditModal({
  visible,
  id,
  confirmLoading,
  needPaid,
  price,
  name,
  category,
  platformCategory,
  thumb,
  preview,
  getPlatformCategory,
  recommended = true,
  edition = 4,
  categorys,
  onCancel,
  getModules,
  labelsAllList,
  onOk,
}: {
  visible: boolean;
  id?: string;
  needPaid: boolean;
  price: number;
  confirmLoading: boolean;
  name?: string;
  category?: number;
  thumb?: string;
  preview?: string;
  recommended?: boolean;
  platformCategory: any[];
  edition?: 1 | 2 | 3 | 4;
  labelsAllList?: string[];
  categorys: any[];
  onCancel: () => void;
  getModules: () => void;
  getPlatformCategory: (x: 1 | 2) => any;
  onOk: (param) => void;
}) {
  const isFail = useRef(true);
  const [type, setType] = useState<1 | 2>(1);
  const [isTageHide, setTageHide] = useState(false);
  const [form] = Form.useForm();
  const { validateFields, setFieldsValue, getFieldValue, resetFields } = form;
  const labelsOption =
    labelsAllList &&
    labelsAllList.map((d) => (
      <Option key={d} value={d}>
        {d}
      </Option>
    ));

  useEffect(() => {
    if ([1,3].includes(form.getFieldValue('edition'))&& isTageHide) {
      form.setFieldsValue({
        edition: 4,
      });
    }
  }, [isTageHide, form]);

  useEffect(() => {
    visible && setTageHide(!!needPaid);
  }, [needPaid, visible]);

  useEffect(() => {
    visible ? getModules() : setTageHide(false);
  }, [visible]);

  useEffect(() => {
    isFail.current && !platformCategory.length && platformCategorys();
  }, [platformCategory, isFail]);

  const platformCategorys = async () => {
    const result = await getPlatformCategory(2);
    if (!result || !result.length) {
      isFail.current = false;
    }
  };
  const selectList = type === 1 ? platformCategory : categorys;
  const groupedCategorys = getGroupedCategorys(selectList).filter((d) => d.children.length);
  useEffect(() => {
    visible &&
      Array.isArray(selectList) &&
      !selectList.some((d) => d.id === getFieldValue('platformCategoryId')) &&
      setFieldsValue({
        platformCategoryId: groupedCategorys[0]?.children[0]?.id,
      });

    if (!visible) {
      resetFields();
    }
  }, [setFieldsValue, selectList, visible, type]);

  const handleThumbChange = useCallback((file, code) => {
    const o = {};
    o[code] = file;
    setFieldsValue(o);
  }, []);

  const handleSubmit = useCallback(() => {
    validateFields()
      .then((values) => {
        if (values.needPaid && !values.price) {
          message.error('请填写价格');
          return;
        }
        const { platformCategoryId,needPaid = false, ...rest } = values;
        const newValues = { ...rest ,needPaid};
        if (type === 2) {
          // 素材广场
          newValues['officialCategoryId'] = platformCategoryId;
        } else {
          // 官方素材
          newValues['platformCategoryId'] = platformCategoryId;
        }
        if (newValues.price) {
          // 单位分
          newValues.price = priceConvert(newValues.price);
        }
        if (newValues.labels?.length === 0) {
          newValues.labels = undefined;
        }

        onOk({
          ...newValues,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }, [type]);

  useMousetrapPause(visible);

  const defaultData = {
    platformCategoryId: category,
    type,
    preview,
    recommended,
    edition,
    name,
    price: priceConvert(price,'remove'),
  };

  return (
    <ConfirmModal
      visible={visible}
      confirmLoading={confirmLoading}
      title={id ? '编辑资源' : '保存为资源'}
      footer={true}
      theme={'black'}
      wrapClassName={styles.editConfirmModal}
      okText="确定"
      onCancel={onCancel}
      onOk={handleSubmit}
      destroyOnClose>
      <Form
        labelCol={{ span: 5 }}
        onValuesChange={(changedValues, allValues) => {
          setTageHide(allValues.needPaid);
        }}
        wrapperCol={{ span: 19 }}
        form={form}
        initialValues={defaultData}>
        <Form.Item
          label="组件名称"
          name="name"
          rules={[
            { required: true, whitespace: true, message: '请输入组件名称' },
            { max: 12, message: '超过12个字符' },
          ]}>
          <Input placeholder="请输入组件名称，12个字符以内" autoComplete="off" />
        </Form.Item>
        <Form.Item label="选择分类" required name="platformCategoryId">
          <Select dropdownClassName={styles.select} style={{ width: '50%' }}>
            {groupedCategorys.map((d) => (
              <Select.OptGroup key={d.id} label={d.name}>
                {d.children?.map((v) => {
                  return (
                    <Select.Option key={v.id} value={v.id}>
                      {v.name}
                    </Select.Option>
                  );
                })}
              </Select.OptGroup>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="缩略图"
          name="thumb"
          rules={[{ required: true, message: '请上传缩略图' }]}>
          <UploadThumb
            url={thumb ? getAssetsUrl(`${thumb}`) : null}
            onChange={(file) => {
              handleThumbChange(file, 'thumb');
            }}
          />
        </Form.Item>
        <Form.Item
          label="预览图"
          name="preview"
          rules={[{ required: true, message: '请上传预览图' }]}>
          <UploadThumb
            maxSize={2 * 1024 * 1024}
            url={thumb ? getAssetsUrl(`${preview}`) : null}
            onChange={(file) => {
              handleThumbChange(file, 'preview');
            }}
          />
        </Form.Item>
        {type === 2 && (
          <Form.Item
            label="标签（选填）"
            name="labels"
            className={styles.labels}
            rules={[
              {
                validator: (rule, value) => {
                  if (value?.length) {
                    if (value[value.length - 1].length > 6 || value.length > 10) {
                      return Promise.reject('最多输入10个标签，每个标签长度不可超过6');
                    }
                  }
                  return Promise.resolve();
                },
              },
            ]}>
            <Select
              mode="tags"
              style={{ width: '100%' }}
              dropdownClassName={styles.dropMenu}
              dropdownStyle={{ backgroundColor: '#181a24' }}
              placeholder="最多输入10个标签，每个标签长度不可超过6">
              {labelsOption}
            </Select>
          </Form.Item>
        )}
        {type === 2 && (
          <Form.Item label="官方推荐" name="recommended" valuePropName="checked">
            <Switch />
          </Form.Item>
        )}
        <Form.Item label="类型">
          <Radio.Group
            value={type}
            onChange={(e) => {
              setType(e.target.value);
            }}>
            <Radio value={1}>官方素材</Radio>
            {!window.appConfig.LOCAL && <Radio value={2}>素材广场</Radio>}
          </Radio.Group>
        </Form.Item>
        {type === 2 && (
          <Form.Item label="是否付费" name={'needPaid'} valuePropName={'checked'}>
            <Switch disabled={!!id} />
          </Form.Item>
        )}

        {!window.appConfig.LOCAL && type === 2 && (
          <Form.Item label="开放权限" name="edition">
            <Radio.Group
              options={isTageHide ? adminPanelAuthorityConfig : adminPanelTypeOptions}
              optionType="button"
              buttonStyle="solid"
            />
          </Form.Item>
        )}
        {type === 2 && isTageHide && (
          <PriceTages setFieldsValue={setFieldsValue} Form={Form} value={defaultData.price} />
        )}
      </Form>
    </ConfirmModal>
  );
}
const mapStateToProps = ({ materialLib }) => {
  return {
    platformCategory: materialLib.platformCategory,
  };
};
export default connect(mapStateToProps, {
  getPlatformCategory,
  getModules,
})(EditModal);
