import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Button, message, Descriptions, Spin, Tree, Radio } from 'antd';
import { connect, history } from 'umi';
import { EditOutlined, LeftOutlined } from '@ant-design/icons';
import { getCookie } from '@/utils/method';

import './Account.less';
import { zhCnFaci, enUsFaci } from '@/utils/power';
import { AccountTip } from '@/utils/tip';

import SelectCommunity from '@/components/SelectCommunity';
import { getNumber } from '@/utils/string'; // 正则
import { RA } from '@/utils/method';

const Account = (props: any) => {
  const module = 'Account';

  const { dispatch, SubResult, CommunityList, loading, user } = props;

  // 权限列表
  const treeData = enUsFaci || zhCnFaci;

  const [expandedKeys, setExpandedKeys] = useState<string[]>([]); // 展开栏目
  const [checkedKeys, setCheckedKeys] = useState([] as any); // 默认已选栏目
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]); // 设置选中的树节点
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true); // 树形菜单展开关闭

  // 单选 二级还是三级管理员
  const [values, setvalues] = useState(2); // 树形菜单展开关闭

  // 表单标识
  const [form] = Form.useForm();
  const formRef = useRef(null);

  // 当前账户信息
  useEffect(() => {
    if (user != null) {
      let treeDatas = treeData;
      let _a = user.currentUser.permission; // 当前账户权限
      let _p = treeDatas[0].children; // 所有权限列表

      let arr: any = []; // 一级栏目权限
      let erArr: any = []; // 一级栏目权限
      // 循环一级 判断当前账户有没有权限修改增加
      for (let i of _a) {
        for (let j in _p) {
          if (_p[j].key == i) {
            arr.push(_p[j].key);
            _p[j].disabled = false;
          }
          // 二级权限
          for (let k in _p[j].children) {
            if (_p[j].children[k].key == i) {
              erArr.push(_p[j].children[k].key);
              _p[j].children[k].disableCheckbox = false;
            }
          }
        }
      }
      // 赋值改变
      treeDatas[0].children = _p;
      setCheckedKeys(treeDatas as any); // 可勾选列表
    }
  }, [user]);

  useEffect(() => {
    // 提交信息结果
    if (SubResult != null) {
      if (SubResult.statr == 0 && SubResult.desc == 0) {
        // 保存成功， 清掉原来数据 并且跳转
        message.success('Submitted Successfully !');
        dispatch({ type: module + '/ReData' });
        dispatch({ type: module + '/AccountClear' });
        history.go(-1);
      }
    }
  }, [SubResult]);

  // 保存提交
  const onFinishContract = async (value: any) => {
    const userInfo = localStorage.getItem('userInfo') || '';
    const id = JSON.parse(userInfo).userModel.id;
    if (
      value.tosAccountName.length <= 2 &&
      value.tosUserPhone.length != 8 &&
      value.tosUserPhone.length != 11
    ) {
      // 姓名联系方式
      message.error('Please enter the correct name and contact information!');
      return false;
    } else if (checkedKeys[0].key) {
      // 如果存在key  就是没有选择
      // 权限
      message.error('Please Select Permission!');
      return false;
    } else if (value.community.value == null || value.community.value.length == 0) {
      // 小区
      message.error('Please Select The Jurisdiction Area!');
      return false;
    } else if (value.tosUserName.length < 6) {
      // 账号长度
      message.error('The Account Password is Greater Than 6 Digits!');
      return false;
    } else {
      value.tosUserServiceCellList = value.community.value; // 管辖小区
      value.tosUserEmail = value.tosUserName; //  邮箱就是账号
      value.tosUserLevel = values; //级别
      value.creatorName = getCookie('name'); //新建者账号
      value.creatorId = id; //新建者ID
      delete value.community;
      // console.log(checkedKeys);

      // 判断有没有 0  有就删除
      for (var i in checkedKeys) {
        checkedKeys[i] == '0' ? checkedKeys.splice(i, 1) : '';
      }

      // 另传权限
      let obj = {
        userName: value.tosUserName,
        userPassword: value.tosUserPwd,
        permissionArray: checkedKeys.sort((n1: any, n2: any) => {
          return parseInt(n1) - parseInt(n2);
        }),
      };

      RA(38, value, module, dispatch); // 信息上传
      RA(42, obj, module, dispatch); // 权限上传
      return true;
    }
  };

  //goToReturn
  const goToReturn = () => {
    history.go(-1);
  };

  // 展开/收起树形菜单触发
  const onExpand = (expandedKeys: any) => {
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  };

  // 点击单个触发
  const onCheck = (checkedKeys: any) => {
    // console.log('onCheck', checkedKeys);
    setCheckedKeys(checkedKeys);
  };

  // 点击树节点触发  - 大栏目
  const onSelect = (selectedKeys: any, info: any) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeys);
  };

  // 管理员级别样式
  const radioStyle = {
    display: 'block',
    height: '30px',
    lineHeight: '30px',
    marginBottom: '15px',
  };

  //级别切换
  const onRadio = (e: any) => {
    setvalues(e.target.value);
  };

  //手机号
  const keyup_communityManagerFee = (e: any) => {
    e.target.value = keyup_tool(e.target.value);
  };
  const keyup_tool = (value: any) => {
    return getNumber(value.replace(/[^\d^\.]+/g, ''));
  };
  // 选择小区名字并赋值

  return (
    <Spin spinning={loading}>
      <div className="contop" style={{ padding: '12px 20px' }}>
        <h3 className="capi">
          <EditOutlined />
          &nbsp; Add Account
          <div className="back">
            <Button onClick={goToReturn}>
              <LeftOutlined />
              Back
            </Button>
          </div>
        </h3>
        <hr></hr>
        <Form
          ref={formRef}
          form={form}
          autoComplete="off"
          // layout="inline"
          layout="horizontal"
          name="contract"
          onFinish={onFinishContract}
        >
          <Descriptions column={{ xs: 1, sm: 2, md: 3 }}>
            <Descriptions.Item>
              <Form.Item name="tosUserName" label="Account ID" rules={AccountTip[0] as any}>
                <Input placeholder="Login Account" className="input" />
              </Form.Item>
            </Descriptions.Item>
          </Descriptions>

          <Descriptions column={{ xs: 1, sm: 2, md: 3 }}>
            <Descriptions.Item>
              <Form.Item name="tosAccountName" label="Name" rules={AccountTip[1] as any}>
                <Input placeholder="Name Of Administrator" className="input" />
              </Form.Item>
            </Descriptions.Item>
            <Descriptions.Item>
              <Form.Item name="tosUserPhone" label="Phone" rules={AccountTip[2] as any}>
                <Input
                  placeholder="Contact Information"
                  className="input"
                  maxLength={11}
                  onKeyUp={keyup_communityManagerFee}
                />
              </Form.Item>
            </Descriptions.Item>
          </Descriptions>

          <Form.Item name="community" label="Community">
            <SelectCommunity checklist={CommunityList == null ? null : CommunityList} />
          </Form.Item>

          <div className="diy" style={{ marginBottom: '14px' }}>
            <div className="label">
              <span className="title">Privilege Level：</span>
            </div>
            <div className="label">
              <Radio.Group defaultValue={values} onChange={onRadio}>
                <Radio style={radioStyle} value={2}>
                  Two Level Administrator
                </Radio>
                <Radio style={radioStyle} value={3}>
                  Three Level Administrator
                  {/* <Input placeholder="三级管理员" style={{ width: 160, marginLeft: 10 }} /> */}
                </Radio>
              </Radio.Group>
            </div>
          </div>

          <div className="diy" style={{ marginBottom: '24px' }}>
            <div className="label">
              <span className="title">Permission List：</span>
            </div>
            <div className="label">
              <Tree
                checkable
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                onCheck={onCheck}
                checkedKeys={checkedKeys}
                onSelect={onSelect}
                selectedKeys={selectedKeys}
                treeData={treeData}
              />
            </div>
          </div>

          <div className="diy">
            <div className="label"></div>
            <div className="label">
              <Button type="primary" htmlType="submit" loading={loading}>
                Submit
              </Button>
            </div>
          </div>
        </Form>
      </div>
    </Spin>
  );
};

const AccountProps = (state: any) => {
  const { Data, DataSave, DataSaveDetail, Result, SubResult } = state.Account;
  const { CommunityList } = state.Init; // 小区列表
  const loading = state.loading.models.Account || false;
  const { user } = state;
  return {
    Data,
    DataSave,
    DataSaveDetail,
    Result,
    loading,
    CommunityList,
    user, // 获取当前账户信息
    SubResult,
  };
};

export default connect(AccountProps)(Account);
