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

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderEmployeDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTraderEmploye;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.RandomUtil;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
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.dao.UserDao;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class TraderEmployeService extends BaseService {
    @Autowired
    private TraderEmployeDao traderEmployeDao;

    @Autowired
    UserDao userDao;


    public CrmTraderEmploye findByUserId(String userId) {
        return traderEmployeDao.findByUserId(userId);
    }

    public CrmTraderEmploye getById(String id) {
        return traderEmployeDao.get(id);
    }

    /**
     * 获取服务商员工设置列表数据
     *
     * @return
     */
    public List<Record> getTaderEmployeData(Map<String, String> map, String traderId) {
        List<Record> memberRds = traderEmployeDao.getTaderEmployeData(map, traderId);
        return memberRds;
    }

    public String getPageData(LayuiPage page, Map<String, String> map,  String traderId) {
        page.setData(traderEmployeDao.findPageData(page, map, traderId));
        page.setCount(traderEmployeDao.findPageCount(map, traderId));
        return page.renderJson();
    }

    /**
     * 小程序派工获取服务商员工列表
     * @param map
     * @param traderId
     * @return
     */
    public List<Record> getTraderEmployeDataList(Map<String, String> map, String traderId) {
        List<Record> memberRds = traderEmployeDao.getTaderEmployeData(map, traderId);
        String sql = "select count(1) from crm_customer_entry a where  FIND_IN_SET(?,a.engineer_id) and install_flag in('2','3') and a.status in('4','f')";
        for (Record re : memberRds) {
            re.set("sta_count", Db.queryLong(sql, re.getStr("id")));
        }
        return memberRds;
    }

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


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


    /**
     * 保存工程师
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveTraderEmploye(Map<String, String> map) {
        User users = UserUtils.getUser();
        String id = map.get("id") != null ? map.get("id") : "";
        String name = map.get("name") != null ? map.get("name") : "";
        String loginName = map.get("loginName") != null ? map.get("loginName").trim() : "";
        String password = map.get("password") != null ? map.get("password") : "";
      //  String traderId = getTraderId(users.getId());
        String traderId ;
        if(User.USER_TYPE_ADVISOR.equals(users.getUserType())){
            CrmTraderEmploye emp =findByUserId(users.getId());
            traderId= emp.getTraderId();
        }else{
            traderId= getTraderId(users.getId());
        }
        String mobile = map.get("mobile") != null ? map.get("mobile") : "";
        String job_number = map.get("jobNumber") != null ? map.get("jobNumber") : "";
        String hiredate = map.get("hiredate") != null ? map.get("hiredate") : "";
        String roleId = map.get("roleId") != null ? map.get("roleId") : "";
        String roleName = map.get("roleName") != null ? map.get("roleName") : "";
        String idCard = map.get("idCard") != null ? map.get("idCard") : "";
        String hgImgs = map.get("hgImgs") != null ? map.get("hgImgs") : "";
        String dydgimgs = map.get("dydgImgs") != null ? map.get("dydgImgs") : "";
        List<Record> list = traderEmployeDao.getEmpByName(name, traderId);
        CrmTraderEmploye emp;
        if (StringUtil.isNotBlank(id)) {
            emp = traderEmployeDao.get(id);
            User user = userDao.get(emp.getUserId());
            if (traderEmployeDao.getExistsLoginNameNew(user.getId(), loginName)) {
                throw new BusinessException("该登录账号已存在!");
            }
            user.setLoginName(loginName);
            if (!password.equals("default")) {
                String passwords = RandomUtil.entryptPassword(password);
                if (!user.getPassword().equals(passwords)) {
                    user.setPassword(passwords);
                }
            }
            user.setMobile(mobile);
            userDao.save(user);
            emp.setName(name);
            emp.setMobile(mobile);
            emp.setJobNumber(job_number);
            emp.setHiredate(DateUtils.parseDate(hiredate));
            emp.setRoleId(roleId);
            emp.setRoleName(roleName);
            emp.setIdCard(idCard);
            emp.setHgImgs(hgImgs);
            emp.setDydgImgs(dydgimgs);
            traderEmployeDao.save(emp);
            logger.info("保存Crmsite表数据成功：" + emp + ",saveTime:" + DateUtils.getDateTime());
        } else {
            if (traderEmployeDao.getExistsLoginName(loginName)) {
                throw new BusinessException("该登录账号已存在!");
            }
            User user = new User();
            user.setCreateBy(UserUtils.getUser().getId());
            user.setUserType(UserConstants.TYPE_JXS_EMP);
            user.setMobile(mobile);
            user.setCreateType(1);
            user.setLoginName(loginName);
            user.setPassword(RandomUtil.entryptPassword(password));
            userDao.save(user);
            emp = new CrmTraderEmploye();
            emp.setCreateBy(UserUtils.getUser().getId());
            emp.setName(name);
            emp.setMobile(mobile);
            emp.setTraderId(traderId);
            emp.setJobNumber(job_number);
            emp.setHiredate(DateUtils.parseDate(hiredate));
            emp.setUserId(user.getId());
            emp.setRoleId(roleId);
            emp.setRoleName(roleName);
            emp.setIdCard(idCard);
            emp.setHgImgs(hgImgs);
            emp.setDydgImgs(dydgimgs);
            emp.setParentId(users.getTopTraderId());
            traderEmployeDao.save(emp);
            logger.info("保存CrmTraderEmpile表数据成功：" + emp + ",saveTime:" + DateUtils.getDateTime());
        }

    }

    /**
     * 修改员工保存之前进行校验登录账号是否已经存在
     *
     * @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 = traderEmployeDao.getExistsLoginNameNew(id, loginName);
        if (rd) {
            mess = "1";
        }
        return mess;
    }


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

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

    /**
     * 保存设置的数据权限
     */
    public int  saveTraderRights(String id,String dataAuthority){
        logger.info("saveTraderRights id:{},dataAuthority:{}" ,id,dataAuthority);
        return Db.update(" UPDATE `crm_trader_employe` SET data_authority=? WHERE id=? ",dataAuthority,id);
    }

}
