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



export type UpdateFormProps = {
  updateModalOpen: boolean;
  handleModal: () => void;
  values: Partial<API.UserView>;
  reload: any;
};
const UpdateForm: React.FC<UpdateFormProps> = (props) => {

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

  return (
    <ModalForm<API.User>
      title={intl.formatMessage({
        id: 'common.modal.table.update.title',
        defaultMessage: '$$$',
      })}
      open={props.updateModalOpen}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => props.handleModal(),
      }}
      submitTimeout={2000}
      onFinish={async (values: any) => {
        if ('roleIds' in values) {
          if ((values?.roleIds || []).length) {
            values.roleId = values.roleIds[0]
            values.roleIds = values.roleIds.join(',')
          } else {
            values.roleId = undefined
            values.roleIds = ''
          }
        }
        if ('postIds' in values) {
          if ((values?.postIds || []).length) {
            values.postId = values.postIds[0]
            values.postIds = values.postIds.join(',')
          } else {
            values.postIds = ''
            values.postId = undefined
          }
        }

        handleOneFile(values, 'avatarId')
        console.log(values)
        console.log(props.values)
        putUserSetUserInfo(values).then(() => {
          message.success(intl.formatMessage({id: 'common.success', defaultMessage: '$$$'}))
          props.reload()
        }).catch(() => {
          message.error(intl.formatMessage({id: 'common.failure', defaultMessage: '$$$'}))
        })

        props.handleModal();
        return true;
      }}
    >

      <ProForm.Group>
        <ProFormText width="md" name="id" label="id" disabled={true} initialValue={props.values.id}/>
        <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: '$$$'})}`}
                     initialValue={props.values.userName}
                     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: '$$$'})}`}
                     initialValue={props.values.nickName}
                     required={true}
                     rules={[
                       {
                         required: true,
                         message: (
                           <FormattedMessage
                             id="system.department.table.rule.required.nickName"
                             defaultMessage="nickName is required"
                           />
                         ),
                       },
                     ]}
        />


      </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}
                       initialValue={parseIds(props.values.roleIds)}
                       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}
                       initialValue={parseIds(props.values.postIds)}
                       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}
                           initialValue={props.values.deptId}
                           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="$$$"/>}
                              initialValue={imageInit(SERVER_HOST,props.values.avatarUrl)}
                             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: '$$$'})}`}
                     initialValue={props.values.remark}
                     required={false}/>
        <ProFormSwitch width="md" name="enable" initialValue={props.values.enable}
                       label={<FormattedMessage id="system.user.table.list.enable" defaultMessage="$$$"/>}
                       required={false}>

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