import React, { useState, useEffect } from 'react';
import {
  Modal,
  Form,
  Select,
  Radio,
  Checkbox,
  Input,
  Row,
  Col,
  Button,
  InputNumber,
  Tree,
  Tooltip,
  Dropdown,
  message,
} from 'antd';
import Icon from '@/tenants-ui/SgIcon';
import styles from './index.less';
import cx from 'classnames';
import { useModel, history } from 'umi';
import { EllipsisOutlined } from '@ant-design/icons';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import AreaTree from '../areaTree';

import moment from 'moment';
import { queryUserInfo, saveUserInfo, deleteUser } from '@/services/sagacare_service/member';

const PersonModal = ({
  spaceMap,
  checkUser,
  checkSign,
  setCheckSign,
  onClose,
  temporary,
  invalidSign,
  setInvalidSign,
  refreshList,
}) => {
  const { initialState } = useModel('@@initialState');
  const [form] = Form.useForm();
  const [radioValue, setRadioValue] = useState(); //'0-0-0-0'
  const [checkedValues, setCheckedValues] = useState([]); //'0-0-0-0'
  //const [userControlSpaces, setUserControlSpaces] = useState([]);
  const [nameVal, setNameVal] = useState('');
  useEffect(() => {
    if (checkUser.userId) {
      var paramObj = {
        criteria: {
          userId: checkUser.userId,
          companyId: initialState?.currentUser?.companyId,
        },
      };
      queryUserInfo(paramObj)
        .then((res) => {
          var userControlSpaces = res?.data?.controlSpaceUserList || [];
          var controlSpaces = [];
          //处理可控工区
          userControlSpaces.forEach((item) => {
            controlSpaces.push(item.spaceId);
            if (item.isPermanentSpace) {
              setRadioValue(item.spaceId); //常驻
            }
          });
          setCheckedValues(controlSpaces);
        })
        .catch((err) => {});
    }
  }, [checkUser]);

  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };
  const onCheck = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
  };

  const saveUser = () => {
    //debugger;
    form
      .validateFields()
      .then((value) => {
        //处理可控工区
        var slist = [];
        checkedValues.forEach((item) => {
          if (item != 'special') {
            slist.push({
              companyId: initialState?.currentUser?.companyId,
              spaceId: item,
              isPermanentSpace: radioValue == item ? true : false,
              userId: checkUser.userId,
            });
          }
        });

        var param = {
          companyId: initialState?.currentUser?.companyId,
          controlSpaceUserList: slist,
          ...value,
        };
        checkUser.userId && (param.userId = checkUser.userId);
        saveUserInfo(param)
          .then((res) => {
            if (res.message) {
              message.error(res.message);
            } else {
              if (res.result == 'success') {
                onClose();
                refreshList();
              }
            }
          })
          .catch((err) => {});
      })
      .catch((err) => {});
  };
  const editUser = () => {
    setCheckSign('edit');
  };
  const menuItems = [
    {
      key: '1',
      label: (
        <div
          className={styles.operateLi}
          onClick={() => {
            setInvalidSign(true);
          }}
        >
          作废
        </div>
      ),
    },
  ];
  const UserTypeArr = {
    1: '普通成员',
    2: '临时成员',
    3: '管理员',
  };
  const invalidPerson = () => {
    //填写的用户名不对
    if (nameVal !== checkUser.name) return;
    deleteUser({ userId: checkUser.userId })
      .then((res) => {
        onClose();
        history.push(`/member/invalid`);
      })
      .catch((err) => {});
  };
  const nameValChange = (event) => {
    var value = event.target.value;
    setNameVal(value);
  };
  return (
    <>
      <Modal open closable={false} footer={null} width={760}>
        <div className={styles.modalmain}>
          <div className={styles.header}>
            <div
              className={styles.close}
              onClick={() => {
                onClose();
              }}
            >
              <Icon type="close" />
            </div>
            {checkUser.userId && !invalidSign && (
              <div className={styles.status}>
                <span
                  className={cx(styles.circle, {
                    [styles.activated]: checkUser.status == '待激活',
                  })}
                ></span>
                <span className={styles.cont}>{checkUser.status}</span>
                {!checkUser.oaId && checkUser.status != 5 && (
                  <Dropdown menu={{ items: menuItems }}>
                    <EllipsisOutlined style={{ color: '#C4C4C4', fontSize: '20px' }} />
                  </Dropdown>
                )}
              </div>
            )}
            <div className={styles.circlePic}>
              <Icon
                type="member"
                style={{
                  color: '#fff',
                  fontSize: '35px',
                }}
              ></Icon>
            </div>
          </div>
          {!invalidSign && (
            <>
              <div className={styles.content}>
                <Form
                  // {...formItemLayout}
                  form={form}
                  layout="vertical"
                  initialValues={{
                    ...checkUser,
                    manageUserType: checkUser?.manageUserType?.toString(),
                  }}
                >
                  <Row gutter={[32, 8]}>
                    <Col span={12}>
                      <Form.Item
                        shouldUpdate={(pre, curr) => {
                          return true;
                        }}
                        name="name"
                        label="姓名"
                        labelAlign="left"
                        rules={[
                          {
                            required: true,
                            message: '不能为空!',
                          },
                        ]}
                      >
                        {checkSign == 'check' || checkUser.oaId ? (
                          <Tooltip
                            title={checkUser.oaId ? 'OA同步人员，姓名不可修改' : ''}
                            placement="topRight"
                          >
                            <div className={styles.showName}>{checkUser.name}</div>
                          </Tooltip>
                        ) : (
                          <Input
                            autoComplete="off"
                            placeholder="输入姓名"
                            style={{ width: 300, height: 50 }}
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="manageUserType"
                        label="成员类型"
                        tooltip="短期的保洁、外包、顾问、实习生等可归为临时成员"
                        rules={[
                          {
                            required: true,
                            message: '不能为空!',
                          },
                        ]}
                      >
                        {checkSign == 'check' || temporary ? (
                          <div className={styles.showName}>
                            {UserTypeArr[checkUser.manageUserType] || '临时成员'}
                          </div>
                        ) : (
                          <Select placeholder="选择成员类型" style={{ width: 300, height: 50 }}>
                            <Select.Option value="1">普通成员</Select.Option>
                            <Select.Option value="3">管理员</Select.Option>
                            <Select.Option value="2">临时成员</Select.Option>
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="phone"
                        label="手机"
                        labelAlign="left"
                        rules={[
                          {
                            required: true,
                            message: '不能为空!',
                          },
                        ]}
                      >
                        {checkSign == 'check' || checkUser.oaId ? (
                          <Tooltip
                            title={checkUser.oaId ? 'OA同步人员，手机号不可修改' : ''}
                            placement="topRight"
                          >
                            <div className={styles.showName}>{checkUser.phone}</div>
                          </Tooltip>
                        ) : (
                          <Input
                            autoComplete="off"
                            prefix={<span>+86</span>}
                            style={{ width: 300, height: 50 }}
                            suffix={<ExclamationCircleOutlined />}
                            placeholder="输入手机号"
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item name="job" label="职务" labelAlign="left" hasFeedback>
                        {checkSign != 'check' ? (
                          <Input
                            autoComplete="off"
                            placeholder="输入职务"
                            style={{ width: 300, height: 50 }}
                          />
                        ) : (
                          <div className={styles.showName}>{checkUser.job}</div>
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item label="工区选择" labelAlign="left" hasFeedback>
                        <AreaTree
                          checkSign={checkSign}
                          spaceMap={spaceMap}
                          radioValue={radioValue}
                          setRadioValue={setRadioValue}
                          checkedValues={checkedValues}
                          setCheckedValues={setCheckedValues}
                        ></AreaTree>
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </div>
              <div className={styles.footer}>
                {checkSign != 'check' ? (
                  <div
                    className={styles.btn}
                    onClick={() => {
                      saveUser();
                    }}
                  >
                    <span>保存</span>
                  </div>
                ) : (
                  <div
                    className={styles.btn}
                    onClick={() => {
                      editUser();
                    }}
                  >
                    <span>编辑</span>
                  </div>
                )}
              </div>
            </>
          )}
          {invalidSign && (
            <div className={styles.invalidCont}>
              <div className={styles.title}>作废{checkUser.phone}的身份</div>
              <div className={styles.article}>
                该账号在贵公司的认证状态将失效，重新使用该软件需重新认证
              </div>
              <div className={styles.article}>
                将释放该账号下的所有权益，包括但不限于该公司空间控制、通行，碳积分兑换及相关消费活动
              </div>
              <div className={styles.article}>
                将保留该账号下所有已预约的空间、服务订单、访客邀请记录、历史设备操作记录及碳积分
              </div>
              <div className={styles.phoneTitle}>请在下方输入框内输入账号姓名</div>
              <div className={styles.phone}>{checkUser.phone}</div>
              <div className={styles.name}>
                <Input
                  autoComplete="off"
                  style={{ width: 300, height: 50 }}
                  value={nameVal}
                  onChange={nameValChange}
                ></Input>
              </div>
              <div
                onClick={invalidPerson}
                className={cx(styles.btnDiv, {
                  [styles.disableBtnDiv]: nameVal !== checkUser.name,
                })}
              >
                <span className={styles.btn}>作废</span>
              </div>
            </div>
          )}
        </div>
      </Modal>
    </>
  );
};

export default PersonModal;
