package io.renren.modules.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.business.dao.*;
import io.renren.modules.business.entity.*;
import io.renren.modules.business.service.BusinessApprovalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("businessApprovalService")
public class BusinessApprovalServiceImpl extends ServiceImpl<BusinessApprovalDao, BusinessApprovalEntity> implements BusinessApprovalService {

    @Autowired
    BusinessWorkerDao businessWorkerDao;//人员
    @Autowired
    BusinessWorkerCqDao businessWorkerCqDao;//出勤
    @Autowired
    BusinessWorkerSalaryDao businessWorkerSalaryDao;//工资账目
    @Autowired
    BusinessProjectDao businessProjectDao;//立项
    @Autowired
    BusinessContractDao businessContractDao;//合同
    @Autowired
    BusinessSsjdexcelDao businessSsjdexcelDao;//送审进度
    @Autowired
    BusinessSsjdexcelServiceImpl businessSsjdexcelService;//送审进度
    @Autowired
    BusinessTotalDao businessTotalDao;//今日总结
    @Autowired
    BusinessOutlayDao businessOutlayDao;//支出明细
    @Autowired
    BusinessOutlayIncomeDao businessOutlayIncomeDao;//收支总结
    @Autowired
    BusinessMoneyDao businessMoneyDao;//基础工资

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BusinessApprovalEntity> page = this.page(
                new Query<BusinessApprovalEntity>().getPage(params),
                new QueryWrapper<BusinessApprovalEntity>().orderByDesc("id")
        );

        return new PageUtils(page);
    }

    @Override
    public List<BusinessApprovalEntity> queryNewPage(Map<String, Object> params) {
        return baseMapper.selectAll();
    }

    @Override
    public List<BusinessApprovalEntity> querySonList(Integer approvalFatherId) {
        return baseMapper.querySonList(approvalFatherId);
    }

    //获取出勤记录
    @Override
    public List<BusinessApprovalEntity> queryCQList(Map<String, Object> params) {
        String userId = (String) params.get("userId");
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = formatter.format(date);
        int year = Integer.parseInt(nowDate.substring(0, 4));
        String month = nowDate.substring(5, 7);
        String startTime = null;
        String endTime = null;
        if (!month.equals("01") && !month.equals("02")) {
            startTime = year + "-03-01";
            endTime = (year + 1) + "-02-01";
        } else {
            startTime = (year - 1) + "-03-01";
            endTime = year + "-02-01";
        }
        /*System.out.println(startTime);
        System.out.println(endTime);*/
        return baseMapper.queryCQList(userId, startTime, endTime);
    }

    /**
     * 审批通过处理  需要 传入  新的实体的所有数据字段，对应审批的id，
     *
     * @param params
     */
    @Override
    public void pass(Map<String, Object> params) {
        System.out.println(params);
        System.out.println(params.get("approvalData"));
        System.out.println(params.get("approvalType"));
        if (params.get("approvalData") != null) {
            //先对审批表中对应的数据进行处理
            BusinessApprovalEntity businessApprovalFatherEntity = new BusinessApprovalEntity();
            System.out.println(params);
            businessApprovalFatherEntity.setId(Integer.parseInt(params.get("id").toString()));
            businessApprovalFatherEntity.setApprovalSuccess(1);
            baseMapper.updateById(businessApprovalFatherEntity);
            if (params.get("approvalType").toString().equals("0")) {//人员管理
                BusinessWorkerEntity businessWorkerEntity = JSON.parseObject(params.get("approvalData").toString(), BusinessWorkerEntity.class);
                if (businessWorkerEntity.getPositionId() == 151 || businessWorkerEntity.getPositionId() == 152) {//处理改变之后的数据如果工人的位置改成外部人员2或者现场施工则人员变为可分配
                    businessWorkerEntity.setIsFp(0);
                } else {
                    businessWorkerEntity.setIsFp(1);
                }
                businessWorkerDao.updateById(businessWorkerEntity);
            } else if (params.get("approvalType").toString().equals("1")) {//人员出勤  传入的数据为数组 相当于出勤实体放入    中的approvalId是对应的审批表中的数据
                String[] cq = params.get("approvalData").toString().split("},");
                for (int i = 0; i < cq.length; i++) {
                    //BusinessCqTran是一个中间转换实体
                    BusinessCqTran businessCqTran = new BusinessCqTran();
                     if (i + 1 != cq.length) {
                        businessCqTran = JSON.parseObject(cq[i] + "}", BusinessCqTran.class);//split把}祛除了 在这里需要加上
                        //System.out.println(businessCqTran);
                    } else {
                        businessCqTran = JSON.parseObject(cq[i], BusinessCqTran.class);
                        //System.out.println(businessCqTran);
                    }
                    BusinessApprovalEntity businessApprovalEntity = new BusinessApprovalEntity();
                    businessApprovalEntity.setId(businessCqTran.getApprovalId());
                    businessApprovalEntity.setApprovalSuccess(1);
                    baseMapper.updateById(businessApprovalEntity);
                    BusinessWorkerCqEntity b = new BusinessWorkerCqEntity();
                    b.setId(businessCqTran.getId());//Id
                    b.setUserId(businessCqTran.getUserId());
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-ss");
                    String date = businessCqTran.getDateDay() + "-01";
                    try {
                        b.setDateDay(formatter.parse(date));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    b.setWorkDay(businessCqTran.getWorkDay());
                    b.setRemark(businessCqTran.getRemark());
                    b.setApproval(0);
                    businessWorkerCqDao.updateById(b);
                    //System.out.println(b);
                }
            } else if (params.get("approvalType").toString().equals("2")) {//工资账目    不管是关联的工资账目还是  单个的工资账目进入此都为 数组形式存入的是审批表中的这条数据
                String[] gzzm = params.get("approvalData").toString().split("},");
                for (int i = 0; i < gzzm.length; i++) {
                    //传入的数据解析成实体
                    BusinessApprovalEntity businessApprovalEntity = new BusinessApprovalEntity();
                    if (i + 1 != gzzm.length) {
                        businessApprovalEntity = JSON.parseObject(gzzm[i] + "}", BusinessApprovalEntity.class);
                    } else {
                        businessApprovalEntity = JSON.parseObject(gzzm[i], BusinessApprovalEntity.class);
                    }
                    //更新数以map形式更新  处理下
                    BusinessApprovalEntity bus = new BusinessApprovalEntity();
                    businessApprovalEntity.setId(businessApprovalEntity.getId());
                    businessApprovalEntity.setApprovalSuccess(1);
                    baseMapper.updateById(businessApprovalEntity);
                    //将审批表中的新的数据从JSON装换成对应的实体
//                    BusinessWorkerSalaryEntity salaryEntity = JSON.parseObject(businessApprovalEntity.getApprovalData(), BusinessWorkerSalaryEntity.class);
                    BusinessWorkerSalaryEntity salaryEntity = JSON.parseObject(params.get("approvalData").toString(), BusinessWorkerSalaryEntity.class);
                    salaryEntity.setApproval(0);
                    businessWorkerSalaryDao.updateById(salaryEntity);
                }
            } else if (params.get("approvalType").toString().equals("3")) {//立项管理
                BusinessProjectEntity businessProjectEntity = JSON.parseObject(params.get("approvalData").toString(), BusinessProjectEntity.class);
                businessProjectDao.updateById(businessProjectEntity);
            } else if (params.get("approvalType").toString().equals("4")) {//合同管理
                BusinessContractEntity businessContractEntity = JSON.parseObject(params.get("approvalData").toString(), BusinessContractEntity.class);
                businessContractEntity.setApproval(0);
                businessContractDao.newUpdateById(businessContractEntity);

                //修改关联立项导入合同
                BusinessContractEntity businessContractEntityOld = JSON.parseObject(params.get("approvalOldData").toString(), BusinessContractEntity.class);
                String projectOldIds = businessContractEntityOld.getProjectId();
                if(projectOldIds!=null && !projectOldIds.equals(""))
                {
                    String[] pOldIds = projectOldIds.split(",");
                    System.out.println(pOldIds);
                    businessProjectDao.channelState(pOldIds);
                }
                String projectIds = businessContractEntity.getProjectId();
                if(projectIds!=null && !projectIds.equals(""))
                {
                    String[] pIds = projectIds.split(",");
                    System.out.println(pIds);
                    businessProjectDao.changeState(pIds);
                }
                //对于合同管理中的送审进度的处理
                if (params.get("approvalExcel") != null) {
                    BusinessSsjdexcelEntity businessSsjdexcelEntity = JSON.parseObject(params.get("approvalExcel").toString(), BusinessSsjdexcelEntity.class);
                    System.out.println(businessSsjdexcelEntity);
                    if (businessSsjdexcelEntity.getId() == null || businessSsjdexcelEntity.getId().toString().equals("") || businessSsjdexcelEntity.getId().toString().equals("undefined")) {
                        businessSsjdexcelEntity.setExcelContractMoneyNew(businessSsjdexcelEntity.getExcelContractMoney());
                        businessSsjdexcelService.save(businessSsjdexcelEntity);
                    } else {
                        if(businessSsjdexcelEntity.getExcelContractMoney() != null) {
                            businessSsjdexcelEntity.setExcelContractMoney(null);
                        }
                        businessSsjdexcelDao.updateById(businessSsjdexcelEntity);
                    }
                }
            } else if (params.get("approvalType").toString().equals("5")) {//今日总结
                BusinessTotalEntity businessTotalEntity = JSON.parseObject(params.get("approvalData").toString(), BusinessTotalEntity.class);
                businessTotalDao.updateById(businessTotalEntity);
            } else if (params.get("approvalType").toString().equals("6")) {//支出明细
                BusinessOutlayEntity businessOutlayEntity = JSON.parseObject(params.get("approvalData").toString(), BusinessOutlayEntity.class);
                businessOutlayDao.updateById(businessOutlayEntity);
            } else if (params.get("approvalType").toString().equals("7")) {//收支总结
                BusinessOutlayIncomeEntity businessOutlayIncomeEntity = JSON.parseObject(params.get("approvalData").toString(), BusinessOutlayIncomeEntity.class);
                businessOutlayIncomeDao.updateById(businessOutlayIncomeEntity);
            }else if (params.get("approvalType").toString().equals("8")) {//基础工资
                BusinessMoneyEntity businessMoneyEntity = JSON.parseObject(params.get("approvalData").toString(), BusinessMoneyEntity.class);
                businessMoneyDao.updateById(businessMoneyEntity);
            }else if (params.get("approvalType").toString().equals("88")) {//新的今日总结
                String day = params.get("approvalData").toString();
                Map<String, Object> totalMap = new HashMap<>();
                totalMap.put("isFinished", "0");
                totalMap.put("day", day);
                businessTotalDao.updateTotalAuditNew(totalMap);
            }
        }
    }

    /**
     * 审批不通过处理
     *
     * @param params
     */
    @Override
    public void noPass(Map<String, Object> params) {
        baseMapper.noPass(params.get("id").toString());
        if (params.get("approvalType").toString().equals("0")) {//员工
            businessWorkerDao.newUpdateById(params.get("approvalId").toString());
        } else if (params.get("approvalType").toString().equals("1")) {//出勤
            businessWorkerCqDao.updateNoPassByIds(params.get("approvalId").toString());
        } else if (params.get("approvalType").toString().equals("2")) {//工资账目
            businessWorkerSalaryDao.updateNoPassByIds(params.get("approvalId").toString());
        } else if (params.get("approvalType").toString().equals("3")) {//立项管理
            System.out.println(params.get("approvalId").toString());
            businessProjectDao.updateNoPassByIds(params.get("approvalId").toString());
        } else if (params.get("approvalType").toString().equals("4")) {//合同管理  送审进度 一对一  相当于合同在审批 送审进度在审批
            businessContractDao.updateNoPassByIds(params.get("approvalId").toString());
        } else if (params.get("approvalType").toString().equals("5")) {//今日总结
            businessTotalDao.updateNoPassByIds(params.get("approvalId").toString());
        } else if (params.get("approvalType").toString().equals("6")) {//支出明细
            businessOutlayDao.updateNoPassByIds(params.get("approvalId").toString());
        } else if (params.get("approvalType").toString().equals("7")) {//收支总结
            businessOutlayIncomeDao.updateNoPassByIds(params.get("approvalId").toString());
        }
        else if (params.get("approvalType").toString().equals("8")) {//基础工资
            businessMoneyDao.updateNoPassByIds(params.get("approvalId").toString());
        }else if (params.get("approvalType").toString().equals("88")) {//新的今日总结
            String day = params.get("approvalData").toString();
            Map<String, Object> totalMap = new HashMap<>();
            totalMap.put("isFinished", "1");
            totalMap.put("day", day);
            businessTotalDao.updateTotalAuditNew(totalMap);
        }
    }

    /**
     * 根据id 获取立项信息  合同信息
     * @param projectId
     * @return
     */
    @Override
    public Map<String, Object> getProjectConInfo(Integer projectId) {
        //建立map   为了信息整合 传到前端
        Map<String, Object> map = new HashMap<>();
        //对应的立项信息
        BusinessProjectEntity proList = businessProjectDao.projectInfo(projectId);
        //建立合同   以防多个合同
        List<BusinessContractEntity> contract = businessContractDao.getByProjectId(projectId.toString());
        map.put("proList",proList);
        map.put("contract",contract);
        return map;
    }

    /**
     * 根据id 获取工资账目或者出勤记录信息
     * @param id
     * @return
     */
    @Override
    public BusinessApprovalEntity getCqOrGzInfo(Integer id) {
        return baseMapper.getCqOrGzInfo(id);
    }
}