import React, { useRef, useState, useEffect } from 'react';
import { Input, Checkbox, Radio, Button, notification, Spin } from 'antd';
import { Form } from '@ant-design/compatible';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RolePermissionsModal from '../components/RolePermissionsModal';
import { getRoleList, addUser, getUserDetail, updateUser } from '../../service';
import { shopGetBySupplierId } from '@/pages/ServiceGoods/service';
import UUID from '@/utils/uuid';

import style from './index.less';

const AccountInfo = props => {
  const { getFieldDecorator, validateFields, getFieldValue, setFieldsValue } = props.form;
  const { id } = props.location.query;
  const [title, setTitle] = useState('新增用户');
  const [inputType, setInputType] = useState('text');
  const [confirmInputType, setConfirmInputType] = useState('text');
  const [roleList, setRoleList] = useState([]);
  const [supplierList, setSupplierList] = useState([]);
  const [detailInfo, setDetailInfo] = useState({});
  const [loading, setLoading] = useState(false);

  const userInfo = JSON.parse(localStorage.getItem('user') || '{}');

  const rolePermissionsModalRef = useRef();

  const popReg = /^pop_/g;
  const isPop = popReg.test(userInfo.supplierCode);

  // 表单布局
  const formLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 12 },
  };
  const btnLayout = {
    wrapperCol: { offset: 4, span: 12 },
  };

  const handleConfirmPassword = (rule, value, callback) => {
    if (value && value !== getFieldValue('password')) {
      callback('两次输入不一致！');
    }
    callback();
  };

  // 表单验证
  const formRules = {
    account: [
      { required: true, message: '请设置登录用户名' },
      { pattern: /^[a-zA-Z0-9@.]{1,32}$/g, message: '用户名格式错误' },
    ],
    name: [{ required: true, message: '请输入姓名' }],
    password: [
      { required: true, message: '请设置密码' },
      {
        pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{13,18}$/g,
        message: '密码格式错误',
      },
    ],
    confirmPassword: [
      { required: true, message: '请确认登录密码' },
      { validator: handleConfirmPassword, message: '两次密码不一致' },
    ],
    roleId: [{ required: true, type: 'array', message: '请选择用户角色' }],
  };

  // 角色权限 modal
  const openRolePermissionsModal = record => {
    rolePermissionsModalRef.current.open(record);
  };

  // 获取所有门店列表
  const getAllSupplier = res => {
    if (res.code !== '0000') {
      notification.warning({
        message: res.detail,
      });
      return;
    }
    setSupplierList(res.data);
  };

  // 获取所有角色列表
  const getAllRoleList = res => {
    if (res.code !== 2000) {
      notification.warning({ message: res.detail });
      return;
    }
    console.log(res);
    const { content } = res.data;
    setRoleList(content);
  };

  // 获取当前选中的角色id
  const getSelectedRoleIds = () => {
    const cacheIds = window.sessionStorage.getItem('_selectedRoleIds');
    return cacheIds ? JSON.parse(cacheIds) : [];
  };
  // 获取账户详情
  const getAccountDetail = res => {
    setLoading(false);
    if (res.code !== 2000) {
      notification.warning({ message: res.detail });
      return;
    }
    console.log(res);
    setDetailInfo(res.data);
    const { account, name, organization } = res.data;
    const roleId = getSelectedRoleIds();
    console.log(roleId);
    setFieldsValue({
      account,
      name,
      organizationId: organization.id,
      roleId,
    });
  };

  // 用户角色多选框
  const userRoleCheckbox = () =>
    roleList.map(item => (
      <Checkbox value={item.id}>
        <a
          onClick={e => {
            e.preventDefault();
            openRolePermissionsModal(item);
          }}
        >
          {item.name}
        </a>
      </Checkbox>
    ));

  // 选择门店多选框
  const selectSupplierCheckbox = () => {
    let list = supplierList;
    const filterData = supplierList.filter(item => item.orgId === userInfo.orgId);
    if (filterData.length) {
      list = filterData;
    }
    return list.map(item => <Radio value={item.orgId}> {item.name}</Radio>);
  };

  // 表单验证辅助函数
  const rulesHandler = (field, initialValue = '') => ({
    rules: formRules[field] || [],
    initialValue,
  });

  // 提交
  const onSubmit = () => {
    validateFields(async (err, fieldsValue) => {
      console.log(err, fieldsValue);
      if (err) {
        return;
      }
      // 提交
      console.log(fieldsValue);
      const { organizationId, email } = fieldsValue;
      const { orgId } = userInfo;
      const code = UUID.createUUID();
      const params = {
        ...fieldsValue,
        code,
        email: email || `${code}@stms.quantgroup.cn`,
        organization: {
          id: organizationId || orgId,
        },
      };
      delete params.organizationId;
      let api = addUser;
      if (id) {
        console.log(id, 222444);
        params.id = id;
        api = updateUser;
      }
      const res = await api(params);
      if (res.code !== 2000) {
        notification.warning({
          message: res.detail || res.msg,
        });
        return;
      }
      notification.success({
        message: '保存成功',
      });
      setTimeout(() => {
        window.history.back();
      }, 1000);
    });
  };

  // 处理初始化密码自动填充函数
  const handlePasswordChange = (e, fn) => {
    if (e.target.value) {
      fn('password');
    } else {
      fn('text');
    }
  };

  const initData = async () => {
    const roleListParams = {
      page: 1,
      size: 1000,
    };
    setLoading(true);
    const roleListRes = await getRoleList(roleListParams);
    const supplierListRes = await shopGetBySupplierId();
    let accountDetailRes = null;
    if (id) {
      accountDetailRes = await getUserDetail({ id });
      getAccountDetail(accountDetailRes);
    }
    setLoading(false);

    getAllRoleList(roleListRes);
    getAllSupplier(supplierListRes);
  };
  useEffect(() => {
    initData();
    if (id) {
      setTitle('编辑用户');
    }
  }, []);

  return (
    <PageHeaderWrapper title={title}>
      <div className={style['user-info']}>
        <Spin spinning={loading}>
          <Form className={style['user-info--form']} {...formLayout}>
            <Form.Item label="用户名" extra="限32字符以内，限英文/数字/“@”“ .”">
              {getFieldDecorator('account', rulesHandler('account'))(
                <Input disabled={!!id} placeholder="请输入用户名" maxLength={32} />,
              )}
            </Form.Item>
            <Form.Item label="姓名" extra="限10字符以内">
              {getFieldDecorator('name', rulesHandler('name'))(
                <Input maxLength={10} placeholder="请输入用户姓名" />,
              )}
            </Form.Item>
            {id ? (
              ''
            ) : (
              <>
                <Form.Item label="初始密码" extra="限13-18字符，包含大小写字母、数字和特殊字符">
                  {getFieldDecorator('password', rulesHandler('password'))(
                    <Input
                      type={inputType}
                      onChange={e => handlePasswordChange(e, setInputType)}
                      placeholder="请设置登录密码"
                    />,
                  )}
                </Form.Item>
                <Form.Item label="确认密码">
                  {getFieldDecorator('confirmPassword', rulesHandler('confirmPassword'))(
                    <Input
                      type={confirmInputType}
                      onChange={e => handlePasswordChange(e, setConfirmInputType)}
                      placeholder="请确认登录密码"
                    />,
                  )}
                </Form.Item>
              </>
            )}
            <Form.Item label="选择门店" extra="仅限POP商家设置">
              {getFieldDecorator('organizationId', rulesHandler('organizationId'))(
                isPop && supplierList.length ? (
                  <Radio.Group disabled={!!id} style={{ width: '100%' }}>
                    {selectSupplierCheckbox()}
                  </Radio.Group>
                ) : (
                  <div>暂无门店信息</div>
                ),
              )}
            </Form.Item>
            <Form.Item label="用户角色">
              {getFieldDecorator('roleId', rulesHandler('roleId'))(
                roleList.length ? (
                  <Checkbox.Group style={{ width: '100%' }}>{userRoleCheckbox()}</Checkbox.Group>
                ) : (
                  <div>暂无角色信息</div>
                ),
              )}
            </Form.Item>

            <Form.Item {...btnLayout}>
              <Button type="default" onClick={() => window.history.back()}>
                返回
              </Button>
              <Button className={style['submit-button']} type="primary" onClick={onSubmit}>
                提交
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </div>
      <RolePermissionsModal ref={rolePermissionsModalRef} />
    </PageHeaderWrapper>
  );
};

export default Form.create({})(AccountInfo);
