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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.business.dao.BusinessWorkerCqDao;
import io.renren.modules.business.entity.BusinessWorkerCqEntity;
import io.renren.modules.business.service.BusinessWorkerCqService;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("businessWorkerCqService")
public class BusinessWorkerCqServiceImpl extends ServiceImpl<BusinessWorkerCqDao, BusinessWorkerCqEntity> implements BusinessWorkerCqService {

    @Autowired
    SysUserDao sysUserDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        IPage<BusinessWorkerCqEntity> page = this.page(
//                new Query<BusinessWorkerCqEntity>().getPage(params),
//                new QueryWrapper<BusinessWorkerCqEntity>()
//        );
        IPage<BusinessWorkerCqEntity> page = new Query<BusinessWorkerCqEntity>().getPage(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 startTime = "1999-01-01";
        String endTime = "9999-12-31";
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        List<BusinessWorkerCqEntity> list = baseMapper.querySearchList(params);
        if(list.size() > 0) {
            Map<String, BigDecimal> timeMap = new HashMap<>();
            List<Map<String, Object>> workerTimeList = baseMapper.queryWorkerTimeList(userId,startTime,endTime);
            if(workerTimeList.size() > 0) {
                for(Map<String, Object> tmp : workerTimeList) {
                    timeMap.put(tmp.get("total_date")+"", new BigDecimal(tmp.get("cnt")+""));
                }
            }
            for(BusinessWorkerCqEntity tmp : list) {
                if(tmp.getDateDay() != null) {
                    String tmpDateDayStr = DateUtils.format(tmp.getDateDay(), "yyyy-MM");
                    if(timeMap.containsKey(tmpDateDayStr)) {
                        tmp.setStatusDay(timeMap.get(tmpDateDayStr).toString());
                    }
                    // 状态+修正
                    BigDecimal statusBg = BigDecimal.ZERO;
                    if(StringUtils.isNotBlank(tmp.getStatusDay())) {
                        statusBg = new BigDecimal(tmp.getStatusDay());
                    }
                    BigDecimal fixBg = BigDecimal.ZERO;
                    if(StringUtils.isNotBlank(tmp.getFixDay())) {
                        fixBg = new BigDecimal(tmp.getFixDay());
                    }
                    tmp.setOutWorkDay(statusBg.add(fixBg).toString());
                }
            }
        }
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public List<BusinessWorkerCqEntity> querySearchList(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 startTime = "1999-01-01";
        String endTime = "9999-12-31";
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        List<BusinessWorkerCqEntity> list = baseMapper.querySearchList(params);
        if(list.size() > 0) {
            Map<String, BigDecimal> timeMap = new HashMap<>();
            // 查询人员施工时间
            // 按人和时间，查business_total  的total_date和isfinished，再用plan_id查的表
            List<Map<String, Object>> workerTimeList = baseMapper.queryWorkerTimeList(userId,startTime,endTime);
            if(workerTimeList.size() > 0) {
                for(Map<String, Object> tmp : workerTimeList) {
                    timeMap.put(tmp.get("total_date")+"", new BigDecimal(tmp.get("cnt")+""));
                }
            }
            for(BusinessWorkerCqEntity tmp : list) {
                if(tmp.getDateDay() != null) {
                    String tmpDateDayStr = DateUtils.format(tmp.getDateDay(), "yyyy-MM");
                    if(timeMap.containsKey(tmpDateDayStr)) {
                        tmp.setStatusDay(timeMap.get(tmpDateDayStr).toString());
                    }
                    // 状态+修正
                    BigDecimal statusBg = BigDecimal.ZERO;
                    if(StringUtils.isNotBlank(tmp.getStatusDay())) {
                        statusBg = new BigDecimal(tmp.getStatusDay());
                    }
                    BigDecimal fixBg = BigDecimal.ZERO;
                    if(StringUtils.isNotBlank(tmp.getFixDay())) {
                        fixBg = new BigDecimal(tmp.getFixDay());
                    }
                    tmp.setOutWorkDay(statusBg.add(fixBg).toString());
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> querySearchListAll(Map<String, Object> params) {
        String type = params.get("type").toString();
        List<Map<String,Object>> list = baseMapper.querySearchListAll(params.get("date").toString());

        List<Map<String, Object>> resultList = new ArrayList<>();

        list.forEach(item->{
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userId",item.get("user_id"));
            resultMap.put("name",item.get("name"));
            resultMap.put("status",item.get("status"));
            resultMap.put("workerDay",item.get("worker_day"));
            resultMap.put("fixDay",item.get("fix_day"));
            resultMap.put("id",item.get("cq_id"));
            resultMap.put("remark",item.get("remark"));

            // 2代表修正数据，也就是说在出勤表中有数据,1代表未修正数据
//            if("2".equals(type) && !Objects.isNull(item.get("cq_id"))){
//                // 状态+修正
//                BigDecimal statusBg = BigDecimal.ZERO;
//                if(item.get("worker_day")!=null) {
//                    statusBg = new BigDecimal(item.get("worker_day").toString());
//                }
//
//                BigDecimal fixBg = BigDecimal.ZERO;
//                if(item.get("fix_day")!=null) {
//                    fixBg = new BigDecimal(item.get("fix_day").toString());
//                }
//
//                resultMap.put("outWorkDay",statusBg.add(fixBg));
//                resultList.add(resultMap);
//            }
//            else if("1".equals(type) && Objects.isNull(item.get("cq_id"))) {
//                resultList.add(resultMap);
//            }

//            if("2".equals(type) && (!Objects.isNull(item.get("cq_id")) || !Objects.isNull(item.get("worker_day")) || ("150".equals(item.get("relevance_id").toString()) && "0".equals(item.get("status").toString())))){
//                // 状态+修正
//                BigDecimal statusBg = BigDecimal.ZERO;
//                if(item.get("worker_day")!=null) {
//                    statusBg = new BigDecimal(item.get("worker_day").toString());
//                }
//
//                BigDecimal fixBg = BigDecimal.ZERO;
//                if(item.get("fix_day")!=null) {
//                    if(!"".equals(item.get("fix_day").toString().trim())){
//                        fixBg = new BigDecimal(item.get("fix_day").toString());
//                    }
//                }
//
//                resultMap.put("outWorkDay",statusBg.add(fixBg));
//                resultList.add(resultMap);
//            }
//            else if("1".equals(type) && Objects.isNull(item.get("cq_id")) && Objects.isNull(item.get("worker_day")) && !"150".equals(item.get("relevance_id").toString())  ) {
//                resultList.add(resultMap);
//            }

            if("2".equals(type)){
                boolean xz = false;
                if(!Objects.isNull(item.get("cq_id"))){
                    xz = true;
                }
                if(!Objects.isNull(item.get("worker_day"))){
                    xz = true;
                }
                if("150".equals(item.get("relevance_id").toString()) && "0".equals(item.get("status").toString())){
                    xz = true;
                }
                if(xz){
                    // 状态+修正
                    BigDecimal statusBg = BigDecimal.ZERO;
                    if(item.get("worker_day")!=null) {
                        statusBg = new BigDecimal(item.get("worker_day").toString());
                    }

                    BigDecimal fixBg = BigDecimal.ZERO;
                    if(item.get("fix_day")!=null) {
                        if(!"".equals(item.get("fix_day").toString().trim())){
                            fixBg = new BigDecimal(item.get("fix_day").toString());
                        }
                    }
                    resultMap.put("outWorkDay",statusBg.add(fixBg));
                    resultList.add(resultMap);
                }
            }else if("1".equals(type)){
                boolean wxz = false;
                if(Objects.isNull(item.get("cq_id")) && Objects.isNull(item.get("worker_day"))){
                    wxz = true;
                }else{
                    wxz = false;
                }
                if(wxz){
                    if("150".equals(item.get("relevance_id").toString())){
                        if("0".equals(item.get("status").toString())){
                            wxz = false;
                        }
                    }
                }
                if(wxz){
                    resultList.add(resultMap);
                }
            }
        });
        return resultList;
    }
    /**
     * 获取出勤记录信息
     * @param params
     * @return
     */
    @Override
    public List<BusinessWorkerCqEntity> cqjlList(Map<String, Object> params) {
        String startTime = params.get("year") + "-02-01";
        String endTime = (Integer.parseInt((String) params.get("year")) + 1) + "-03-01";
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        //获取用户侯吉光的登录id
        //人员信息列表
        List<SysUserEntity> ry = sysUserDao.sysUserlist();
        for(SysUserEntity sysUser : ry){
            if(sysUser.getAuthenticName().equals("侯吉光")){
                params.put("sysUserId",sysUser.getUserId());
            }
        }
        return baseMapper.cqjlList(params);
    }

    @Override
    public PageUtils cqjlPage(Map<String, Object> params){
        String startTime = params.get("year") + "-03-01";
        String endTime = (Integer.parseInt((String) params.get("year")) + 1) + "-02-01";
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        //获取用户侯吉光的登录id
        //人员信息列表
        List<SysUserEntity> ry = sysUserDao.sysUserlist();
        for(SysUserEntity sysUser : ry){
            if(sysUser.getAuthenticName().equals("侯吉光")){
                params.put("sysUserId",sysUser.getUserId());
            }
        }
        IPage<BusinessWorkerCqEntity> page = new Query<BusinessWorkerCqEntity>().getPage(params);
        List<BusinessWorkerCqEntity> list = baseMapper.cqjlList(params);
        page.setRecords(list);
        return new PageUtils(page);
    }

}