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($t('add.user'));
  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($t('inputs.do.not.match'));
    }
    callback();
  };

  // 表单验证
  const formRules = {
    account: [
      { required: true, message: $t('set.login.username') },
      { pattern: /^[a-zA-Z0-9@.]{1,32}$/g, message: $t('username.format.error') },
    ],
    name: [{ required: true, message: $t('enter.name') }],
    password: [
      { required: true, message: $t('set.password') },
      {
        pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{13,18}$/g,
        message: $t('invalid.password.format'),
      },
    ],
    confirmPassword: [
      { required: true, message: $t('confirm.login.password') },
      { validator: handleConfirmPassword, message: $t('passwords.do.not.match') },
    ],
    roleId: [{ required: true, type: 'array', message: $t('select.user.role') }],
  };

  // 角色权限 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`,
        source: 1,
        tenantId: 560761,
        organization: {
          id: organizationId || orgId,
        },
      };
      delete params.organizationId;
      let api = addUser;
      if (id) {
        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: $t('saved.successfully'),
      });
      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($t('edit.user'));
    }
  }, []);

  return (
    <PageHeaderWrapper title={title}>
      <div className={style['user-info']}>
        <Spin spinning={loading}>
          <Form className={style['user-info--form']} {...formLayout}>
            <Form.Item label={$t('username')} extra={$t('max.32.chars.lettersdigits')}>
              {getFieldDecorator('account', rulesHandler('account'))(
                <Input disabled={!!id} placeholder={$t('enter.username')} maxLength={32} />,
              )}
            </Form.Item>
            <Form.Item label={$t('name')} extra={$t('max.10.characters')}>
              {getFieldDecorator('name', rulesHandler('name'))(
                <Input maxLength={10} placeholder={$t('enter.user.name')} />,
              )}
            </Form.Item>
            {id ? (
              ''
            ) : (
              <>
                <Form.Item label={$t('initial.password')} extra={$t('1318.chars.uppercase.lowercase.digits.special.chars')}>
                  {getFieldDecorator('password', rulesHandler('password'))(
                    <Input
                      type={inputType}
                      onChange={e => handlePasswordChange(e, setInputType)}
                      placeholder={$t('set.login.password')}
                    />,
                  )}
                </Form.Item>
                <Form.Item label={$t('confirm.password')}>
                  {getFieldDecorator('confirmPassword', rulesHandler('confirmPassword'))(
                    <Input
                      type={confirmInputType}
                      onChange={e => handlePasswordChange(e, setConfirmInputType)}
                      placeholder={$t('confirm.login.password')}
                    />,
                  )}
                </Form.Item>
              </>
            )}
            <Form.Item label={$t('select.store')} extra={$t('pop.merchants.only')}>
              {getFieldDecorator('organizationId', rulesHandler('organizationId'))(
                isPop && supplierList.length ? (
                  <Radio.Group disabled={!!id} style={{ width: '100%' }}>
                    {selectSupplierCheckbox()}
                  </Radio.Group>
                ) : (
                  <div>{$t('no.store.info')}</div>
                ),
              )}
            </Form.Item>
            <Form.Item label={$t('user.role')}>
              {getFieldDecorator('roleId', rulesHandler('roleId'))(
                roleList.length ? (
                  <Checkbox.Group style={{ width: '100%' }}>{userRoleCheckbox()}</Checkbox.Group>
                ) : (
                  <div>{$t('no.role.info')}</div>
                ),
              )}
            </Form.Item>

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

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