package io.renren.modules.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.business.entity.*;
import io.renren.modules.business.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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


/**
 * 计划总结信息
 *
 * @author jiaqiao
 * @email jiaqiao@163.com
 * @date 2022-07-30 22:18:10
 */
@RestController
@RequestMapping("business/businesstotal")
public class BusinessTotalController {
    @Autowired
    private BusinessTotalService businessTotalService;
    @Autowired
    private BusinessPlanService businessPlanService;
    @Autowired
    private BusinessProjectService businessProjectService;
    @Autowired
    private BusinessDictService businessDictService;
    @Autowired
    private BusinessContractService businessContractService;
    @Autowired
    private BusinessWorkerService businessWorkerService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("business:businesstotal:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = businessTotalService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 字典信息列表
     * @param params
     * @return
     */
    @RequestMapping("/dictList")
    @RequiresPermissions("business:businesstotal:list")
    public R dictList(@RequestParam Map<String, Object> params){
        // PageUtils page = businessDictService.queryPage(params);
        List<BusinessDictEntity> businessDictEntitys = businessDictService.listWithTree();
        return R.ok().put("data", businessDictEntitys);
    }

    /**
     * 获取计划中的已经提交的信息
     */
    @RequestMapping("/getWZjList")
    @RequiresPermissions("business:businesstotal:list")
    public R getZjList(@RequestParam Map<String, Object> params){
        PageUtils page = businessPlanService.getWZjList(params);
        //System.out.println(page);
        return R.ok().put("page", page);
    }

    /**
     * 内容复制通过时间 获取符合条件的list
     */
    @RequestMapping("/getListByTime/{time}")
    @RequiresPermissions("business:businesstotal:list")
    public R getTimeList(@PathVariable("time") String time){
        List<BusinessTotalEntity> page = businessTotalService.getListByTime(time);
        return R.ok().put("page", page);
    }

    /**
     * 内容复制通过时间 获取符合条件的list 包括立项 合同 复制信息
     */
    @RequestMapping("/getListByTimeNew/{time}")
    @RequiresPermissions("business:businesstotal:list")
    public R getListByTimeNew(@PathVariable("time") String time){
        Map<String, Object> page = businessTotalService.getListByTimeNew(time);
        return R.ok().put("page", page);
    }

    /**
     * 获取今日总结的总结时间
     */
    @RequestMapping("/getTimeList")
    @RequiresPermissions("business:businesstotal:list")
    public R getTimeList(){
        List<String> page = businessTotalService.getTimeList();
        //System.out.println(page);
        return R.ok().put("page", page);
    }

    /**
     * 获取立项信息
     * @param params
     * @return
     */
    @RequestMapping("/projectList")
    @RequiresPermissions("business:businesstotal:list")
    public R projectList(@RequestParam Map<String, Object> params){
        PageUtils page = businessProjectService.queryPage(params);
        //List<BusinessProjectEntity> page = businessProjectService.quaryListNoPage(params);
        //System.out.println(page);
        return R.ok().put("page", page);
    }

    /**
     * 获取立项统计信息
     */
    @RequestMapping("/getTotal")
    @RequiresPermissions("business:businesstotal:list")
    public R getTotal(@RequestParam Map<String, Object> params){
        //System.out.println(params);
        List<Map<String,Object>> page = businessProjectService.getTotal(params);
        return R.ok().put("page", page);
    }

    /**
     * 获取可分配并且未离职的人员信息列表
     */
    @RequestMapping("/fpWlzList")
    @RequiresPermissions("business:businesstotal:list")
    public R fpWlzList() {
        List<BusinessWorkerEntity> page = businessWorkerService.queryfpWlzList();
        return R.ok().put("page", page);
    }

    /**
     * 列表  所有人员列表 不含有翻页
     */
    @RequestMapping("/tcList")
    @RequiresPermissions("business:businesstotal:list")
    public R tcList(@RequestParam Map<String, Object> params) {
        List<BusinessWorkerEntity> page = businessWorkerService.selectAllContainsDeparture(params);
        return R.ok().put("page", page);
    }

    /**
     * 根据立项id获取立项信息
     */
    @RequestMapping("/projectInfo/{projectId}")
    @RequiresPermissions("business:businesstotal:info")
    public R projectInfo(@PathVariable("projectId") String projectId){
        List<BusinessProjectEntity> businessProject = businessProjectService.queryPerojectList(projectId);
        return R.ok().put("businessProject", businessProject);
    }

    /**
     * 立项负责工人idList
     */
    @RequestMapping("/ddIdList")
    @RequiresPermissions("business:businesstotal:list")
    public R ddIdList(){
        //System.out.println(params);
        List<Integer> ddIdList = businessProjectService.ddIdList();
        return R.ok().put("page", ddIdList);
    }

    /**
     * 根据立项id获取合同信息
     */
    @RequestMapping("/contractInfo/{projectId}")
    @RequiresPermissions("business:businesstotal:info")
    public R contractInfo(@PathVariable("projectId") String projectId){
        Map<String,Object> list = businessContractService.getByProjectId(projectId);
        return R.ok().put("contractList", list);
    }

    /**
     * 根据立项id获取所有的总结列表
     */
    @RequestMapping("/getListByProjectId/{projectId}")
    @RequiresPermissions("business:businesstotal:list")
    public R getListByProjectId(@PathVariable("projectId") String projectId){
        List<BusinessTotalEntity> page = businessTotalService.getListByProjectId(projectId);
        //System.out.println(page);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{totalId}")
    @RequiresPermissions("business:businesstotal:info")
    public R info(@PathVariable("totalId") Integer totalId){
		BusinessTotalEntity businessTotal = businessTotalService.getById(totalId);

        return R.ok().put("businessTotal", businessTotal);
    }

    /**
     * 信息 包含关联信息
     */
    @RequestMapping("/infoNew/{totalId}")
    @RequiresPermissions("business:businesstotal:info")
    public R infoNew(@PathVariable("totalId") Integer totalId){
		BusinessTotalEntity businessTotal = businessTotalService.getByIdNew(totalId);

        return R.ok().put("businessTotal", businessTotal);
    }

    @RequestMapping("/totalList")
    @RequiresPermissions("business:businesstotal:totalList")
    public R totalList(@RequestParam Map<String, Object> params){
        List<BusinessTotalEntity> list  = businessTotalService.totalList(params);
        List<BusinessWorkerEntity> businessWorkerEntityList =  businessWorkerService.selectName();
        // 保存施工人工作时间
        Map<String, Float> workerDay = new HashMap<>();
        // 保存施工计划信息
        Map<Integer, Map<String, Object>> dataDict = new HashMap<>();

        for (BusinessWorkerEntity businessWorkerEntity : businessWorkerEntityList) {
            workerDay.put(businessWorkerEntity.getName(), (float) 0);
        }
        // 循环将相同人的工作时间相加，并将list计划重复的数据去重，之所以有重复数据，是因为和施工人连表查询出现的
        for (BusinessTotalEntity businessTotalEntity : list) {
            // 施工计划
            Map<String, Object> data = new HashMap<>();
            Integer id = businessTotalEntity.getId();

            if(dataDict.containsKey(id)){
                Map<String, Object> entry = dataDict.get(id);
                entry.put("selectPersionId", entry.get("selectPersionId")+","+businessTotalEntity.getSelectPersionId());
                entry.put("selectPersion", entry.get("selectPersion")+businessTotalEntity.getSelectPer()+"-<span style='color:#ff0000'>"+businessTotalEntity.getDay()+"</span><br/>");
            }
            else {
                data.put("totalId", id);
                data.put("planId", businessTotalEntity.getPlanId());
                data.put("project", businessTotalEntity.getProjectNewName());
                data.put("projectId", businessTotalEntity.getTotalProjectId());
                data.put("planSgdd", businessTotalEntity.getSgdd());
                data.put("isOne", businessTotalEntity.getOneDay());
                data.put("isOneDay", businessTotalEntity.getIsOneDay());
                data.put("planFzgz", businessTotalEntity.getFzgz());
                data.put("selectPersionId", businessTotalEntity.getSelectPersionId());
                data.put("selectPersion", businessTotalEntity.getSelectPer()+"-<span style='color:#ff0000'>"+businessTotalEntity.getDay()+"</span><br/>");
                data.put("day", businessTotalEntity.getDay());
                data.put("isFinished", businessTotalEntity.getIsFinished());
                dataDict.put(id, data);
                dataDict.put(businessTotalEntity.getId(), data);
            }

            // 施工人员工作时间
            String worker = businessTotalEntity.getSelectPer();
            if("".equals(worker)||worker ==null){
                continue;
            }
            if(workerDay.containsKey(worker)){
                workerDay.put(worker, workerDay.get(worker) + businessTotalEntity.getDay());
            }
            else {
                workerDay.put(worker, businessTotalEntity.getDay());
            }
        }

        List<Object> dataList = new ArrayList<>();
        for (Object value : dataDict.values()) {
            dataList.add(value);
        }

        // 查询总结表中没有提交立项跟踪的数据
        QueryWrapper<BusinessTotalEntity> qw = new QueryWrapper<>();
        qw.eq("is_finished", 0);
        qw.eq("status", 0);
        // 查询当前类型的所有对应为提交时间
        List<BusinessTotalEntity> planTimeList = businessTotalService.list(qw);
        HashSet<String> planTimes = new HashSet<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (BusinessTotalEntity planTimeEntity: planTimeList) {
            if(planTimeEntity.getPlanTime() != null){
                String format = sdf.format(planTimeEntity.getPlanTime());
                if(!format.equals(params.get("date"))){
                    planTimes.add(format);
                }
            }
        }

        Map<String, Object> res = new HashMap<>();
        res.put("workerDay", workerDay);
        res.put("dataList", dataList);
        res.put("workerIdList", workerDay.keySet());
        res.put("planTimes", planTimes);
        return R.ok().put("page", res);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("business:businesstotal:save")
    public R save(@RequestBody Map<String, Object> data){
        // 计划列表
        List<Map<String, Object>> dataList =  (List<Map<String, Object>>) data.get("dataList");
        List<Integer> planIdList = new ArrayList<>(); // 保存计划id列表

        for (Map<String, Object> businessPlanEntity : dataList) {
            Integer planId = (Integer) businessPlanEntity.get("planId");
            planIdList.add(planId);
        }

        // 根据计划列表id,查询计划实体
        List<BusinessPlanEntity> planEntityList = businessPlanService.listByIds(planIdList);
        // 构造总结表的实体类列表
        List<BusinessTotalEntity> totalEntities = new ArrayList<>();
        for (BusinessPlanEntity businessPlanEntity : planEntityList) {
            // 更新计划表中的是否总结istotal字段
            businessPlanEntity.setIsTotal(1);
            // 构造总结表对象
            BusinessTotalEntity totalEntity = new BusinessTotalEntity();
            totalEntity.setApproval(0);
            totalEntity.setStatus(0);
            totalEntity.setPlanId(businessPlanEntity.getId());
            totalEntity.setIsFinished("0");
            totalEntity.setTotalCl(businessPlanEntity.getPlanCl());
            totalEntity.setTotalSgSummary(businessPlanEntity.getPlanSgSummary());
            totalEntity.setTotalJx(businessPlanEntity.getPlanJx());
            totalEntity.setIsOneDay(businessPlanEntity.getIsOneDay());
            totalEntity.setTotalProjectId(businessPlanEntity.getPlanProjectId());
            totalEntity.setSelectPersionId(businessPlanEntity.getSelectPersionId());
            totalEntity.setTotalPersonNum(businessPlanEntity.getPlanPersonNum());
            totalEntity.setPlanTime(businessPlanEntity.getPlanTime());
            totalEntity.setTotalDate(new Date());
            totalEntities.add(totalEntity);
        }
        // 批量更新计划表中istotal字段
        businessPlanService.saveOrUpdateBatch(planEntityList);
        // 批量插入总结数据
		businessTotalService.saveBatch(totalEntities);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("business:businesstotal:update")
    public R update(@RequestBody BusinessTotalEntity businessTotal){
		businessTotalService.updateById(businessTotal);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/updatebatch")
    @RequiresPermissions("business:businesstotal:updatebatch")
    public R updatebatch(@RequestBody  Map<String, Object> data){
        List<Map<String, Object>> dataList =  (List<Map<String, Object>>) data.get("dataList");
        List<BusinessTotalEntity> totalEntityList = new ArrayList<>(); // 保存修改总结的实体类列表
        List<BusinessPlanEntity> planEntityList = new ArrayList<>(); // 保存修改计划的实体类列表

        String isFinished = (String) data.get("isFinished");
        Integer status = (Integer) data.get("status");

        for (Map<String, Object> businessTotalEntity : dataList) {
            Integer totalId = (Integer) businessTotalEntity.get("totalId");
            Integer planId = (Integer) businessTotalEntity.get("planId");

            BusinessTotalEntity totalEntity =  new BusinessTotalEntity();
            // 如果status是1 则是总结最终成稿向总结未成稿回退 总结表数据删除，计划表数据将istotal设置为0
            if(status != null && status == 1){
                BusinessPlanEntity planEntity =  new BusinessPlanEntity();
                planEntity.setId(planId);
                planEntity.setIsTotal(0);
                planEntityList.add(planEntity);

                totalEntity.setStatus(1);
            }
            totalEntity.setId(totalId);
            totalEntity.setIsFinished(isFinished);
            totalEntityList.add(totalEntity);
        }

        // 更新计划表
        businessPlanService.updateBatchById(planEntityList);
        // 更新总结表
        businessTotalService.updateBatchById(totalEntityList);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("business:businesstotal:delete")
    public R delete(@RequestBody Integer[] totalIds){
		businessTotalService.removeByIds(Arrays.asList(totalIds));

        return R.ok();
    }

    /**
     * 未提交列表
     * @return
     */
    @RequestMapping("/uncommittedList")
    @RequiresPermissions("business:businesstotal:list")
    public R uncommittedList(){
        List<BusinessTotalEntity> list = businessTotalService.getUncommittedList();
        return R.ok().put("page", list);
    }

}
