package com.gree.mall.manager.logic;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.letter.*;
import com.gree.mall.manager.bean.policy.PolicyOrderVO;
import com.gree.mall.manager.commonmapper.LetterMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.LetterItemStatus;
import com.gree.mall.manager.enums.LetterStatusEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.RedisUtil;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LetterLogic {

    @Autowired
    LetterMapper letterMapper;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    LeDepartmentService leDepartmentService;

    @Autowired
    LeUserDepartmentService leUserDepartmentService;

    @Autowired
    LeConfigService leConfigService;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    AdminWebsitService adminWebsitService;

    @Autowired
    LeProjectService leProjectService;

    @Autowired
    LeLetterService leLetterService;

    @Autowired
    LeLetterItemService leLetterItemService;

    @Autowired
    RedisUtil redisUtil;


    public IPage<LeDepartmentVO> list(Page page, ZfireParamBean zfireParam) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, LeDepartmentVO.class, adminUser);

        IPage<LeDepartmentVO> leDepartmentVOIPage = letterMapper.list(page, zfireParam, adminCompanyIds);
        return leDepartmentVOIPage;
    }

    public LeDepartment detail(String id) {

        LeDepartment leDepartment = leDepartmentService.getById(id);
        return leDepartment;

    }

    public void add(LeDepartment leDepartment) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (leDepartmentService.lambdaQuery().eq(LeDepartment::getDapartment,leDepartment.getDapartment()).count() > 0)
            throw new RemoteServiceException("重复科室名称");

        leDepartment.setCompanyWechatId(adminUser.getCompanyWechatId());
        leDepartment.setCompanyWechatName(adminUser.getCompanyName());
        leDepartment.insert();
    }

    public void update(LeDepartment leDepartment) {
        if (leDepartmentService.lambdaQuery().eq(LeDepartment::getDapartment,leDepartment.getDapartment())
                .ne(LeDepartment::getId,leDepartment.getId()).count() > 0)
            throw new RemoteServiceException("重复科室名称");

        leDepartment.updateById();
    }

    public void del(String id) {

        leDepartmentService.removeById(id);
    }

    public IPage<LeUserDepartmentVO> listUser(Page page, ZfireParamBean zfireParam) {

        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, LeUserDepartmentVO.class, adminUser);

        IPage<LeUserDepartmentVO> leUserDepartmentVOIPage = letterMapper.listUser(page, zfireParam, adminCompanyIds);
        return leUserDepartmentVOIPage;
    }

    public LeUserDepartment detailUser(String id) {
        LeUserDepartment leUserDepartment = leUserDepartmentService.getById(id);
        return leUserDepartment;
    }

    public void addUser(LeUserDepartment leUserDepartment) {

        if (leUserDepartmentService.lambdaQuery().eq(LeUserDepartment::getAdminUserId,leUserDepartment.getAdminUserId())
                .eq(LeUserDepartment::getWebsitId,leUserDepartment.getWebsitId())
                .eq(LeUserDepartment::getDapartmentId,leUserDepartment.getDapartmentId()).count() > 0) {
            throw new RemoteServiceException("该账号设置过科室");
        }

        AdminUserCom adminUser = commonLogic.getAdminUser();

        leUserDepartment.setCompanyWechatName(adminUser.getCompanyName());
        leUserDepartment.setCompanyWechatId(adminUser.getCompanyWechatId());


        leUserDepartment.insert();

    }

    public void updateUser(LeUserDepartment leUserDepartment) {

        if (leUserDepartmentService.lambdaQuery().eq(LeUserDepartment::getAdminUserId,leUserDepartment.getAdminUserId())
                .eq(LeUserDepartment::getWebsitId,leUserDepartment.getWebsitId())
                .eq(LeUserDepartment::getDapartmentId,leUserDepartment.getDapartmentId())
                .ne(LeUserDepartment::getId,leUserDepartment.getId())
                .count() > 0) {
            throw new RemoteServiceException("该账号设置过科室");
        }

        leUserDepartment.updateById();
    }

    public void delUser(String id) {
        leUserDepartmentService.removeById(id);
    }

    public LeConfig configDeatil() {
        if (leConfigService.lambdaQuery().eq(LeConfig::getLeConfigId,"1").count() < 1)
            return new LeConfig();

        return leConfigService.getById("1");
    }

    public void addConfig(LeConfig leConfig) {
        if (leConfigService.lambdaQuery().eq(LeConfig::getLeConfigId,"1").count() < 1) {
            leConfig.setLeConfigId("1");
            leConfig.insert();
        }

        leConfig.setLeConfigId("1");
        leConfig.updateById();
    }

    public void importUser(List<Object> objects) {

        List<LeUserDepartment> leUserDepartments = new ArrayList<>();

        for (Object o : objects) {
            List<Object> row = (List<Object>) o;
            List<AdminUser> adminUsers = adminUserService.lambdaQuery().eq(AdminUser::getUserName, (String) row.get(0)).list();

            if (CollectionUtils.isEmpty(adminUsers))
                throw new RemoteServiceException((String) row.get(0)+"未找到当前账号");

            AdminWebsit adminWebsit = adminWebsitService.getById((String) row.get(1));

            if (adminWebsit == null)
                throw new RemoteServiceException((String) row.get(1)+"未找到当前网点");

            List<LeDepartment> leDepartments = leDepartmentService.lambdaQuery().eq(LeDepartment::getDapartment, (String) row.get(2)).list();

            if (CollectionUtils.isEmpty(leDepartments))
                throw new RemoteServiceException((String) row.get(2)+"未找到当前科室");

            AdminUser adminUser = adminUsers.get(0);

            LeDepartment leDepartment = leDepartments.get(0);

            LeUserDepartment leUserDepartment = new LeUserDepartment();

            leUserDepartment.setAdminUserId(adminUser.getAdminUserId());
            leUserDepartment.setNickName(adminUser.getNickName());
            leUserDepartment.setUserName(adminUser.getUserName());
            leUserDepartment.setDapartment(leDepartment.getDapartment());
            leUserDepartment.setDapartmentId(leDepartment.getId());
            leUserDepartment.setWebsitId(adminWebsit.getWebsitId());
            leUserDepartment.setWebsitName(adminWebsit.getName());
            leUserDepartment.setCompanyWechatId(adminWebsit.getCompanyWechatId());
            leUserDepartment.setCompanyWechatName(adminWebsit.getCompanyWechatName());


            leUserDepartments.add(leUserDepartment);
        }

        leUserDepartmentService.saveBatch(leUserDepartments);
    }

    public IPage<LeProjectVO> listProject(Page page, ZfireParamBean zfireParam) {

        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, LeProjectVO.class, adminUser);

        IPage<LeProjectVO> leProjectVOIPage = letterMapper.listProject(page, zfireParam, adminCompanyIds);
        return leProjectVOIPage;
    }

    public LeProject detailProject(String id) {
        LeProject leProject = leProjectService.getById(id);
        return leProject;
    }

    public void addProject(LeProject leProject) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        leProject.setCompanyWechatName(adminUser.getCompanyName());
        leProject.setCompanyWechatId(adminUser.getCompanyWechatId());

        leProject.insert();
    }

    public void updateProject(LeProject leProject) {
        leProject.updateById();
    }

    public void delProject(String id) {
        leProjectService.removeById(id);
    }

    public IPage<LeLetterVO> listLetter(Page page, ZfireParamBean zfireParam) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();


        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, LeLetterVO.class, adminUser);

        IPage<LeLetterVO> leLetterVOIPage = letterMapper.listLetter(page, zfireParam, adminCompanyIds,
                adminUser.getType().equals(0)?true:false);
        return leLetterVOIPage;

    }

    public LeLetterDetail detailLetter(String id) {
        LeLetter leLetter = leLetterService.getById(id);

        LeLetterDetail leLetterDetail = BeanUtil.toBean(leLetter, LeLetterDetail.class);

        List<LeLetterItem> leLetterItems = leLetterItemService.lambdaQuery().eq(LeLetterItem::getLeLetterId, id).orderByDesc(LeLetterItem::getCreateTime).list();

        leLetterDetail.setLeLetterItems(leLetterItems);

        return leLetterDetail;
    }

    public void addLetter(LeLetter leLetter) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        AdminWebsit adminWebsit = adminWebsitService.getById(leLetter.getWebsitId());

        if (adminWebsit == null)
            throw new RemoteServiceException("网点未配置");

        leLetter.setCompanyWechatName(adminUser.getCompanyName());
        leLetter.setCompanyWechatId(adminUser.getCompanyWechatId());
        leLetter.setBelongCompany(adminWebsit.getBelongCompany());
        leLetter.setBelongCompanyCode(adminWebsit.getBelongCompanyCode());
        if (adminWebsit.getBelongCompanyCode().equals("S9219801"))
            leLetter.setLetterNumber(this.generateInvoiceOrder("GZ"));
        else
            leLetter.setLetterNumber(this.generateInvoiceOrder("FS"));


        if (leLetter.getStatus().equals(LetterStatusEnum.SEND.getKey())){
            leLetter.setSendTime(new Date());
        }else {
            leLetter.setStatus(LetterStatusEnum.WAIT.getKey());
        }


        leLetter.insert();

        leLetter.setLetterNum(leLetterService.lambdaQuery().eq(LeLetter::getBelongCompany,leLetter.getBelongCompany()).count());
        leLetter.setLetteWebsitNum(leLetterService.lambdaQuery().eq(LeLetter::getWebsitId,leLetter.getWebsitId()).count());

        leLetter.updateById();
    }

    /*
     * 产生编号
     * */
    public String generateInvoiceOrder(String websitNumber) {

        //生成订单流水号
        if (websitNumber.equals("GZ")) {
            String yyyyMM = DateUtil.format(new Date(), "yyyy");

            if (redisUtil.get(Constant.RedisPrefix.LETTER_NUMBER + yyyyMM) == null) {
                redisUtil.set(Constant.RedisPrefix.LETTER_NUMBER + yyyyMM, yyyyMM+"00000", 2726560);
            }
            Object water = redisUtil.get(Constant.RedisPrefix.LETTER_NUMBER + yyyyMM);


            Long number = Convert.toLong(water) + 1;
            redisUtil.set(Constant.RedisPrefix.LETTER_NUMBER + yyyyMM, number, 2726560);
            return "GZ"+number;
        }

        String yyyyMM = DateUtil.format(new Date(), "yyyy");

        if (redisUtil.get(Constant.RedisPrefix.LETTER_NUMBER_FS + yyyyMM) == null) {
            redisUtil.set(Constant.RedisPrefix.LETTER_NUMBER_FS + yyyyMM, yyyyMM+"00000", 2726560);
        }
        Object water = redisUtil.get(Constant.RedisPrefix.LETTER_NUMBER_FS + yyyyMM);


        Long number = Convert.toLong(water) + 1;
        redisUtil.set(Constant.RedisPrefix.LETTER_NUMBER + yyyyMM, number, 2726560);
        return "FS"+number;

    }


    public void updateLetter(LeLetter leLetter) {

        if (leLetter.getStatus().equals(LetterStatusEnum.SEND.getKey())){
            leLetter.setSendTime(new Date());
        }
        leLetter.updateById();
    }

    public void delLetter(String id) {
        leLetterService.removeById(id);
    }

    public void send(List<String> ids) {
        if (leLetterService.lambdaQuery().in(LeLetter::getLeLetterId,ids).ne(LeLetter::getStatus,"WAIT").count()>0)
            throw new RemoteServiceException("存在有非待发送的联络函");
        leLetterService.lambdaUpdate().in(LeLetter::getLeLetterId,ids)
                .set(LeLetter::getSendTime,new Date())
                .set(LeLetter::getStatus, LetterStatusEnum.SEND.getKey()).update();

    }

    public void cancel(List<String> ids) {
        if (leLetterService.lambdaQuery().in(LeLetter::getLeLetterId,ids).ne(LeLetter::getStatus,"WAIT").count()>0)
            throw new RemoteServiceException("存在有非待发送的联络函");
        leLetterService.lambdaUpdate().in(LeLetter::getLeLetterId,ids)
                .set(LeLetter::getStatus, LetterStatusEnum.CANCEL.getKey()).update();
    }

    public void reject(List<String> ids) {

        if (leLetterService.lambdaQuery().in(LeLetter::getLeLetterId,ids)
                .in(LeLetter::getStatus,LetterStatusEnum.WAIT.getKey(),LetterStatusEnum.SEND.getKey(),LetterStatusEnum.WAIT_EXAMINE.getKey(),
                        LetterStatusEnum.CANCEL.getKey()).count()>0)
            throw new RemoteServiceException("存在有非审批的联络函");

        leLetterService.lambdaUpdate().in(LeLetter::getLeLetterId,ids)
                .set(LeLetter::getSendTime,new Date())
                .set(LeLetter::getStatus, LetterStatusEnum.SEND.getKey()).update();
    }

    public void appeal(LeLetterItem leLetterItem) {
        LeLetter leLetter = leLetterService.getById(leLetterItem.getLeLetterId());
        if (!leLetter.getStatus().equals(LetterStatusEnum.SEND.getKey()))
            throw new RemoteServiceException("不为待执行不能申诉");

        if (StringUtil.isEmpty(leLetterItem.getWebsitAppeal()))
            throw new RemoteServiceException("网点状态未传");

        leLetter.setStatus(LetterStatusEnum.WAIT_EXAMINE.getKey());
        if (leLetterItem.getWebsitAppeal().equals("OK")){
            leLetter.setStatus(LetterStatusEnum.EXECUTED.getKey());
            leLetter.setExaminePrice(leLetter.getPrice());
            leLetter.setExamineFration(leLetter.getFraction());
        }


        leLetter.updateById();

        leLetterItem.insert();
    }

    public void examine(LeLetterItem leLetterItem) {
        AdminUserCom adminUser = commonLogic.getAdminUser();


        LeLetter leLetter = leLetterService.getById(leLetterItem.getLeLetterId());
        if (!leLetter.getStatus().equals(LetterStatusEnum.WAIT_EXAMINE.getKey()))
            throw new RemoteServiceException("不为待审批状态");
        if (leLetterItem.getExamineStatus().equals(LetterItemStatus.OK.getKey())){
            leLetter.setStatus(LetterStatusEnum.REVOKE.getKey());
        }
        if (leLetterItem.getExamineStatus().equals(LetterItemStatus.FAIL.getKey()))
            leLetter.setStatus(LetterStatusEnum.EXECUTED.getKey());

        if (leLetterItem.getExamineStatus().equals(LetterItemStatus.SUB.getKey()))
            leLetter.setStatus(LetterStatusEnum.REDUCTION.getKey());

        leLetterItem.setExamineName(adminUser.getNickName());
        leLetterItem.setExamineTime(new Date());

        leLetter.setExamineFration(leLetterItem.getExamineFration());
        leLetter.setExamineName(leLetterItem.getExamineName());
        leLetter.setExaminePrice(leLetterItem.getExaminePrice());
        leLetter.setExamineStatus(leLetterItem.getExamineStatus());
        leLetter.setExamineTime(leLetterItem.getExamineTime());
        leLetter.updateById();
        leLetterItem.updateById();
    }

    public void importProject(List<Object> objects) {
        AdminUserCom adminUserCom = commonLogic.getAdminUser();
        List<LeProject> leProjects = new ArrayList<>();

        for (Object o : objects) {
            List<Object> row = (List<Object>) o;

            LeProject leProject = new LeProject();


            leProject.setCompanyWechatId(adminUserCom.getCompanyWechatId());
            leProject.setCompanyWechatName(adminUserCom.getCompanyName());
            leProject.setProjectName((String)row.get(0));
            leProject.setProjectReg((String)row.get(1));
            leProject.setProjectText((String)row.get(2));
            leProject.setPrice(Convert.toBigDecimal(row.get(3)));
            leProject.setFraction(Convert.toBigDecimal(row.get(4)));


            leProjects.add(leProject);
        }

        leProjectService.saveBatch(leProjects);
    }
}
