import {
  ProCard,
  ProForm,
  ProFormDateTimeRangePicker,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, message, Row } from 'antd';
import Upload, { RcFile } from 'antd/es/upload';
import React, { useRef  } from 'react';
import { history } from '@umijs/max';
import { getClassesTypeListForAdminUsingPost } from '@/services/pop-b2b2c/pbcTrainingClassesTypeController';
import { addOrUpdateClassUsingPost } from '@/services/pop-b2b2c/pbcTrainingClassesController';


const Detail: React.FC<any> = () => {

  const formRef = useRef<ProFormInstance>();

  const onSave = () => {
    formRef.current?.submit()
  }

  const onSubmit = async (values: any) => {

    let pbcImages = ""
    if (values.pbcImages && values.pbcImages.length > 0) {
      if (
        values.pbcImages[0].response &&
        values.pbcImages[0].response.retcode
      ) {
        pbcImages = values.pbcImages[0].response.data;
      }
    }
    
    const params: API.PbcTrainingClasses_ = {
      ...values,
      pbcImages,
      pbcTrainingStartDatetime: values.pbcTrainingStartDatetime[0],
      pbcTrainingEndDatetime: values.pbcTrainingStartDatetime[1]
    }
    const msg = await addOrUpdateClassUsingPost(params)
    if (msg.retcode && msg.data) {
      message.success("创建成功！")
      history.replace('/training-classes/detail/' + msg.data.pbcId + "?isEdit=1");
      return true
    } else {
      message.error(msg.retmsg)
      return false
    }
  }

  return (
    <PageContainer
      header={{
        title: '',
      }}
      footer={[
        <Button
          key="back"
          onClick={() => {
            history.back();
          }}
        >
          返回
        </Button>,
        <Button type="primary" key="submit" onClick={onSave}>
          保存
        </Button>
      ]}
    >
      <ProForm layout="horizontal" labelAlign="left" requiredMark={false} formRef={formRef} onFinish={onSubmit} submitter={false}>
        <ProFormText name="pbcClassesTypeName" hidden />
        <ProCard title="基本信息" style={{ marginBottom: 12 }}>
          <Row gutter={20}>
            <Col span={12}>
              <ProFormText label="课程名称" name="pbcTitle" rules={[
                { required: true, message: '请输入课程名称' },
              ]} />
            </Col>
            <Col span={12}>
              <ProFormSelect
                label="课程类型"
                name="pbcClassesTypeId"
                rules={[
                  { required: true, message: '请选择课程类型' }
                ]}
                request={ async () => {
                  const msg = await getClassesTypeListForAdminUsingPost();
                  if (msg.retcode && msg.data) {
                    return msg.data;
                  }
                  return [];
                }}
                fieldProps={{ 
                  onChange(value, option: any) {
                    console.log(option)
                    formRef.current?.setFieldsValue({
                      pbcClassesTypeName: option.label
                    })
                  },
                  showSearch: true,
                  fieldNames: { label: 'pbcType', value: 'pbcId' }
                }}
              />
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={12}>
              <ProFormDigit label="总课次" name="pbcClassesSubCount" min={0} fieldProps={{ precision: 0 }} rules={[
                { required: true, message: '请输入总课次' },
              ]} />
            </Col>
            <Col span={12}>
              <ProFormUploadButton
                label="课程缩略图"
                name="pbcImages"
                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('pbcImages', [])
                        }
                        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: '请上传课程缩略图' }
                ]}
              />
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={12}>
              <ProFormSelect label="教学方式" name="pbcTeachMethod" options={['线上', '线下']} rules={[
                { required: true, message: '请选择教学方式' },
              ]} />
            </Col>
            <Col span={8}>
              <ProFormDateTimeRangePicker label="培训时间" name="pbcTrainingStartDatetime" rules={[
                { required: true, message: '请选择培训时间' },
              ]} />
            </Col>
          </Row>
        </ProCard>
      </ProForm>
    </PageContainer>
  );
};

export default Detail;
