import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Upload, Space, Modal, Row, Col, Drawer, message } from 'antd';
import users from '@/assets/images/icon/userinfo.png';
import { changePass, changeInfo, getUserInfo } from '@/layout/request';
import { uploadFiles } from '@/utils/upload';
import AliOSS from 'ali-oss';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { getAliOSSSTSToken } from '@/pages/setting/help/addedit/requet';

const UserInfo = () => {
  const navigator = useNavigate();
  const [file, setFile] = useState('');

  const [imageUrl, setImageUrl] = useState('');
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [showModal, setShowModal] = useState(false);

  const [ossClient, setOssClient] = useState(null); // oss 操作
  const [STSToken, setSTSToken] = useState(null); // oss 过期设置

  let ossClientTemp;

  const getStsAuthToken = () => {
    return new Promise(async (resolve) => {
      const data = await getAliOSSSTSToken();
      if (data) {
        window.sessionStorage.setItem('sts', JSON.stringify(data));
        setSTSToken(data);
        ossClientTemp = await new AliOSS({
          accessKeyId: data.AccessKeyId,
          accessKeySecret: data.AccessKeySecret,
          stsToken: data.SecurityToken,
          endpoint: data.endpoint,
          bucket: 'zxts-user-file',

          timeout: 180000,
          refreshSTSToken: async () => {
            const info = await getAliOSSSTSToken();
            return {
              AccessKeyId: info.AccessKeyId,
              AccessKeySecret: info.AccessKeySecret,
              SecurityToken: info.SecurityToken,
            };
          },
          refreshSTSTokenInterval: 14 * 60 * 1000,
        });
        setOssClient(ossClientTemp);
      }
      resolve();
    });
  };

  // const props = {
  //   name: 'file',
  //   accept: '.jpg,.png',
  //   showUploadList: false,
  //   beforeUpload: async (file) => {
  //     const suffixArr = ['png', 'jpg'];
  //     const suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
  //     if (!suffixArr.includes(suffix)) {
  //       message.error(`请上传以${suffixArr.join('、')}的图片`);
  //       return false;
  //     }
  //     setFile(file);
  //   },
  //   customRequest: async () => {
  //     if (!ossClient) {
  //       message.error('ossClient还未初始化', ossClient);
  //       return false;
  //     }

  //     try {
  //       const result = await ossClient.put(file.name, file);
  //       console.log('result', result);
  //       // 假设 result 中包含了文件的 URL
  //       const imageUrl = result.url;

  //       // 更新图片 URL 状态
  //       setImageUrl(imageUrl);
  //       form.setFieldsValue({ pic: imageUrl });

  //       // 上传成功，返回 true 表示可以继续上传
  //       return true;
  //     } catch (error) {
  //       // 上传失败，处理错误
  //       console.error('上传文件失败：', error);
  //       message.error('上传文件失败，请重试');
  //       return false;
  //     }
  //   },
  //   // ... 其他属性
  // };

  const props = {
    name: 'file',
    accept: '.jpg,.png',
    showUploadList: false,
    beforeUpload: async (file) => {
      const suffixArr = ['png', 'jpg'];
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (!suffixArr.includes(suffix)) {
        message.error(`请上传以${suffixArr.join('、')}的图片`);
        return false;
      }
      // 检查文件大小是否超过1MB
      if (file.size > 1024 * 1024) {
        message.error('图片大小不能超过1MB');
        return false;
      }
      setFile(file);
    },
    customRequest: async () => {
      if (!ossClient) {
        message.error('ossClient还未初始化', ossClient);
        return false;
      }

      try {
        const fileExt = file.name.substring(file.name.lastIndexOf('.'));
        const fileName = `user-${dayjs().valueOf()}-${Math.random().toString(36).substring(2)}${fileExt}`;
        const filePath = `${dayjs().format('YYYY/MM/DD')}/${fileName}`;

        const result = await ossClient.put(filePath, file);
        console.log('result', result);
        // 假设 result 中包含了文件的 URL
        const imageUrl = result.url;

        // 更新图片 URL 状态
        setImageUrl(imageUrl);
        form.setFieldsValue({ pic: imageUrl });

        // 上传成功，返回 true 表示可以继续上传
        return true;
      } catch (error) {
        // 上传失败，处理错误
        console.error('上传文件失败：', error);
        message.error('上传文件失败，请重试');
        return false;
      }
    },
    // ... 其他属性
  };

  const fetchData = async (obj) => {
    try {
      const userData = await getUserInfo(obj);

      form.setFieldsValue({
        real_name: userData.real_name,
        tel: userData.tel,
        pic: userData.pic,
      });
      const imageUrl = userData.pic;
      setImageUrl(imageUrl);
    } catch (error) {
      console.error('Error fetching user data:', error);
    }
  };

  useEffect(() => {
    getStsAuthToken();
    fetchData();
  }, []);

  const changePasswrd = async (obj) => {
    const bool = await changePass(obj);
    setShowModal(false);
  };

  const submitForm = async (obj) => {
    const updatedData = await changeInfo({ ...obj });
    if (updatedData) {
      await fetchData();
    }
  };

  return (
    <div style={{ padding: '20px 0' }}>
      <Form form={form} labelCol={{ span: 2 }} onFinish={submitForm}>
        <Form.Item label='头像' className='uploadPar' name='pic'>
          <img
            src={imageUrl ? imageUrl : users}
            style={{ borderRadius: '50%' }}
            width={80}
            height={80}
            id='avatar'
          />
          <div>
            <Upload {...props} valuePropName='file'>
              <Button className='upload'>点击上传</Button>
            </Upload>
            <span className='desc' style={{ marginLeft: 19, color: '#999', fontSize: '14px' }}>
              尺寸：只能上传jpg/png文件，且不超过1M
            </span>
          </div>
        </Form.Item>
        <Form.Item
          label='管理员名称'
          name='real_name'
          rules={[{ required: true, message: '请输入管理员名称' }]}
        >
          <Input autoComplete='off' placeholder='请输入管理员名称' style={{ width: 200 }}></Input>
        </Form.Item>
        <Form.Item label='手机号' name='tel' rules={[{ required: true, message: '请输入手机号' }]}>
          <Input autoComplete='off' placeholder='请输入手机号' style={{ width: 200 }}></Input>
        </Form.Item>
        <Form.Item label='密码'>
          <Button type='primary' ghost onClick={() => setShowModal(true)}>
            修改密码
          </Button>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 2 }}>
          <Space size={20}>
            <Button className='cancel' onClick={() => navigator(-1)}>
              取消
            </Button>
            <Button className='submit' htmlType='submit'>
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Drawer
        open={showModal}
        onClose={() => {
          setShowModal(false);
        }}
        mask={false}
        maskClosable={false}
        footer={null}
        centered
        destroyOnClose
        keyboard={false}
      >
        <Form labelCol={{ span: 5 }} form={form2} onFinish={changePasswrd}>
          <Form.Item
            label='旧密码'
            name='old_password'
            rules={[{ required: true, message: '请输入旧密码' }]}
          >
            <Input.Password autoComplete='off' placeholder='请输入旧密码'></Input.Password>
          </Form.Item>
          <Form.Item
            label='新密码'
            name='password'
            rules={[
              { required: true, message: '请输入新密码' },
              {
                pattern: /^((?=.*\d)(?=.*[A-Z])(?=.*[a-z]))|((?=.*\d)(?=.*[A-Z])(?=.*[\W_]))|((?=.*\d)(?=.*[a-z])(?=.*[\W_]))|((?=.*[A-Z])(?=.*[a-z])(?=.*[\W_]))[a-zA-Z\d\W_]{8,12}$/,
                message:
                  '密码至少满足三种格式(大写字母、小写字母、数字、特殊符号), 长度为8~12位字符！',
                trigger: ['change', 'blur']
              },
              {
                validator (_, value) {
                  if (!value || form2.getFieldValue('re_password') === value) {
                    form2.setFields([{ name: 're_password', errors: [''] }]);
                    return Promise.resolve();
                  }
                  form2.setFields([{ name: 're_password', errors: ['两次输入的密码不一致'] }]);
                  return Promise.reject();
                },
              },
            ]}
          >
            <Input.Password autoComplete='off' placeholder='请输入新密码'></Input.Password>
          </Form.Item>
          <Form.Item
            label='确认新密码'
            name='re_password'
            rules={[
              { required: true, message: '请确认新密码' },
              {
                pattern: /^((?=.*\d)(?=.*[A-Z])(?=.*[a-z]))|((?=.*\d)(?=.*[A-Z])(?=.*[\W_]))|((?=.*\d)(?=.*[a-z])(?=.*[\W_]))|((?=.*[A-Z])(?=.*[a-z])(?=.*[\W_]))[a-zA-Z\d\W_]{8,12}$/,
                message:
                  '密码至少满足三种格式(大写字母、小写字母、数字、特殊符号), 长度为8~12位字符！',
                trigger: ['change', 'blur']
              },
              {
                validator (_, value) {
                  if (!value || form2.getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              },
            ]}
          >
            <Input.Password autoComplete='off' placeholder='请确认新密码'></Input.Password>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 5 }}>
            <Row justify={'center'}>
              <Space size={20}>
                <Col>
                  <Button className='cancel' onClick={() => setShowModal(false)}>
                    取消
                  </Button>
                </Col>
                <Col>
                  <Button className='submit' htmlType='submit'>
                    确认
                  </Button>
                </Col>
              </Space>
            </Row>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default UserInfo;
