/*
 * @Author: wufan
 * @Date: 2020-11-27 16:21:49
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-09 19:20:49
 * @Description: Description
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useEffect } from 'react';
import { Modal, Form, Button, Input, InputNumber, Radio, Row, Col, message, Tooltip } from 'antd';
import _, { values } from 'underscore';
import './EmployeeAddOrEditModal.less';
import { CropperModal } from '@/components/';
import StoreService from '@/domains/store-domain/storeService';
import WWOpenDataCom from '@/components/WWOpenDataCom';
import $ from 'jquery';
import User from '@/common/js/user';

const RadioGroup = Radio.Group;
declare let window: any;

interface AddEmployeeModalProps {
  choosedItem: {
    nickName?: string;
    phone?: string;
    role: Array<string>;
    avatar?: string;
    storeUserId?: string;
    weChatAccount?: string;
    depNameList?: any;
  };
  onClose: () => void;
  isWorkWechat: boolean;
}
function AddEmployeeModal(props: AddEmployeeModalProps) {
  const [nickName, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [role, setRole] = useState('CloudLecturer');
  const [avatar, setAvatar] = useState('https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png');
  const storeUserId = props.choosedItem.storeUserId;
  const [imgUrl, setImgUrl] = useState(avatar || 'https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png');
  const [nameErrorMsg, setNameErrorMsg] = useState('');
  const [nameStatus, setNameStatus] = useState<'' | 'error' | 'success' | 'warning' | 'validating' | undefined>();
  const [phoneErrorMessage, setPhoneErrorMessage] = useState('');
  const [phoneStatus, setPhoneStatus] = useState<'' | 'error' | 'success' | 'warning' | 'validating' | undefined>();
  const [cropperModalVisible, setCropperModalVisible] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    if (props.choosedItem.nickName) {
      console.log('props.choosedItem', props.choosedItem);
      setName(props.choosedItem.nickName);
      console.log('choosedItem', props.choosedItem);
      props.choosedItem.phone && setPhone(props.choosedItem.phone);
      props.choosedItem.role && setRole(props.choosedItem.role[0]);
      props.choosedItem.avatar && setAvatar(props.choosedItem.avatar);
      const _role = props.choosedItem.role[0];
      form.setFieldsValue({
        nickName: props.choosedItem.nickName,
        role: _role,
        phone: props.choosedItem.phone,
        avatar: props.choosedItem.avatar,
      });
    }
  }, [props.choosedItem.nickName]);

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };

  function handleChangeRole(value: string) {
    setRole(value);
  }

  function _handleUpdateAvatar(e: any): any {
    const avatar = e.target.files[0];
    const newUrl = URL.createObjectURL(avatar);
    const $image = $('#image');
    setImgUrl(newUrl);
    setCropperModalVisible(true);
  }

  function _onUpload(): any {
    $('#CrpperAvatarPic').trigger('click');
  }

  function changeAvatar(img: string): any {
    form.setFieldsValue({
      avatar: img,
    });
    setAvatar(img);
    setImgUrl(img);
  }

  function closeCropperModal(): any {
    setCropperModalVisible(false);
  }

  function handleOk(): void {
    const values = form.getFieldsValue();
    if (!values.nickName.trim()) {
      setNameErrorMsg('请输入员工昵称');
      setNameStatus('error');
      return;
    }
    setNameErrorMsg('');
    setNameStatus('');

    if (!String(values.phone) && !props.isWorkWechat) {
      setPhoneErrorMessage('请输入手机号码');
      setPhoneStatus('error');
      return;
    }
    setPhoneErrorMessage('');
    setPhoneStatus('');

    if (String(values.phone).length !== 11 && !props.isWorkWechat) {
      setPhoneErrorMessage('请输入11位手机号');
      setPhoneStatus('error');
      return;
    }
    setPhoneErrorMessage('');
    setPhoneStatus('');

    props.choosedItem.nickName ? handleEditEmployee() : handleAddEmployee();
  }

  function handleChangeValues(name: string, value: any) {
    switch (name) {
      case 'nickName':
        form.setFieldsValue({ nickName: value });
        setName(value);
        return;

      case 'phone':
        form.setFieldsValue({ phone: value });
        setPhone(value);
        setPhoneErrorMessage('');
        setPhoneStatus('');
        return;

      case 'role':
        form.setFieldsValue({ role: value });
        setRole(value);
        return;

      default:
        break;
    }
  }

  function handleAddEmployee() {
    const params = {
      nickName,
      phone: String(phone),
      roleCodes: [role],
      avatar,
    };
    console.log('params', params);
    StoreService.addEmployee(params).then((res) => {
      message.success('保存成功');
      props.onClose();
    });
  }

  function handleEditEmployee() {
    const params = {
      nickName,
      phone: String(phone),
      roleCodes: [role],
      avatar,
      storeUserId: storeUserId,
      storeId: User.getStoreId(),
    };
    console.log('params', params);

    StoreService.editEmployee(params).then((res) => {
      message.success('编辑成功');
      props.onClose();
    });
  }

  return (
    <Modal
      visible={true}
      title={`${props.choosedItem.nickName ? '编辑员工' : '添加员工'}`}
      className='employee-add-modal'
      width={680}
      onCancel={props.onClose}
      onOk={handleOk}
      maskClosable={false}
      closeIcon={<span className='icon iconfont modal-close-icon'>&#xe6ef;</span>}>
      <Row style={{ height: 271 }}>
        <Col span={18}>
          <Form {...layout} form={form} name='basic' initialValues={{ nickName: nickName, phone: phone, role: role }}>
            <Form.Item
              label='员工姓名'
              name='nickName'
              // rules={[{ required: true }]}
              // validateStatus={nameStatus}
              // help={nameErrorMsg || undefined}
              style={{ marginBottom: 0 }}>
              <div
                style={{
                  whiteSpace: 'nowrap',
                  textOverflow: 'ellipsis',
                  overflow: 'hidden',
                }}>
                <WWOpenDataCom type='userName' openid={props.choosedItem.weChatAccount} />
              </div>
            </Form.Item>
            {props.isWorkWechat ? (
              <Form.Item label='企业微信账号' name='weChatAccount'>
                <Tooltip title={props.choosedItem.weChatAccount}>
                  <div
                    style={{
                      whiteSpace: 'nowrap',
                      textOverflow: 'ellipsis',
                      overflow: 'hidden',
                    }}>
                    {props.choosedItem.weChatAccount}
                  </div>
                </Tooltip>
              </Form.Item>
            ) : (
              <Form.Item label='手机号码' name='phone' rules={[{ required: true }]} validateStatus={phoneStatus} help={phoneErrorMessage}>
                <Input
                  style={{ width: 200 }}
                  placeholder='请输入手机号'
                  maxLength={11}
                  autoComplete='off'
                  disabled={!!props.choosedItem.nickName}
                  onChange={(e) => {
                    if (e.target.value.match(/^\d+$/)) {
                      handleChangeValues('phone', e.target.value);
                    } else {
                      setPhoneErrorMessage('只能输入数字');
                      setPhoneStatus('error');
                    }
                  }}
                />
              </Form.Item>
            )}
            <Form.Item label='所在部门' name='weChatAccount' style={{ marginBottom: 0 }}>
              <div
                style={{
                  whiteSpace: 'nowrap',
                  textOverflow: 'ellipsis',
                  overflow: 'hidden',
                }}>
                {props.choosedItem.depNameList.map((item: any, index: any) => {
                  return (
                    <span>
                      <WWOpenDataCom type='departmentName' openid={item} />
                      {index < props.choosedItem.depNameList.length - 1 ? '、' : ''}
                    </span>
                  );
                })}
              </div>
            </Form.Item>
            <Form.Item label='员工角色' name='role' rules={[{ required: false }]} style={{ marginBottom: '-2px !important' }} className='mt-26'>
              <RadioGroup
                onChange={(e) => {
                  handleChangeValues('role', e.target.value);
                }}
                className='mt5'>
                <Radio value={'CloudLecturer'} className='mt-4'>
                  <span style={{ color: '#333' }}>普通讲师</span>
                  <p className='radio-tip'>仅可查看/使用与自己相关的文件和课表，并进行上课</p>
                </Radio>
                <Radio value={'CloudManager'}>
                  <span style={{ color: '#333' }}>管理员</span>
                  <p className='radio-tip'>可执行学院中所有的操作</p>
                </Radio>
              </RadioGroup>
            </Form.Item>
          </Form>
        </Col>

        <Col span={6}>
          <div className='avatar-box'>
            <div className='avatar-text'>头像</div>
            <div className='avatart-img'>
              <img className='avatar' src={avatar}></img>
            </div>
          </div>
        </Col>
      </Row>
    </Modal>
  );
}

export default AddEmployeeModal;
