package com.sifang.modules.sunshine.partnerManagement.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.config.SfCacheService;

import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.partnerManagement.dao.PartnerStaffDao;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartnerStaff;
import com.sifang.modules.sunshine.partnerManagement.vo.PartnerStaffVo;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.dao.UserDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PartnerStaffService extends BaseService {

    @Autowired
    private PartnerStaffDao partnerStaffDao;

    public CrmPartnerStaff getById(String id) {
        return partnerStaffDao.get(id);
    }

    @Autowired
    UserDao userDao;

    @Autowired
    SfCacheService sfCacheService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 获取服务商员工设置列表数据
     *
     * @return
     */
    public List<Record> getPartnerEmployeData(Map<String, String> map, String traderId) {
        List<Record> memberRds ;
        User user = UserUtils.getUser();
        String emps = sfCacheService.hget("partnerStaff",user.getId());
        logger.info("getPartnerEmployeData emps :{}",emps);
        if(StringUtil.isNotBlank(emps)){
            memberRds =new Gson().fromJson(emps, new TypeToken< List<Record>>() {
            }.getType());
            logger.info("getPartnerEmployeData 缓存取数据 memberRds :{}",memberRds);
        }else{
            memberRds = partnerStaffDao.getTaderEmployeData(map, traderId);
            sfCacheService.hset("partnerStaff",user.getId(),new Gson().toJson(memberRds));
        }
        return memberRds;
    }

    /**
     * 新增员工保存之前进行校验登录账号是否已经存在
     *
     * @param map
     * @return
     */
    public String beforeSave(Map<String, String> map) {
        String id = "";
        String mess = "0";//正常
        String loginName = map.get("loginName");
        boolean rd = partnerStaffDao.getExistsLoginName(loginName);
        if (rd) {
            mess = "1";
        }
        return mess;
    }


    public String getStaffIsBrowse(String userId){
        return Db.queryStr("SELECT is_browse FROM crm_partner_staff WHERE user_id=?",userId);
    }

    /**
     * 查询修改员工信息页面数据
     *
     * @return
     */
    public Record getSiteEmployeeById(String id, String traderId) {
        Record rd = new Record();
        if (StrKit.isBlank(id)) {
            return rd;
        } else {
            rd = partnerStaffDao.getSiteEmployeeById(id, traderId);
            return rd;
        }
    }


    /**
     * 保存工程师
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object saveTraderEmploye(PartnerStaffVo staffVo){
        Result result = new Result();
        String loginName= staffVo.getLoginName();
        try{

            User us = UserUtils.getUser();
            sfCacheService.hdel("partnerStaff",us.getId());
            String partner_id = partnerStaffDao.getPartnerIdByUserId(us.getId());
            List<Record> list = partnerStaffDao.getEmpByName(staffVo.getName(),partner_id,staffVo.getId());

            if (list.size()>0) {
                    result.setCode("203");
                    return result;
                }
            CrmPartnerStaff emp;

            if(StringUtil.isNotBlank(staffVo.getId())){
                emp = partnerStaffDao.get(staffVo.getId());
                User user = userDao.get(emp.getUserId());
                if (user==null) {
                    if(partnerStaffDao.getExistsLoginName(loginName)){
                        result.setCode("201");
                        return result;
                    }
                    user = new User();
                    user.setCreateBy(UserUtils.getUser().getId());
                    user.setUserType("a");
                }
                if (partnerStaffDao.getExistsLoginNameNew(user.getId(),loginName)) {
                    result.setCode("201");
                    return result;
                }
                user.setLoginName(loginName);
                if (!staffVo.getPassword().equals("default")) {
                    String passwords = HashKit.md5(staffVo.getPassword());
                    if (!user.getPassword().equals(passwords)) {
                        user.setPassword(passwords);
                    }
                }
                user.setMobile(staffVo.getMobile());
                userDao.save(user);
                emp.setIsBrowse(staffVo.getIsBrowse());
                emp.setName(staffVo.getName());
                emp.setMobile(staffVo.getMobile());
                emp.setJobNumber(staffVo.getJobNumber());
                emp.setInductionTime(DateUtils.parseDate(staffVo.getInductionTime()));
                partnerStaffDao.save(emp);
                logger.info("修改保存表数据成功："+emp+",saveTime:"+ DateUtils.getDateTime());
                result.setCode("200");
            } else{
                if(partnerStaffDao.getExistsLoginName(loginName)){
                    result.setCode("201");
                    return result;
                }
                User user = new User();
                user.setCreateBy(UserUtils.getUser().getId());
                user.setUserType("a");
                user.setMobile(staffVo.getMobile());
                user.setCreateType(1);
                user.setLoginName(loginName);
                user.setPassword(HashKit.md5(staffVo.getPassword()));
                userDao.save(user);
                emp = new CrmPartnerStaff();
                emp.setName(staffVo.getName());
                emp.setMobile(staffVo.getMobile());
                emp.setPartnerId(partner_id);
                emp.setIsBrowse(staffVo.getIsBrowse());
                emp.setJobNumber(staffVo.getJobNumber());
                emp.setCreateTime(new Date());
                emp.setInductionTime(DateUtils.parseDate(staffVo.getInductionTime()));
                emp.setStatus("1");
                emp.setUserId(user.getId());
                partnerStaffDao.save(emp);
                logger.info("保存CrmTraderEmpile表数据成功："+emp+",saveTime:"+ DateUtils.getDateTime());
                result.setCode("200");
            }
        }catch (Exception e){
            result.setCode("205");
            logger.error("返回异常信息:"+e+",saveTime:"+ DateUtils.getDateTime());
        }
        return result;
    }

    /**
     * 修改员工保存之前进行校验登录账号是否已经存在
     *
     * @param map
     * @return
     */
    public String updateSaveBefore(Map<String, String> map) {
        String id = map.get("id");
        String mess = "0";//正常
        String loginName = map.get("loginName");
        boolean rd = partnerStaffDao.getExistsLoginNameNew(id, loginName);
        if (rd) {
            mess = "1";
        }
        return mess;
    }


    /**
     * 删除员工信息
     *
     * @return
     */
    public Result delEmployee(Map<String, String> params) {
        String id = params.get("id");
        boolean bo = partnerStaffDao.delEmploye(id);
        return bo ? Result.ok(): Result.fail("205","删除失败");
    }

    /**
     * 获取当前服务商id
     *
     * @param userId
     * @return
     */
    public String getPartnerId(String userId) {
        return partnerStaffDao.getPartnerIdByUserId(userId);
    }
}
