import React, { Fragment, useState, useEffect } from 'react';
import { Form, Input, Select, Radio, Checkbox, Switch } from '@easyv/antd';
import UploadThumb from 'components/NewUploadThumb';
import { useMousetrapPause } from 'components/easyUse';
import ConfirmModal from 'components/ConfirmModal';
import { objectValueTrim, getAssetsUrl, priceConvert } from 'utils/utils';
import styles from '../SortModal.less';
import { getLabelsById } from 'services/labelsResource';
import { ResourcesType } from 'models/adminPanel.types';
import PriceTages from '@/components/PriceTages';
import message from '@/components/message';
import { adminPanelAuthorityConfig, adminPanelTypeOptions } from '@/constants/config';
const { Option } = Select;

export default function EditModal({
  children,
  data,
  categorys,
  edit,
  labelsAllList = [],
  onOk,
}: {
  children: React.ReactNode;
  data?: any;
  categorys: any;
  edit?: boolean;
  labelsAllList: string[];
  onOk: (value: any) => any;
}) {
  const [visible, setVisible] = useState(false);
  const [isPay, setIsPay] = useState(false);
  const [thumb, setThumb] = useState();
  const [form] = Form.useForm();
  const { validateFields } = form;
  const [uploading, setUploading] = useState(false);
  const labelsOption = labelsAllList.map((d) => (
    <Option key={d} value={d}>
      {d}
    </Option>
  ));

  useEffect(() => {
    visible && setIsPay(!!data?.needPaid);
  }, [data, visible]);

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

  const handleSubmit = () => {
    validateFields().then(async (values) => {
      if (values.needPaid && !values.price) {
        message.error('请填写价格');
        return;
      }
      setUploading(true);
      const param: any = {
        ...values,
      };
      if (param.price) {
        // 单位分
        param.price = priceConvert(param.price);
      }
      if (thumb) {
        param.thumb = thumb;
      }
      if (data?.id) {
        param.id = data.id;
      }
      param.recommended = param.recommended ? 1 : 0;
      if (!edit && param.labels?.length === 0) {
        param.labels = undefined;
      }
      const result = await onOk(objectValueTrim(param));
      setUploading(false);
      if (result) {
        setVisible(false);
      }
    });
  };

  const updateLabelsById = async () => {
    const _labelsList = await getLabelsById(data.id, ResourcesType.MATERIAL_MODEL);
    const _data = { ...data, labels: _labelsList.names };
    form.setFieldsValue({
      ..._data,
      price: priceConvert(data?.price, 'remove'),
      originPrice: priceConvert(data?.originPrice, 'remove'),
    });
  };
  useEffect(() => {
    if (edit && visible) {
      updateLabelsById();
    }
    if (!visible && form && form.resetFields) {
      form.resetFields();
      setIsPay(false);
    }
  }, [visible]);

  useMousetrapPause(visible);

  const defaultData = data
    ? {
        ...data,
        price: priceConvert(data?.price, 'remove'),
        originPrice: priceConvert(data?.originPrice, 'remove'),
      }
    : {
        type: 1,
        edition: 4,
        officialCategoryId: categorys[0]?.children[0]?.id,
        needPaid:false
      };

  return (
    <Fragment>
      <span onClick={() => setVisible(true)}>{children}</span>
      <ConfirmModal
        title={edit ? '编辑' : '新建'}
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={handleSubmit}
        destroyOnClose={true}
        footer={true}
        confirmLoading={uploading}
        theme="black">
        <Form
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          initialValues={defaultData}
          onValuesChange={(changedValues, allValues) => {
            setIsPay(allValues.needPaid);
          }}
          form={form}
          autoComplete="off">
          <Form.Item
            label="资源名称"
            name="name"
            rules={[
              { required: true, message: '组件名称必填', whitespace: true },
              { min: 2, max: 16, message: '请输入2～16个字符' },
            ]}>
            <Input placeholder="请输入名称，2～16个字符" />
          </Form.Item>
          <Form.Item
            label="选择分组"
            name="officialCategoryId"
            rules={[{ required: true, message: '选择分组' }]}>
            <Select dropdownClassName={styles.selectDrop}>
              {categorys.map((d) => {
                return (
                  <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="type">
            <Radio.Group>
              <Radio value={1}>图片</Radio>
              <Radio value={2}>视频</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}>
            {({ getFieldValue }) => {
              const type = getFieldValue('type');
              return (
                <Form.Item
                  label="素材上传"
                  name="content"
                  rules={[{ required: true, message: '素材不能为空' }]}>
                  <UploadThumb
                    type={type === 1 ? 'image' : 'video'}
                    url={data?.content ? getAssetsUrl(`${data.content}`) : null}
                    maxSize={type === 1 ? 2 * 1024 * 1024 : 200 * 1024 * 1024}
                    onChange={setThumb}
                  />
                </Form.Item>
              );
            }}
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}>
            {({ getFieldValue }) => {
              const type = getFieldValue('type');
              if (type === 2) {
                return (
                  <Form.Item label="缩略图" name="thumb">
                    <UploadThumb
                      url={data?.thumb ? getAssetsUrl(`${data.thumb}`):null}
                      maxSize={200 * 1024}
                      onChange={setThumb}
                    />
                  </Form.Item>
                );
              } else {
                return null;
              }
            }}
          </Form.Item>
          <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>
          <Form.Item label="官方推荐" name="recommended" valuePropName="checked">
            <Checkbox />
          </Form.Item>
          <Form.Item label="是否付费" name={'needPaid'} valuePropName={'checked'}>
            <Switch disabled={edit} />
          </Form.Item>
          <Form.Item
            label="开放权限"
            name="edition"
            rules={[{ required: true, message: '请选择权限' }]}>
            <Radio.Group
              options={isPay ? adminPanelAuthorityConfig : adminPanelTypeOptions}
              optionType="button"
              buttonStyle="solid"
            />
          </Form.Item>
          {isPay && (
            <PriceTages
              setFieldsValue={form.setFieldsValue}
              Form={Form}
              value={defaultData.price}
            />
          )}
        </Form>
      </ConfirmModal>
    </Fragment>
  );
}
