/*
 * @Author: wufan
 * @Date: 2020-11-27 16:21:49
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-09 14:21:35
 * @Description: Description
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useEffect } from "react";
import {
  Modal,
  Form,
  Button,
  Input,
  InputNumber,
  Radio,
  Row,
  Col,
  message,
} from "antd";
import _, { values } from "underscore";
import "./EmployeeAddOrEditModal.less";
import { CropperModal } from "@/components/";
import StoreService from "@/domains/store-domain/storeService";
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
  };
  onClose: () => void;
  isWorkWechat: boolean;
}
function AddEmployeeModal(props: AddEmployeeModalProps) {
  const [nickName, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [role, setRole] = useState("CloudOperator");
  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: 5 },
    wrapperCol: { span: 12 },
  };

  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>
        <Col span={16}>
          <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}
              style={{marginBottom:'-2px !important'}}
             className="mt-4"
            >
              <Input
                style={{ width: 200 }}
                placeholder="请输入员工昵称"
                maxLength={15}
                autoComplete="off"
                onChange={(e) => handleChangeValues("nickName", e.target.value)}
              />
            </Form.Item>
            {props.isWorkWechat ? (
              <Form.Item
                label="企业微信账号"
                name="weChatAccount"
                style={{marginBottom:'-2px !important'}}
                className="mt-10"
              >
                <div>{props.choosedItem.weChatAccount}</div>
              </Form.Item>
            ) : (
              <Form.Item
                label="手机号码"
                name="phone"
                rules={[{ required: true }]}
                validateStatus={phoneStatus}
                help={phoneErrorMessage}
                style={{marginBottom:'-2px !important'}}
                className="mt-10"
              >
                <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="role"
              rules={[{ required: false }]}
              style={{marginBottom:'-2px !important'}}
              className="mt-26"
            >
              <RadioGroup
                onChange={(e) => {
                  handleChangeValues("role", e.target.value);
                }}
                className="mt5"
              >
                <Radio value={"CloudOperator"} className="mt-4">
                  <span style={{ color: "#333" }}>运营师</span>
                  <p className="radio-tip">
                  仅可查看/转发培训计划内容，并查看其负责的用户学习进度
                  </p>
                </Radio>
                <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={8}>
          <div className="avatar-box">
            <div className="avatar-text">头像</div>
            <div className="avatart-img">
              <img className="avatar" src={avatar}></img>
            </div>
            <div className="upload-avatar">
              <Button id="click_upload_btn" onClick={_onUpload}>
                点击上传
              </Button>
              <input
                type="file"
                accept="image/*"
                id="CrpperAvatarPic"
                style={{ display: "none" }}
                onChange={_handleUpdateAvatar}
              />
              {cropperModalVisible && (
                <CropperModal
                  imgUrl={imgUrl}
                  save={changeAvatar}
                  close={closeCropperModal}
                />
              )}
            </div>
          </div>
        </Col>
      </Row>
    </Modal>
  );
}

export default AddEmployeeModal;
