/*
 * @Author: wufan
 * @Date: 2020-11-27 16:21:49
 * @LastEditors: wufan
 * @LastEditTime: 2020-12-04 15:02:22
 * @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 baseImg from "@/common/images/xiaomai-IMG.png";
import { CropperModal } from "@/components/";
import StoreService from "@/domains/store-domain/storeService";
import UpLoad from "../common/UpLoad";
import $ from "jquery";
import User from "@/common/js/user";

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

interface AddEmployeeModalProps {
  isOpen: boolean;
  choosedItem: {
    nickName?: string;
    phone?: string;
    role: Array<string>;
    avatar?: string;
    storeUserId?: string;
  };
  onClose: () => void;
}

function AddEmployeeModal(props: AddEmployeeModalProps) {
  const [nickName, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [role, setRole] = useState("CloudLecturer");
  const [avatar, setAvatar] = useState(baseImg);
  const storeUserId = props.choosedItem.storeUserId;
  const [imgUrl, setImgUrl] = useState(avatar);
  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);
      props.choosedItem.phone && setPhone(props.choosedItem.phone);
      props.choosedItem.role && setRole(props.choosedItem.role[0]);
      props.choosedItem.avatar && setAvatar(avatar || baseImg);
      const _role = props.choosedItem.role[0] === "讲师" ? "CloudLecturer" : "CloudManager";
      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 },
  };

  const onFinish = (values: any) => {
    console.log("Success:", values);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  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 {
    setAvatar(img);
    setImgUrl(img);
  }

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

  function handleOk(): void {
    const values = form.getFieldsValue();
    console.log("values", values);
    if (!values.nickName.trim()) {
      setNameErrorMsg("请输入员工姓名");
      setNameStatus("error");
      return;
    }
    setNameErrorMsg("");
    setNameStatus("");

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

    if (String(values.phone).length !== 11) {
      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);
        return;

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

      default:
        break;
    }

  }

  function handleAddEmployee() {
    const params = {
      nickName,
      phone: String(phone),
      roleCodes:[role],
      // avatar,
      storeId:User.getStoreId()
    };
    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
    };
    console.log("params",params);

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

  console.log("values",form,form.getFieldsValue())
  return (
    <Modal
      visible={props.isOpen}
      title={`${props.choosedItem.nickName ? "编辑员工" : "添加员工"}`}
      className="employee-add-modal"
      width={680}
      onCancel={props.onClose}
      onOk={handleOk}
    >
      <Row>
        <Col span={16}>
          <Form
            {...layout}
            form={form}
            name="basic"
            initialValues={{ nickName: nickName, phone: phone, role: role }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <Form.Item
              label="员工姓名"
              name="nickName"
              rules={[{ required: true }]}
              validateStatus={nameStatus}
              help={nameErrorMsg}
            >
              <Input
                style={{ width: 200 }}
                // value={nickName}
                placeholder="请输入员工名称"
                maxLength={15}
                onChange={(e) => handleChangeValues("nickName", e.target.value)}
              />
            </Form.Item>

            <Form.Item
              label="手机号码"
              name="phone"
              rules={[{ required: true }]}
              validateStatus={phoneStatus}
              help={phoneErrorMessage}
            >
              <InputNumber
                style={{ width: 200 }}
                // value={phone}
                placeholder="请输入手机号"
                maxLength={11}
                disabled={!!props.choosedItem.nickName}
                onChange={(value) => handleChangeValues("phone", value)}
              />
            </Form.Item>

            <Form.Item
              label="员工身份"
              name="role"
              rules={[{ required: false }]}
            >
              <RadioGroup
                // value={role}
                onChange={(e) => {
                  handleChangeValues("role", e.target.value);
                }}
              >
                <Radio value={"CloudLecturer"}>
                  <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;
