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

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectSettingDao;
import com.sifang.modules.sunshine.SystemSetting.dao.SiteInformationDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.RandomUtil;
import com.sifang.modules.sunshine.partnerManagement.dao.PartnerDao;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.sunshine.partnerManagement.form.AddPartnerReq;
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.dao.UserDao;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class PartnerService extends BaseService {
    @Autowired
    private PartnerDao partnerDao;
    @Autowired
    private ProjectSettingDao projectSettingDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SiteInformationDao siteInformationDao;

    public CrmPartner getById(String id) {
        return partnerDao.get(id);
    }

    public List<Record> getPartnerByIds(String ids) {
        return partnerDao.getPartnerByIds(ids);
    }



    public CrmPartner findByUserId(String userId) {
        return partnerDao.findByUserId(userId);
    }


    public LayuiPage<Record> getPartnerPage(LayuiPage<Record> page, Map<String, String> map) {
        page.setData(partnerDao.listPartner(page, map));
        page.setCount(partnerDao.countPartner(map));
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addPartner(AddPartnerReq req) {
        checkBeforeSave(req);
        if (siteInformationDao.getExistsLoginName(req.getLoginName())) {
            throw new BusinessException("登录账号已存在！");
        }
        User user = createUser(req);
        userDao.save(user);
        CrmPartner partner = new CrmPartner();
        setBaseColumns(partner, req);
        partner.setStatus(SourceConstants.ZERO);
        partner.setUserId(user.getId());
        partner.setCreateBy(UserUtils.getUser().getId());
        partner.setCreateTime(new Date());
        partner.setCreator(CrmUtils.getUserXM(UserUtils.getUser()));
        partnerDao.save(partner);
    }

    @Transactional(rollbackFor = Exception.class)
    public void editPartner(AddPartnerReq req) {
        checkBeforeSave(req);
        CrmPartner partner = partnerDao.get(req.getId());
        checkPartner(partner);
        if (siteInformationDao.getExistsLoginNameNew(partner.getUserId(), req.getLoginName())) {
            throw new BusinessException("登录账号已存在！");
        }
        setBaseColumns(partner, req);
        partner.setUpdateBy(UserUtils.getUser().getCreateBy());
        partner.setUpdateName(CrmUtils.getUserXM(UserUtils.getUser()));
        partner.setUpdateTime(new Date());
        partnerDao.save(partner);
        User user = userDao.getById(partner.getUserId());
        user.setMobile(req.getMobile());
        user.setLoginName(req.getLoginName());
        if (!req.getPassword().equals("default")) {
            user.setPassword(RandomUtil.entryptPassword(req.getPassword()));
        }
        userDao.save(user);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deletePartner(String id) {
        CrmPartner partner = partnerDao.get(id);
        checkPartner(partner);
        partner.setStatus(SourceConstants.ONE);
        User user = UserUtils.getUser();
        partner.setUpdateTime(new Date());
        partner.setUpdateBy(user.getId());
        partner.setUpdateName(CrmUtils.getUserXM(user));
        partnerDao.save(partner);
        User partnerUser = userDao.getById(partner.getUserId());
        partnerUser.setStatus(SourceConstants.ONE);
        partnerUser.setUpdateTime(new Date());
        userDao.save(partnerUser);
    }

    private void setBaseColumns(CrmPartner partner, AddPartnerReq req) {
        partner.setName(req.getName());
        partner.setAuthorizedId(req.getAuthorizedId());
        partner.setMobile(req.getMobile());
        partner.setPersonInCharge(req.getPersonInCharge());
        partner.setLogo(req.getLogo());
        partner.setProvince(req.getProvince());
        partner.setCity(req.getCity());
        partner.setArea(req.getArea());
        partner.setAddress(req.getAddress());
    }

    private User createUser(AddPartnerReq req) {
        User user = new User();
        user.setCreateBy(UserUtils.getUser().getId());
        user.setStatus(UserConstants.USER_STATUS_NORMAL);
        user.setUserType(UserConstants.TYPE_TEAM);
        user.setCreateType(1);
        user.setMobile(req.getMobile());
        user.setCreateDate(new Date());
        user.setLoginName(req.getLoginName());
        user.setPassword(RandomUtil.entryptPassword(req.getPassword()));
        return user;
    }

    public void checkBeforeSave(AddPartnerReq req) {
        StringBuilder sb = new StringBuilder();
        sb.append("select count(*) from crm_partner p where p.status = '0' and p.name = ?");
        if (StrKit.notBlank(req.getId())) {
            sb.append("and p.id  <> '").append(req.getId()).append("'");
        }
        long count = Db.queryLong(sb.toString(), req.getName());
        if (count > 0) {
            throw new BusinessException("合作商名称已存在");
        }
        String[] authorizedId = req.getAuthorizedId().split(",");
        for (String s : authorizedId) {
            CrmProjectSetting project = projectSettingDao.get(s);
            if (!StrKit.notNull(project)) {
                throw new BusinessException("项目不存在");
            }
            if (UserConstants.STATUS_USE.equals(project.getStatus())) {
                throw new BusinessException("项目" + project.getCode() + "已删除");
            }
        }
    }

    private void checkPartner(CrmPartner partner) {
        if (!StrKit.notNull(partner)) {
            throw new BusinessException("合作商不存在");
        }
        if (UserConstants.STATUS_USE.equals(partner.getStatus())) {
            throw new BusinessException("合作商已删除");
        }
    }

    /**
     * 查询资方列表【前端选择器】
     */
    public List<CrmPartner> getAllForChoose() {
        return partnerDao.findAllForChoose();
    }

    public List<Record> partnerList(){
        return partnerDao.partnerList();
    }

    /**
     * 获取可选择的资方列表
     */
    public List<Map> getCapital(){
        List<Record> records = partnerList();
        List<Map> list=new ArrayList<>();
        for(Record rd:records){
            Map map=new HashMap();
            map.put("id",rd.get("id"));
            map.put("name",rd.get("person_in_charge"));
            list.add(map);
        }
        return list;
    }

    //转换合同签署模式（华融）
    public void changePatternType(String partnerId,String newPattern){
        User user = UserUtils.getUser();
        SQLQuery sqlQuery= partnerDao.getSession().createSQLQuery(" UPDATE `crm_partner` SET if_sign_contract=:newPattern,update_time=:updateTime,update_by=:updateBy,update_name=:updateName WHERE id=:id ");
        sqlQuery.setParameter("id", partnerId);
        sqlQuery.setParameter("newPattern", newPattern);
        sqlQuery.setParameter("updateTime",new Date());
        sqlQuery.setParameter("updateBy",user.getId());
        sqlQuery.setParameter("updateName",user.getUserName());
        int cou = sqlQuery.executeUpdate();
        if (cou < 1) {
            throw new IllegalArgumentException("转换合同签署模式失败");
        }
    }
}
