/*
 * @Author: zhangleyuan
 * @Date: 2020-11-27 15:06:31
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-05 10:26:25
 * @Description: 描述一下
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React, { useEffect, useState, useContext } from "react";
import { withRouter } from "react-router-dom";
import { Form, Button, Input, message } from "antd";
import _ from "underscore";
import $ from "jquery";
import { CropperModal } from "@/components/";
import IdentificationModal from "./IdentificationModal";
import ChangePhoneModal from "./ChangePhoneModal";
import BaseService from "@/domains/basic-domain/baseService";
import StoreService from "@/domains/store-domain/storeService";
import WWOpenDataCom from '@/components/WWOpenDataCom';
import User from "@/common/js/user";
import "./index.less";
import { XMContext } from "@/store/context";
import { setStoreList } from "@/store/actions/index";
function PersonalInfoPage() {
  const [avatar, setAvatar] = useState(
    "https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png"
  );
  const [imgUrl, setImgUrl] = useState(avatar);
  const [nickName, setNickName] = useState("");
  const [cropperModalVisible, setCropperModalVisible] = useState(false);
  const [IdentificationModalVisible, setIdentificationModalVisible] = useState(
    false
  );
  const [changePhoneModalVisible, setChangePhoneModalVisible] = useState(false);
  const [roleCodes, setRoleCodes] = useState([]);
  const [phone, setPhone] = useState("");
  const [weChatAccount, setWeChatAccount] = useState("");
  const [departmentList,setDepartmentList] = useState([]);
  const storeUserId = User.getStoreUserId();
  const ctx: any = useContext(XMContext);
  const userId = User.getUserId();
  const isWorkWechat = !!(User.getStoreType() === "WE_CHAT_STORE");
  
  window.ctx = ctx;
  useEffect(() => {
    storeUserId && getUserInfo();
  }, [storeUserId]);
  
  function getUserInfo() {
    const param = {
      storeUserId: User.getStoreUserId(),
    };
    BaseService.getStoreUser(param).then((res) => {
      const { nickName, phone, roleCodes, weChatAccount,depNameList=[]} = res.result;
      setNickName(nickName);
      setPhone(phone);
      setRoleCodes(roleCodes);
      setWeChatAccount(weChatAccount);
      setDepartmentList(depNameList)
      if (res.result.avatar) {
        setAvatar(res.result.avatar);
      }
    });
  }

  function _handleUpdateAvatar(e: any): any {
    console.log("update");
    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 identificationConfirm(): any {
    setIdentificationModalVisible(false);
    setChangePhoneModalVisible(true);
  }

  function saveUserInfo() {
    const params = isWorkWechat ? {
      nickName,
      phone: String(phone),
      roleCodes: roleCodes,
      avatar,
      storeUserId: User.getStoreUserId(),
      storeId:User.getStoreId()
    } : {
      nickName,
      roleCodes: roleCodes,
      avatar,
      storeUserId: User.getStoreUserId(),
      storeId:User.getStoreId()
    };
    
    StoreService.editEmployee(params).then((res) => {
      getStoreGroupAndStoreList();
      message.success("保存成功");
    });
  }

  function getStoreGroupAndStoreList() {
    BaseService.getUserStore({ userId }).then((res) => {
      const { storeVOS = [] } = res.result;
      ctx.dispatch(setStoreList(storeVOS));
    });
  }

  function changePhoneConfirm(phone: any) {
    setPhone(phone);
  }

  return (
    <div className="page personal-info-page">
        <div className="content-header">个人设置</div>
        <div className="box">
          <Form>
            <div className="avatat-item">
              <span className="label">头像：</span>
              <img className="avatar" src={avatar}></img>
              {cropperModalVisible && (
                <CropperModal
                  imgUrl={imgUrl}
                  save={changeAvatar}
                  close={closeCropperModal}
                />
              )}
            </div>
            <div className="name-item">
              <span className="label">昵称：</span>
              <Input
                placeholder="请输入姓名，最多15个字"
                style={{ width: 300, height: 32 }}
                value={nickName}
                maxLength={15}
                onChange={(e) => {
                  setNickName(e.target.value);
                }}
              />
            </div>
            <div className="phone-item">
                <span className="label">企业微信姓名：</span>
                <span><WWOpenDataCom type="userName" openid={weChatAccount}/></span>
            </div>
            {isWorkWechat ? (
              <div className="phone-item">
                <span className="label">企业微信帐号：</span>
                <span>{weChatAccount}</span>
              </div>
            ) : (
              <div className="phone-item">
                <span className="label">手机号：</span>
                <span>{phone}</span>
                <Button
                  className="changePhoneBtn"
                  onClick={() => {
                    setIdentificationModalVisible(true);
                  }}
                >
                  更换手机号
                </Button>
              </div>
            )}
            <div>
                <span className="label">所在部门：</span>
                {departmentList.map((item,index)=>{
                  return  <span><WWOpenDataCom type="departmentName" openid={item}/>{index<departmentList.length-1?'、':''}</span>
                })}
            </div>
            <div className="save-btn">
              <Button
                type="primary"
                onClick={() => {
                  saveUserInfo();
                }}
              >
                保存
              </Button>
            </div>
          </Form>
        </div>
        {IdentificationModalVisible && (
          <IdentificationModal
            phone={phone}
            onClose={() => {
              setIdentificationModalVisible(false);
            }}
            onConfirm={() => {
              identificationConfirm();
            }}
          />
        )}

        {changePhoneModalVisible && (
          <ChangePhoneModal
            onClose={() => {
              setChangePhoneModalVisible(false);
            }}
            onConfirm={changePhoneConfirm}
          />
        )}
    </div>
  );
}

export default withRouter(PersonalInfoPage);
