import React, { useRef, useState } from 'react';
import { DrawerForm, ProFormInstance, ProFormSelect, ProFormText, ProFormUploadButton } from '@ant-design/pro-components';
import { message, Select } from 'antd';
import Upload, { RcFile } from 'antd/es/upload';
import Constants from '@/constants';
export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.PbcBanner_>;
export type UpdateBannerFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  afterClose: () => void;
  updateModalVisible: boolean;
  values: Partial<API.PbcBanner_>;
};

const { Option } = Select;

const UpdateBannerForm: React.FC<UpdateBannerFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [linkType, setLinkType] = useState(props.values.pbcLink && props.values.pbcLink.includes('||') ? props.values.pbcLink.split('||')[0] + '||' : 'web||');

  const selectBefore = (
    <Select defaultValue={linkType} onChange={(value) => {
      setLinkType(value);
    }}>
      <Option value="web||">页面链接</Option>
      <Option value="home||">商家主页</Option>
    </Select>
  );

  return (
    <DrawerForm
      width={640}
      requiredMark={false}
      title={props.values.pbcId ? '编辑' : '新增'}
      open={props.updateModalVisible}
      formRef={formRef}
      onFinish={(value: any) => {
        let pbcBannerImage = ""
        if (value.pbcBannerImage && value.pbcBannerImage.length > 0) {
          if (value.pbcBannerImage[0].uid === '-1') {
            pbcBannerImage = value.pbcBannerImage[0].url || '';
          }
          if (
            value.pbcBannerImage[0].response &&
            value.pbcBannerImage[0].response.retcode
          ) {
            pbcBannerImage = value.pbcBannerImage[0].response.data;
          }
        }
        return props.onSubmit({ ...value, pbcBannerImage, pbcId: props.values.pbcId, pbcLink: value.pbcLink ? linkType + value.pbcLink : '' })
      }}
      drawerProps={{
        destroyOnHidden: true,
        afterOpenChange: (visible) => {
          if (!visible) props.afterClose();
        }
      }}
      
      initialValues={{
        pbcTitle: props.values.pbcTitle,
        pbcBannerType: props.values.pbcBannerType ? props.values.pbcBannerType + '' : null,
        pbcLink: props.values.pbcLink && props.values.pbcLink.includes('||') ? props.values.pbcLink.split('||')[1] : '',
        pbcBannerImage: props.values.pbcBannerImage ? [{
          uid: '-1',
          name: props.values.pbcBannerImage.substring(props.values.pbcBannerImage.lastIndexOf('/') + 1),
          status: 'done',
          url: props.values.pbcBannerImage,
        }] : []
      }}
      onOpenChange={(visible) => {
        formRef.current?.resetFields();
        if (!visible) {
          props.onCancel();
        }
      }}
    >
      <ProFormText
        placeholder={'请输入标题'}
        label="标题"
        rules={[
          {
            required: true,
            message: '标题为必填项',
          },
        ]}
        width="md"
        name="pbcTitle"
      />
      <ProFormUploadButton
        label="banner图"
        name="pbcBannerImage"
        max={1}
        fieldProps={{
          name: 'file',
          accept: 'image/*',
          multiple: true,
          headers: {
            authorization: localStorage.getItem('token') ?? '',
          },
          onChange: (info: any) => {
            switch (info.file.status) {
              case 'done':
                if (info.file.response.retcode === 0) {
                  message.error(info.file.response.retmsg);
                  formRef.current?.setFieldValue('pbcBannerImage', [])
                }
                break;
              default:
                break;
            }
          },
          action: process.env.BASE_URL + '/oss/imgUpload',
          beforeUpload(file: RcFile) {
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
              message.error('图片大小不能超过10MB!');
            }
            return isLt10M || Upload.LIST_IGNORE;
          },
          onPreview: async (file) => {
            if (file.uid === '-1') {
              window.open(file.url);
            }
            if (file.response && file.response.retcode) {
              window.open(file.response.data);
            }
          },
          listType: 'picture-card',
        }}
        rules={[
          { required: true, message: '请上传banner图' }
        ]}
      />
      <ProFormSelect
        name="pbcBannerType"
        label="类型"
        width="md"
        valueEnum={Constants.pbcBannerType}
        placeholder="请选择类型"
        rules={[{ required: true, message: '请选择类型' }]}
      />
      <ProFormText
        placeholder={linkType === 'web||' ? '请输入页面链接' : '请输入商家id'}
        label="链接"
        width="md"
        name="pbcLink"
        addonBefore={selectBefore}
      />
      {/* <ProFormDigit
        placeholder={'请输入排序'}
        label="排序"
        min={1}
        fieldProps={{ precision: 0 }}
      /> */}
    </DrawerForm>
  );
};

export default UpdateBannerForm;
