import {
  ModalForm,
  ProForm,
  ProFormSwitch,
  ProFormTreeSelect,
  ProFormUploadButton
} from '@ant-design/pro-components';
import {ProFormText} from '@ant-design/pro-components';
import {ProFormSelect, ProFormDependency} from '@ant-design/pro-components';
import {FormattedMessage, useIntl} from '@umijs/max';
import React from 'react';
import {postUserAdminRegister} from '@/services/system/User';
import {postRoleGetRoleFkSelect} from "@/services/system/Role";
import {postDepartmentGetDepartmentFkSelect} from "@/services/system/Department";
import {postPostGetPostFkSelect} from "@/services/system/Post";
import {Form, message} from 'antd';
import {beforeUploadImage, handleOneFile} from "@/utils/common";
// @ts-ignore
import cookie from 'react-cookies';

export type CreateFormProps = {
  createModalOpen: boolean;
  handleModal: () => void;
  values: Partial<API.Register>;
  reload: any;
};
const CreateForm: React.FC<CreateFormProps> = (props) => {

  const intl = useIntl();
  const [form] = Form.useForm<API.Register>();

  return (
    <ModalForm<API.Register>
      title={intl.formatMessage({
        id: 'common.modal.table.create.title',
        defaultMessage: '$$$',
      })}
      open={props.createModalOpen}
      name={'createUserForm'}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => props.handleModal(),
      }}
      submitTimeout={2000}
      onFinish={async (values: any) => {
        console.log(values)
        if ((values?.roleIds || []).length) {
          values.roleId = values.roleIds[0]
          values.roleIds = values.roleIds.join(',')
        }
        if ((values?.postIds || []).length) {
          values.postId = values.postIds[0]
          values.postIds = values.postIds.join(',')
        }
        handleOneFile(values, 'avatarId')
        console.log(values)
        postUserAdminRegister(values).then(() => {
          message.success(intl.formatMessage({id: 'common.success', defaultMessage: '$$$'}))
          props.reload()
        }).catch(() => {
          message.error(intl.formatMessage({id: 'common.error', defaultMessage: '$$$'}))
        })
        props.handleModal();
        return true;
      }}
    >

      <ProForm.Group>
        <ProFormText width="md" name="userName"
                     label={<FormattedMessage id="system.user.table.list.userName" defaultMessage="$$$"/>}
                     placeholder={`${intl.formatMessage({
                       id: 'common.please_input',
                       defaultMessage: '$$$'
                     })}${intl.formatMessage({id: 'system.user.table.list.userName', defaultMessage: '$$$'})}`}
                     required={true}
                     rules={[
                       {
                         required: true,
                         message: (
                           <FormattedMessage
                             id="system.user.table.rule.required.name"
                             defaultMessage="name is required"
                           />
                         ),
                       },
                     ]}
        />
        <ProFormText width="md" name="nickName"
                     label={<FormattedMessage id="system.user.table.list.nickName" defaultMessage="$$$"/>}
                     placeholder={`${intl.formatMessage({
                       id: 'common.please_input',
                       defaultMessage: '$$$'
                     })}${intl.formatMessage({id: 'system.user.table.list.nickName', defaultMessage: '$$$'})}`}
                     required={true}
                     rules={[
                       {
                         required: true,
                         message: (
                           <FormattedMessage
                             id="system.department.table.rule.required.nickName"
                             defaultMessage="nickName is required"
                           />
                         ),
                       },
                     ]}
        />
        <ProFormText.Password width="md" name="password"
                              label={<FormattedMessage id="system.user.table.list.password" defaultMessage="$$$"/>}
                              placeholder={`${intl.formatMessage({
                                id: 'common.please_input',
                                defaultMessage: '$$$'
                              })}${intl.formatMessage({id: 'system.user.table.list.password', defaultMessage: '$$$'})}`}
                              required={true}
                              rules={[
                                {
                                  required: true,
                                  message: (
                                    <FormattedMessage
                                      id="user.user.table.rule.required.password"
                                      defaultMessage="password is required"
                                    />
                                  ),
                                },
                              ]}
        />
        <ProFormDependency name={['password']}>
          {
            (record) => {
              return (
                <ProFormText.Password width="md" name="password_re"
                    label={<FormattedMessage id="system.user.table.list.password_re"
                                             defaultMessage="$$$"/>}
                    placeholder={`${intl.formatMessage({
                      id: 'common.please_input',
                      defaultMessage: '$$$'
                    })}${intl.formatMessage({
                      id: 'system.user.table.list.password_re',
                      defaultMessage: '$$$'
                    })}`}
                    required={true}
                    rules={[
                      {
                        required: true,
                        message: (
                          <FormattedMessage
                            id="user.user.table.rule.required.password"
                            defaultMessage="password is required"
                          />
                        ),
                      },
                      () => ({
                        validator(rule, value) {
                          if (!value || record.password === value) {
                            return Promise.resolve()
                          }
                          return Promise.reject(intl.formatMessage({id: 'system.user.table.rule.password.not_same', defaultMessage: '$$$'}))
                        }
                      })
                    ]}
                />
              )
            }
          }

        </ProFormDependency>

      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect width="md" name="roleIds" showSearch
                       fieldProps={{
                         mode: 'multiple',
                       }}
                       label={<FormattedMessage id="system.user.table.list.roleIds" defaultMessage="$$$"/>}
                       placeholder={`${intl.formatMessage({
                         id: 'common.please_select',
                         defaultMessage: '$$$'
                       })}${intl.formatMessage({id: 'system.user.table.list.roleId', defaultMessage: '$$$'})}`}
                       required={false}
                       request={
                         async (keyWord) => {
                           let resp = await postRoleGetRoleFkSelect({keyword: keyWord.keyWords})
                           return resp.data.list.map((v: any)=>{
                             return {
                                label: v.name,
                                value: v.id
                             }
                           })
                         }
                       }
        >

        </ProFormSelect>
        <ProFormSelect width="md" name="postIds" showSearch
                       fieldProps={{
                         mode: 'multiple',
                       }}
                       label={<FormattedMessage id="system.user.table.list.postIds" defaultMessage="$$$"/>}
                       placeholder={`${intl.formatMessage({
                         id: 'common.please_select',
                         defaultMessage: '$$$'
                       })}${intl.formatMessage({id: 'system.user.table.list.postId', defaultMessage: '$$$'})}`}
                       required={false}
                       request={
                         async (keyWord) => {
                           let resp = await postPostGetPostFkSelect({keyword: keyWord.keyWords})
                           return resp.data.list.map((v: any)=>{
                             return {
                               label: v.name,
                               value: v.id
                             }
                           })
                         }
                       }
        >

        </ProFormSelect>
        <ProFormTreeSelect width="md" name="deptId"
                       label={<FormattedMessage id="system.user.table.list.deptId" defaultMessage="$$$"/>}
                       placeholder={`${intl.formatMessage({
                         id: 'common.please_select',
                         defaultMessage: '$$$'
                       })}${intl.formatMessage({id: 'system.user.table.list.deptId', defaultMessage: '$$$'})}`}
                       required={false}
                       request={async () => {
                         let resp = await postDepartmentGetDepartmentFkSelect()
                         return resp.data.list
                       }}
        >

        </ProFormTreeSelect>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormUploadButton width="md" max={1}
                             action="/api/v1/file/uploadImage"
                             name="avatarId"
                             label={<FormattedMessage id="system.user.table.list.avatarId" defaultMessage="$$$"/>}
                             fieldProps={{
                               name: 'file',
                               listType: 'picture-card',
                               beforeUpload: beforeUploadImage,
                               data: {path: 'user/avatar'},
                               headers: { 'X-CSRFToken': cookie.load('csrftoken') , 'X-Token': `${localStorage.getItem('access') || ''}`},}}/>

      </ProForm.Group>
      <ProForm.Group>
        <ProFormText width="md" name="remark"
                     label={<FormattedMessage id="system.user.table.list.remark" defaultMessage="$$$"/>}
                     placeholder={`${intl.formatMessage({
                       id: 'common.please_input',
                       defaultMessage: '$$$'
                     })}${intl.formatMessage({id: 'system.user.table.list.remark', defaultMessage: '$$$'})}`}
                     required={false}/>
        <ProFormSwitch width="md" name="enable" initialValue={true}
                       label={<FormattedMessage id="system.user.table.list.enable" defaultMessage="$$$"/>}
                       required={false}>

        </ProFormSwitch>
      </ProForm.Group>
    </ModalForm>)
}
export default CreateForm;
