package com.goafanti.order.service.impl;

import com.goafanti.admin.service.DepartmentService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.model.TDunLog;
import com.goafanti.common.model.TOrderLegalAffairs;
import com.goafanti.common.model.TOrderMid;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.*;
import com.goafanti.order.enums.NewProjectStatus;
import com.goafanti.order.service.LegalAffairsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LegalAffairsServiceImpl extends BaseMybatisDao<TOrderMidMapper> implements LegalAffairsService {
    @Autowired
    private TOrderMidMapper tOrderMidMapper;
    @Autowired
    private TOrderTaskMapper    tOrderTaskMapper;
    @Autowired
    private TDunLogMapper tDunLogMapper;
    @Autowired
    private TOrderLegalAffairsMapper tOrderLegalAffairsMapper;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private AdminMapper adminMapper;
    @Value(value = "${upload.path}")
    private String uploadPath = null;




    @Override
    public  int pushTransferLagalAffairs(String orderNo,String remarks){
        TOrderMid tm = new TOrderMid();
        tm.setOrderNo(orderNo);
        tm.setLegalAffairs(1);
        tm.setLegalAffairsType(0);
        tm.setLegalAffairsStatus(0);
        InputOrderLegalAffairs in=new InputOrderLegalAffairs();
        in.setOrderNo(orderNo);
        in.setRemarks(remarks);
        in.setType(4);
        addLagalAffairsLog(in);
        return tOrderMidMapper.updateByOrderNo(tm);
    }

    @Override
    public Object orderListPage(InputOrderListBo in) {
        HashMap<String, Object> params = new HashMap<>();
        addParams(in, params);
        Pagination<OutOrderLegalAffairsListBo>  p= (Pagination<OutOrderLegalAffairsListBo>) findPage("legalAffairsOrderList","legalAffairsOrderCount",params,in.getPageNo(),in.getPageSize());
        List<OutOrderLegalAffairsListBo> list = (List<OutOrderLegalAffairsListBo>) p.getList();
        if(in.getType()==0){
            sumDaysRemaining(list);
        }
        return p;
    }

    private void addParams(InputOrderListBo in, HashMap<String, Object> map) {
        if(in.getContractNo()!=null) map.put("contractNo", in.getContractNo());
        if(in.getLegalAffairs()!=null) map.put("legalAffairs", in.getLegalAffairs());
        if(in.getAid()!=null) map.put("aid", in.getAid());
        if(in.getType()==0){
            if (TokenManager.hasRole(AFTConstants.FINANCE)){
                map.put("shiro",1);
                List<String> deps=adminMapper.getFinanceDep(TokenManager.getAdminId());
                if (in.getDeps()==null){
                    map.put("deps",deps);
                }else {
                    map.put("deps",departmentService.selectSubDeps(deps));
                }
            }else if(TokenManager.hasRole(AFTConstants.SALESMAN_MANAGER)){
                map.put("shiro",2);
                map.put("sid", TokenManager.getAdminId());
            }else if(TokenManager.hasRole(AFTConstants.SUPERADMIN)||TokenManager.hasRole(AFTConstants.CED)||
                    TokenManager.hasRole(AFTConstants.CED_ASSISTANT)||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)||
                    TokenManager.hasRole(AFTConstants.VICE_CEO)){
                map.put("shiro",3);
            }else {
                map.put("shiro",0);
                if(TokenManager.getAdminId()!=null)map.put("aid", TokenManager.getAdminId());
            }
            map.put("type", in.getType());
        }else{
            if(in.getAid()!=null) map.put("aid", in.getAid());
            if (in.getStatus()!=null) map.put("status",in.getStatus());
            map.put("type", in.getType());

        }
        if (!TokenManager.hasRole(AFTConstants.FINANCE)){
            if(in.getDeps()!=null){
                map.put("deps", departmentService.parseArray(in.getDeps()));
            }
        }
        if(in.getUserName()!=null) map.put("userName", in.getUserName());
        if(in.getStartTime()!=null)map.put("startTime", in.getStartTime());
        if(in.getEndTime()!=null)map.put("endTime", in.getEndTime()+" 23:59:59");
    }

    private void sumDaysRemaining(List<OutOrderLegalAffairsListBo> list) {
        Date date = new Date();
        for (OutOrderLegalAffairsListBo out : list) {
            if (out.getLegalAffairs()==0){
                if (out.getDunStartTime()!=null){
                    long start=out.getDunStartTime().getTime()+AFTConstants.DUN_START_LIMIT_MS;
                    int i= (int) ((start-date.getTime())/(3600*24*1000));
                    out.setDaysRemaining(i);
                }else {
                    out.setDaysRemaining(0);
                }
            }else {
                out.setDaysRemaining(0);
            }

        }
    }

    @Override
    public List<OutOrderLegalAffairsListBo> getLegalAffairsOrder(InputOrderListBo in) {
        HashMap<String, Object> params = new HashMap<>();
        addParams(in,params);
        List<OutOrderLegalAffairsListBo> list =(List<OutOrderLegalAffairsListBo>) findList("legalAffairsOrderList",params,1,999999);
        sumDaysRemaining(list);
        return list;
    }

    @Override
    public boolean checkTask(String orderNo) {
        List<TOrderTaskBo> list =tOrderTaskMapper.selectOrderTask(orderNo,0);
        for (TOrderTaskBo bo : list) {
            if (bo.getType()==5&&bo.getProjectStatus()!= NewProjectStatus.YXZ.getCode()){
                return true;
            }
        }
        return false;
    }

    @Override
    public List<TDunLogListBo> dunOrderList(String orderNo) {
        return tDunLogMapper.selectByOrderNo(orderNo);
    }

    @Override
    public int addDunOrder(InputDunOrder in) {
        TDunLog log = new TDunLog();
        log.setOrderNo(in.getOrderNo());
        log.setId(UUID.randomUUID().toString());
        log.setType(1);
        log.setRemarks(in.getRemarks());
        log.setAttachmentUrl(in.getAttUrl());
        log.setDumBy(TokenManager.getAdminId());
        log.setDumTime(DateUtils.StringToDate(in.getDate(),AFTConstants.YYYYMMDD));
        return tDunLogMapper.insertSelective(log);
    }

    @Override
    public int addLagalAffairsLog(InputOrderLegalAffairs in) {
        TOrderLegalAffairs la = new TOrderLegalAffairs();
        la.setOrderNo(in.getOrderNo());
        la.setRemarks(in.getRemarks());
        la.setType(in.getType());
        la.setStatus(in.getStatus());
        la.setAttachmentUrl(in.getAttachmentUrl());
        la.setAid(TokenManager.getAdminId());
        if(in.getDate()!=null)la.setOperationTime(DateUtils.StringToDate(in.getDate(),AFTConstants.YYYYMMDD));
        TOrderMid tm = new TOrderMid();
        tm.setOrderNo(in.getOrderNo());
        tm.setLegalAffairsType(in.getType());
        tm.setOperationTime(la.getOperationTime());
        tm.setLegalAffairsStatus(in.getStatus());
        tOrderMidMapper.updateByOrderNo(tm);
        return tOrderLegalAffairsMapper.insertSelective(la);
    }

    @Override
    public List<OutLegalAffairsLogBo> lagalAffairsLogList(String orderNo) {
        return tOrderLegalAffairsMapper.lagalAffairsLogList(orderNo);
    }

    @Override
    public Result orderListExprot(InputOrderListBo in) {
        List<OutOrderLegalAffairsListBo> use = getLegalAffairsOrder(in);
        NewExcelUtil newExcelUtil;
        List<Object> list=new ArrayList<>();
        String tile= new String();
        if (in.getType()==0){
            for (OutOrderLegalAffairsListBo out : use) {
                OutOrderLegalAffairsSalesmanBo bo = new OutOrderLegalAffairsSalesmanBo();
                BeanUtils.copyProperties(out,bo);
                list.add(bo);
            }
            newExcelUtil=new NewExcelUtil<>(OutOrderLegalAffairsSalesmanBo.class);
            tile="订单催款列表";
        }else {
            for (OutOrderLegalAffairsListBo out : use) {
                OutOrderLegalAffairsBo bo = new OutOrderLegalAffairsBo();
                BeanUtils.copyProperties(out,bo);
                list.add(bo);
            }
            newExcelUtil=new NewExcelUtil<>(OutOrderLegalAffairsBo.class);
            if(in.getType()==1){tile="法务催款列表";}
            else if(in.getType()==2){tile="延期法务列表";}
            else if(in.getType()==3){tile="已完成法务列表";}
        }
        StringBuffer sb=new StringBuffer("搜索条件=》");
        if (in.getUserName()!=null)sb=sb.append("客户名称：").append(in.getUserName()).append(",");
        if (in.getLegalAffairs()!=null)sb=sb.append("转交法务：").append(in.getLegalAffairs()==0?"未转交":"已转交").append(",");
        if (in.getContractNo()!=null)sb=sb.append("合同编号：").append(in.getContractNo()).append(",");
        if (in.getDepName()!=null)sb=sb.append("订单部门：").append(in.getDepName()).append(",");
        if (in.getaName()!=null)sb=sb.append("营销员：").append(in.getaName()).append(",");
        if (in.getStartTime()!=null&&in.getEndTime()!=null){
            if (in.getType()==0)sb=sb.append("催款启动时间：");
            if (in.getType()==1||in.getType()==2||in.getType()==3)sb=sb.append("法务时间：");
            sb=sb.append(in.getStartTime()).append("~").append(in.getEndTime()).append(",");
        }
        if(in.getStatus()!=null){
            sb=sb.append("完成状态：");
            if (in.getStatus()==1)sb=sb.append("已回款").append(",");
            else if (in.getStatus()==2)sb=sb.append("已诉讼").append(",");
            else if (in.getStatus()==3)sb=sb.append("已坏账处理").append(",");
        }
        return newExcelUtil.exportExcel(list,tile,uploadPath,sb.substring(0,sb.length()-1));
    }

    @Override
    public void addLagalAffairsLogList(List<String> addList2) {
        tOrderLegalAffairsMapper.insertBatch(addList2);
    }
}
