/*
 * @Author: your name
 * @Date: 2022-03-03 17:42:10
 * @LastEditTime: 2023-06-12 16:14:59
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/pages/personalCenter/components/security.tsx
 */
import React, { useState } from 'react';
import { List } from 'antd';
import KCModal from '@/components/KCModal';
import { ProFormText } from '@ant-design/pro-form';
import { Form, Alert, Progress, notification, Modal } from 'antd';
import PasswordQualityCalculator from 'password-quality-calculator';
import { editUsers, editUsersPsd } from '@/service/user';
import { useModel } from 'umi';

type Unpacked<T> = T extends (infer U)[] ? U : T;

const passwordStrength = {
  strong: <span className="strong">强</span>,
  medium: <span className="medium">中</span>,
  weak: <span className="weak">弱 Weak</span>,
};

const SecurityView: React.FC = () => {
  const getData = () => [
    {
      title: '账户密码',
      description: (
        <>
          当前密码强度：
          {passwordStrength}
        </>
      ),
      actions: [
        <a key="Modify" onClick={() => resetPasswordHandle()}>
          修改
        </a>,
      ],
    },
    // {
    //   title: '密保手机',
    //   description: `已绑定手机：138****8293`,
    //   actions: [<a key="Modify">修改</a>],
    // },
    // {
    //   title: '密保问题',
    //   description: '未设置密保问题，密保问题可有效保护账户安全',
    //   actions: [<a key="Set">设置</a>],
    // },
    // {
    //   title: '备用邮箱',
    //   description: `已绑定邮箱：ant***sign.com`,
    //   actions: [<a key="Modify">修改</a>],
    // },
    // {
    //   title: 'MFA 设备',
    //   description: '未绑定 MFA 设备，绑定后，可以进行二次确认',
    //   actions: [<a key="bind">绑定</a>],
    // },
  ];

  const { initialState, setInitialState } = useModel('@@initialState');

  const [modalVisible, setmodalVisible] = useState(false);
  const [passwordStrength, setpasswordStrength] = useState(0);
  const [showPasswordCompareTip, setshowPasswordCompareTip] = useState(false);

  const data = getData();

  const resetPasswordHandle = () => {
    setmodalVisible(true);
  };

  const onVisibleChangeHandle = (bool: boolean) => {
    setmodalVisible(bool);
  };

  const passwordChangeHandle = (e: React.ChangeEvent<HTMLInputElement>) => {
    // console.log(PasswordQualityCalculator(e.target.value));
    setpasswordStrength(PasswordQualityCalculator(e.target.value));
  };

  const onFinishhandle = async (values: any) => {
    const { newPassword, reNewPassword } = values;

    if (reNewPassword != newPassword) {
      setshowPasswordCompareTip(true);
      setTimeout(() => {
        setshowPasswordCompareTip(false);
      }, 2000);
      return false;
    }
    const userData = localStorage.getItem('userData');

    if (userData) {
      const resp = await editUsersPsd({
        id: JSON.parse(userData).userId,
        password: newPassword,
      });

      if (resp) {
        Modal.confirm({
          title: '密码修改成功，前往重新登录？',
          closable: false,
          okText:'确定',
          onOk: () => {
            if (initialState?.logout) {
              initialState.logout();
            }
          },
          cancelText: '',
        });
        return true;
      }
    } else {
      notification['error']({
        message: '用户信息获取错误！',
      });
    }
  };

  return (
    <div>
      <KCModal
        title="设置密码"
        width={600}
        visible={modalVisible}
        onVisibleChange={onVisibleChangeHandle}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        onFinish={(val) => onFinishhandle(val)}
      >
        <div style={{ position: 'relative', paddingTop: '24px' }}>
          <Alert
            message="两次输入密码不一致！"
            type="error"
            showIcon
            style={{
              position: 'absolute',
              marginBottom: '16px',
              top: showPasswordCompareTip ? -27 : -70,
              transition: 'all 0.3s ease-in',
              width: '100%',
            }}
          />

          <ProFormText.Password
            label="原密码"
            name="oldPassword"
            rules={[{ required: true, message: '这是必填项' }]}
          />
          <ProFormText.Password
            label="新密码"
            name="newPassword"
            rules={[{ required: true, message: '这是必填项' }]}
            fieldProps={{
              onChange: (e) => passwordChangeHandle(e),
            }}
          />
          <ProFormText.Password
            label="再次输入新密码"
            name="reNewPassword"
            rules={[{ required: true, message: '这是必填项' }]}
          />
          <Form.Item label="密码强度">
            <Progress
              percent={passwordStrength}
              steps={10}
              strokeColor={{ '0%': '#108ee9', '100%': '#87d068' }}
            />
          </Form.Item>
        </div>
      </KCModal>

      <List<Unpacked<typeof data>>
        itemLayout="horizontal"
        dataSource={data}
        renderItem={(item) => (
          <List.Item actions={item.actions} className="rightListItem">
            <List.Item.Meta title={item.title} description={item.description} />
          </List.Item>
        )}
      />
    </div>
  );
};

export default SecurityView;
