/*
 * @Author: wufan
 * @Date: 2020-07-09 14:03:09
 * @Last Modified by: chenshu
 * @Last Modified time: 2021-04-10 14:36:43
 * 学院管理-员工管理
 */
import React, { useEffect, useState } from "react";
import { withRouter } from "react-router-dom";
import _ from "underscore";
import { CheckBox, PageControl } from "@/components";
import { Button, Table, Modal, message, Input,Tooltip} from "antd";
import { XMTable } from '@/components';
import college from '@/common/lottie/college.json';
import StoreService from "@/domains/store-domain/storeService";
import EmployeeAddOrEditModal from "../store-manage/EmployeeAddOrEditModal";
import User from "@/common/js/user";
import WechatApi from '@/common/js/wechatApi';
import WWOpenDataCom from '@/components/WWOpenDataCom';
import LimitTip from "./LimitTip";

import "./EmployeeManage.less";
import NewChooseMembersModal from "./modal/NewChooseMembersModal";
const { confirm } = Modal;
const { Search } = Input;

declare var window: any;
interface RecordTypes {
  id: string;
  role: string;
  roleCodes: Array<string>;
  userId: string;
  nickName: string;
  phone: string;
  avatar?: string;
  weChatAccount?: string;
  depNameList:any
}

interface RoleItemType {
  isChecked: boolean;
  roleCode: string;
  name: string;
  id: string;
}

interface QueryType {
  current: number;
  size: number;
  nickName?: string;
  phone?: string;
  roleCodes: Array<string>;
}

interface ChoosedItemType {
  nickName?: string;
  phone?: string;
  role: Array<string>;
  avatar?: string;
  storeUserId?: string;
  weChatAccount?: string;
  depNameList?:any;
}

function EmployeeManage() {
  const [employeeList, setEmployeeList] = useState([]);
  const [query, setQuery] = useState<QueryType>({
    current: 0,
    size: 10,
    nickName: "",
    phone: "",
    roleCodes: [],
  });

  const [total, setTotal] = useState(0);
  const [realTotal, setRealTotal] = useState(0)
  const [model, setModel] = useState<React.ReactNode>(null);
  const [employeeModal, setEmployeeModal] = useState(false);
  const [choosedItem, setChooseItem] = useState<ChoosedItemType>({
    nickName: "",
    phone: "",
    role: [],
    avatar: "",
  });
  const [roleIds, setRoleIds] = useState<Array<RoleItemType>>([]);
  const storeId = User.getStoreId();
  const StoreType = User.getStoreType();
  const isWorkWechat = !!(StoreType === "WE_CHAT_STORE");

  useEffect(() => {
    if (!User.getEnterpriseId()) {
      window.RCHistory.replace('/employees-manage');
    }
    //获取员工数
    const _query = {
      current: 0,
      size: 10,
      nickName: "",
      phone: "",
      roleCodes: [],
    }
    StoreService.getEmployeeList(_query).then((res: any) => {
      setRealTotal(res.result.total);
    });
  }, [])

  useEffect(() => {
    getEmployeeList();
  }, [query]);

  useEffect(() => {
    getListInfo();
   
  }, [storeId]);

 

  async function getListInfo() {
    await getStoreRole();
  }

  function getEmployeeList() {
    let _query = _.clone(query);
    _query.current = query.current + 1;
    StoreService.getEmployeeList(_query).then((res: any) => {
      setEmployeeList(res.result.records);
      setTotal(res.result.total);
    });
  }

  function getStoreRole() {
    StoreService.getStoreRole({ storeId }).then((res: any) => {
      const data = [...res.result];
      const _query = { ...query };

      let _data = _.filter(data, (_item) => {
        return _item.roleCode !== "StoreManager";
      });

      setRoleIds(_data);
    });
  }

  function parseColumn() {
    const columns = [
      {
        title: "员工",
        dataIndex: "nickName",
        render: (val: string, record: RecordTypes) => {
          return (
            <div className="employee-info">
              {isWorkWechat && (
                <img
                  src={
                    record.avatar ||
                    "https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png"
                  }
                  alt=""
                />
              )}

              {/* <span className="title">{val}</span> */}
              <span className="title">
              <WWOpenDataCom type="userName" openid={val}/>
              </span>
            </div>
          );
        },
      },
      {
        title: "手机号",
        dataIndex: "phone",
        key: "phone",
        render: (val: string) => {
          return <div>{val || '-'}</div>;
        },
      },
      {
        title: "部门",
        dataIndex: "depNameList",
        key: "depNameList",
        render: (val:string,record:RecordTypes) => {
          if(!record.depNameList){
            return <span>-</span>
          }
          if(record.depNameList.length === 0){
            return <span>-</span>
          }
          // return record.depNameList.map((item,index)=>{
          //   return <span><WWOpenDataCom type="departmentName" openid={item}/>{index<(record.depNameList.length -1)?';':''}</span>;
          // })
          return <Tooltip title={<div>{handleDepName(record.depNameList)}</div>} placement='top' arrowPointAtCenter><div className="post-name"> {record.depNameList.map((item:any, index:any) => {
            return <span><WWOpenDataCom type="departmentName" openid={item}/>{index<(record.depNameList.length -1)?'；':''}</span>
            })}
          </div>
          </Tooltip>
        },
      },
      {
        title: "身份",
        dataIndex: "role",
        key: "role",
        render: (val: string) => {
          return <div>{val.split("，").join("、")}</div>;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        render: (val: string, record: RecordTypes) => {
          return record.role === "学院管理员" ||
            record.userId === User.getUserId() ? (
            <div className="no-operate">-</div>
          ) : (
            <div className="operation">
              <span className="edit" onClick={() => handleEditEmployee(record)}>
                编辑
              </span>
              <span className="divider-line">{" | "}</span>
              <span
                className="delete"
                onClick={() => {
                  handleDeleteWorkWechatEmployeeConfirm(record)
                }}
              >
                删除
              </span>
            </div>
          );
        },
      },
    ];

    if (isWorkWechat && columns) {
      const item = {
        title: "企业微信账号",
        dataIndex: "weChatAccount",
        key: "weChatAccount",
        render: (val: string) => {
          return <div>{val}</div>;
        },
      };
      columns.splice(1, 1, item);
    }
    return columns;
  }

  function handleDepName(depArray:any):any{
    const depArrayDom = depArray.map((item:any, index:any) => {
    return <span><WWOpenDataCom type="departmentName" openid={item}/>；</span>
    });
    return depArrayDom;
  };

  function handleEditEmployee(record: RecordTypes) {
    const { nickName, phone, roleCodes, avatar, id, weChatAccount,depNameList} = record;
    const _choosesItem = {
      nickName: nickName,
      phone: phone,
      role: roleCodes,
      avatar: avatar,
      storeUserId: id,
      weChatAccount,
      depNameList:depNameList
    };
    setChooseItem(_choosesItem);
    const model: React.ReactNode = (
      <EmployeeAddOrEditModal
        choosedItem={_choosesItem}
        onClose={() => {
          setModel(null);
          getEmployeeList();
          setChooseItem({
            nickName: "",
            phone: "",
            role: [],
            avatar: "",
            storeUserId: "",
            weChatAccount:"",
            depNameList:[]
          });
        }}
        isWorkWechat={isWorkWechat}
      />
    );
    setModel(model);
  }

  function handleDeleteWorkWechatEmployeeConfirm(record: RecordTypes) {
    return confirm({
      title: "你确定要删除此员工吗？",
      content: "删除后数据无法恢复",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      okType: "danger",
      cancelText: "取消",
      onOk: () => {
        handleDeleteEmployee(record.id);
      },
    });
  }

  function handleToAddEmployee() {
    setEmployeeModal(true);
  }

  function handleDeleteEmployee(storeUserId: string) {
    StoreService.deleteEmployee({ storeUserId }).then((res: any) => {
      const msg = isWorkWechat ? "员工已删除" : "讲师已删除";
      message.success(msg);
      getEmployeeList();
    });
  }
  function updateListData(){
    let num:any;
    const params = {
      enterpriseId:User.getEnterpriseId(),
      storeId:User.getStoreId(),
      userType:'USER'
    }
    StoreService.getSyncCount(params).then((res) => {
      num = res.result;
      if(num<3){
        return confirm({
          title: "确定更新列表数据吗？",
          content: `员工数据来源企微通讯录，一天只能更新3次，今日还能更新${3-num}次。`,
          icon: (
            <span className="icon iconfont default-confirm-icon">&#xe839; </span>
          ),
          okText: "确定",
          cancelText: "取消",
          onOk: () => {
            confirmUpdateListData()
          },
        });
      }else{
        Modal.warning({
          title: '提示',
          okText: '我知道了',
          content: '员工数据今日更新次数已达上限（3次），无法继续更新。',
          icon: (
            <span className='icon iconfont default-confirm-icon' style={{ color: '#FFBB54 !important' }}>
              &#xe834;
            </span>
          ),
        });
      }
    });

   
  }

  function confirmUpdateListData(){
    const params = {
      enterpriseId:User.getEnterpriseId(),
      storeId:User.getStoreId(),
      userType:'USER'
    }
    StoreService.syncWorkWeChatDepartment(params).then((res) => {
      getEmployeeList();
      message.success('已更新');
    });
  }
  return (
    <div className="page employee-manage-page">
        <div className="content-header">角色管理</div>
        <div className="box">
          <div className="box-header">
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "flex-start",
                padding: "0px 0 4px",
              }}
            >
              <div>
              搜索员工：
              <Search
                style={{
                  width: 300,
                  marginRight: 40,
                }}
                placeholder={
                  isWorkWechat ? "请输入员工昵称" : "搜索员工昵称/手机号"
                }
                onSearch={(value) => {
                  const _query = { ...query };
                  // 企业微信用户只能搜索员工昵称
                  if (isWorkWechat) {
                    _query.nickName = value;
                    _query.current = 0;
                    setQuery(_query);
                    return;
                  }

                  if (value) {
                    const isPhone = (value || "").match(/^\d+$/);
                    const name = isPhone ? "phone" : "nickName";
                    const otherName = isPhone ? "nickName" : "phone";
                    _query[name] = value;
                    _query[otherName] = "";
                    _query.current = 0;
                  } else {
                    _query.nickName = "";
                    _query.phone = "";
                    _query.current = 0;
                  }
                  setQuery(_query);
                }}
                enterButton={<span className="icon iconfont">&#xe832;</span>}
              />
            </div>

            <div>
              角色：
              {_.map(roleIds, (item: any) => {
                return (
                  <CheckBox
                    key={item.roleCode}
                    text={item.name}
                    name={item.roleCode}
                    onChange={(e: any) => {
                      const { checked, name } = e.target;
                      const _query = { ...query };
                      _query.roleCodes = [];
                      _query.current = 0;
                      const _roleIds: Array<RoleItemType> = roleIds.map(
                        (_item: RoleItemType) => {
                          if (name === _item.roleCode) {
                            if (checked) {
                              _item.isChecked = true;
                            } else {
                              _item.isChecked = false;
                            }
                          }
                          if (_item.isChecked) {
                            _query.roleCodes.push(_item.roleCode);
                          }
                          return _item;
                        }
                      );

                      setRoleIds(_roleIds);
                      setQuery(_query);
                    }}
                    defaultChecked={item.isChecked}
                  />
                );
              })}
            </div>
          </div>
          {(User.getUserRole() === 'CloudManager' || User.getUserRole() === 'StoreManager') &&
              <>
                <Button
                  onClick={() => {
                    handleToAddEmployee();
                  }}
                  type="primary"
                  className="add-show-btn"
                >
                  添加员工
                </Button>
                <Button className="update-user-btn" onClick={()=>{updateListData()}}>更新列表数据</Button>
                <span className="origin-text">数据来源企业微信通讯录</span>
                <a
                  href="https://www.yuque.com/wangzhong-zkqw0/qixue"
                  target="_blank"
                >
                  <span className="view-text">查看数据更新说明</span>
                </a>
               </>
            }
        </div>
        <LimitTip type="员工" total={realTotal} tip={() => { return (<div>数据为当前学院的员工数，若员工存在多个学院，企业人数只统计为1人</div>) }} />
        <div className="box-body">
          <XMTable
            renderEmpty={{
              image: college,
              description: '暂无数据'
            }}
            size={"middle"}
            pagination={false}
            dataSource={employeeList}
            columns={parseColumn()}
            rowKey={(item: any) => item.id}
            bordered
          />
        </div>
        <div className="box-footer">
          <PageControl
            current={query.current}
            pageSize={query.size}
            total={total}
            toPage={(page: any) => {
              const queryStates = _.clone(query);
              queryStates.current = page;
              setQuery(queryStates);
            }}
          />
        </div>
      </div>
      {model}
      {employeeModal &&
        <NewChooseMembersModal
            treeDepType="DEP_CHAT"
            visible={employeeModal}
            type="USER"
            close={()=>{setEmployeeModal(false)}}
            onConfirm={() => {
              setEmployeeModal(false)
              message.success('添加成功')
              getEmployeeList();
            }}
        />
      }
    </div>
  );
}

export default withRouter(EmployeeManage);
