package io.renren.modules.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.commons.lang.StringUtils;
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-28 16:45:01
 */
@RestController
@RequestMapping("business/businessplan")
public class BusinessPlanController {
    @Autowired
    private BusinessPlanService businessPlanService;
    @Autowired
    private BusinessDictService businessDictService;
    @Autowired
    private BusinessProjectService businessProjectService;
    @Autowired
    private BusinessWorkerService businessWorkerService;
    @Autowired
    private BusinessContractService businessContractService;
    @Autowired
    private BusinessPlanWorkerService businessPlanWorkerService;
    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("business:businessplan:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = businessPlanService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 获取提前计划的数据
     */
    @RequestMapping("/uncommitPlan")
    @RequiresPermissions("business:businessplan:uncommitPlan")
    public R uncommitPlan(@RequestParam Map<String, Object> params){
        List<BusinessPlanEntity> list = businessPlanService.uncommitPlan(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 (BusinessPlanEntity businessPlanEntity : list) {
            // 施工计划
            Map<String, Object> data = new HashMap<>();
            Integer id = businessPlanEntity.getId();

            if(dataDict.containsKey(id)){
                Map<String, Object> entry = dataDict.get(id);
                entry.put("selectPersionId", entry.get("selectPersionId")+","+businessPlanEntity.getSelectPersionId());
                entry.put("selectPersion", entry.get("selectPersion")+businessPlanEntity.getSelectPer()+"-<span style='color:#ff0000'>"+businessPlanEntity.getDay()+"</span><br/>");
            }
            else {
                data.put("planId", id);
                data.put("type", businessPlanEntity.getType());
                data.put("projectNewName", businessPlanEntity.getProjectNewName());
                data.put("projectId", businessPlanEntity.getPlanProjectId());
                data.put("planSgdd", businessPlanEntity.getSgdd());
                data.put("isOne", businessPlanEntity.getOneDay());
                data.put("isOneDay", businessPlanEntity.getIsOneDay());
                data.put("planFzgz", businessPlanEntity.getFzgz());
                data.put("selectPersionId", businessPlanEntity.getSelectPersionId());
                data.put("selectPersion", businessPlanEntity.getSelectPer()+"-<span style='color:#ff0000'>"+businessPlanEntity.getDay()+"</span><br/>");
                data.put("day", businessPlanEntity.getDay());
                data.put("commit", "1");
                dataDict.put(id, data);
            }

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

        List<Object> dataList = new ArrayList<>();
        for (Object value : dataDict.values()) {
            dataList.add(value);
        }
        // 当前日期对应的类型，用类型获取当前类型所对应的未提交数据日期
//        Integer type = 2;
//        // 说明是总结请求
//        if(params.get("isTotal") != null || (list.size()!=0 && list.get(0).getType()==0)){
//            type = 0;
//        }
//        QueryWrapper<BusinessPlanEntity> qw = new QueryWrapper<>();
//        qw.eq("type", type);

        QueryWrapper<BusinessPlanEntity> qw = new QueryWrapper<>();
        // 说明是总结请求
        if(params.get("isTotal") != null){
            //总结-未成稿
            qw.eq("type", 1);
            qw.eq("is_total", params.get("isTotal"));
        }else{
            //计划-未总结
            qw.eq("type", 0);
        }


        // 查询当前类型的所有对应为提交时间
        List<BusinessPlanEntity> planTimeList = businessPlanService.list(qw);
        HashSet<String> planTimes = new HashSet<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (BusinessPlanEntity 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);
    }

    /**
     * 获取字典信息
     * @param params
     * @return
     */
    @RequestMapping("/dictList")
    @RequiresPermissions("business:businessplan: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("/projectAllList")
    @RequiresPermissions("business:businessplan:list")
    public R allList(){
        //System.out.println(params);
        List<BusinessProjectEntity> page = businessProjectService.allList();
        return R.ok().put("page", page);
    }

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

    /**
     * 总结功能中类表查询
     */
    @RequestMapping("/newList")
    @RequiresPermissions("business:businessplan:list")
    public R newList(@RequestParam Map<String, Object> params){
        PageUtils page = businessPlanService.queryNewPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 所有list不含分页带有排序
     */
    @RequestMapping("/selectAll")
    @RequiresPermissions("business:businessplan:list")
    public R selectAll(@RequestParam Map<String, Object> params){
        PageUtils page = businessPlanService.selectAll(params);
        //System.out.println(page);
        return R.ok().put("page", page);
    }

    /**
     * 计划综述通过时间 获取符合条件的list
     */
    @RequestMapping("/getListByTime/{time}")
    @RequiresPermissions("business:businessplan:list")
    public R getTimeList(@PathVariable("time") String time){
        List<BusinessPlanEntity> page = businessPlanService.getListByTime(time);
        //System.out.println(page);
        return R.ok().put("page", page);
    }

    /**
     * 计划综述通过时间 获取符合条件的list  包含对应的所有的立项信息和所有的合同信息   以及小程序前端数据展示的信息
     */
    @RequestMapping("/getListByTimeNew/{time}")
    @RequiresPermissions("business:businessplan:list")
    public R getTimeListNew(@PathVariable("time") String time){
        Map<String, Object> page = businessPlanService.getListByTimeNew(time);
        //System.out.println(page);
        return R.ok().put("page", page);
    }

    /**
     * 获取已有计划的计划时间（未删除，未提交）
     */
    @RequestMapping("/getTimeList")
    @RequiresPermissions("business:businessplan:list")
    public R getTimeList(){
        List<BusinessPlanEntity> page = businessPlanService.getTimeList();
        //System.out.println(page);
        return R.ok().put("page", page);
    }

    /**
     * 根据传入的计划时间对人员进行处理
     */
    @RequestMapping("/getNewRyList/{time}")
    @RequiresPermissions("business:businessplan:list")
    public R getNewRyList(@PathVariable("time") String time){
        List<BusinessWorkerEntity> page = businessPlanService.getNewRyList(time);
        //System.out.println(page);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{planId}")
    @RequiresPermissions("business:businessplan:info")
    public R info(@PathVariable("planId") Integer planId){
		BusinessPlanEntity businessPlan = businessPlanService.getById(planId);
        return R.ok().put("businessPlan", businessPlan);
    }

    /**
     * 新信息带有管理信息
     */
    @RequestMapping("/infoNew/{planId}")
    @RequiresPermissions("business:businessplan:info")
    public R infoNew(@PathVariable("planId") Integer planId){
		BusinessPlanEntity businessPlan = businessPlanService.getInfoNew(planId);
        return R.ok().put("businessPlan", businessPlan);
    }

    /**
     * 获取立项信息列表
     */
    @RequestMapping("/projectList")
    @RequiresPermissions("business:businessplan: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:businessplan: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("/tcList")
    @RequiresPermissions("business:businessplan:list")
    public R tcList(@RequestParam Map<String, Object> params) {
        List<BusinessWorkerEntity> page = businessWorkerService.queryNewPage(params);
        return R.ok().put("page", page);
    }

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

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

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

    /**
     * 根据立项id 获取 立项 合同  明日计划信息穿入 一个立项id
     */
    @RequestMapping("/lxHtPlanInfo/{projectId}")
    @RequiresPermissions("business:businessplan:info")
    public R lxHtPlanInfo(@PathVariable("projectId") String projectId){
        Map<String,Object> list = businessPlanService.lxHtPlanInfo(projectId);
        return R.ok().put("list", list);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("business:businessplan:save")
    public R save(@RequestBody BusinessPlanEntity businessPlan){
        Integer planId = businessPlan.getId();
        // 查询当前数据的对象, 如果有数据说明是修改，否则是新增,新增直接添加
        BusinessPlanEntity plan = businessPlanService.getById(planId);
        if(plan == null){
            plan = new BusinessPlanEntity();
            plan.setStatus(0);
            businessPlanService.save(plan);
        }

        // 无论添加还是修改 都需要设置其他属性
        plan.setPlanProjectId(businessPlan.getPlanProjectId());
        plan.setIsOneDay(businessPlan.getIsOneDay());
        plan.setPlanTime(businessPlan.getPlanTime());
        plan.setPlanCl(businessPlan.getPlanCl());
        plan.setPlanJx(businessPlan.getPlanJx());
        plan.setPlanSgSummary(businessPlan.getPlanSgSummary());
        plan.setStatus(0);
        plan.setType(2);
        plan.setIsTotal(0);

        // 如果为空，说明没有修改施工人员，则不需要对计划员工表进行操作
        if(businessPlan.getSelectUser() != null){
            planId =  plan.getId();
            // 处理施工人数据
            UpdateWrapper<BusinessPlanWorkerEntity> wq = new UpdateWrapper<>();
            wq.eq("plan_id", planId);
            List<BusinessPlanWorkerEntity> list = businessPlanWorkerService.list(wq);

            List<BusinessPlanWorkerEntity> planWorkerList = new ArrayList<>();
            String[] selectIds = new String[0];
            if(StringUtils.isNotBlank(plan.getSelectPersionId())){
                selectIds = plan.getSelectPersionId().substring(1).split(",");
            }
//            String[] selectIds = plan.getSelectPersionId().substring(1).split(",");
            ArrayList< String> selectPersionId = new ArrayList<String>(selectIds.length);
            Collections.addAll(selectPersionId, selectIds);
            for (Integer key : businessPlan.getSelectUser().keySet()) {
                if(list.size() == 0){
                    selectPersionId.add(String.valueOf(key));
                    // 构造计划施工人对象
                    BusinessPlanWorkerEntity planWorker = new BusinessPlanWorkerEntity();
                    planWorker.setPlanId(planId);
                    planWorker.setPersionId(key);
                    planWorker.setPersionName((String) businessPlan.getSelectUser().get(key).get("name"));
                    planWorker.setDay(Double.parseDouble((String) businessPlan.getSelectUser().get(key).get("day")));
                    planWorkerList.add(planWorker);
                }else {
                    for (BusinessPlanWorkerEntity businessPlanWorkerEntity : list) {
                        //判断天数为加
                        if (businessPlanWorkerEntity.getPersionId().equals(businessPlan.getSelectUser().get(key).get("userId"))
                                && businessPlan.getSelectUser().get(key).get("addOrSubtract").equals("+"))
                        {
                            businessPlanWorkerEntity.setDay(Double.parseDouble((String) businessPlan.getSelectUser().get(key).get("day")));
                            businessPlanWorkerService.updateById(businessPlanWorkerEntity);
                        }else if(businessPlanWorkerEntity.getPersionId()!= businessPlan.getSelectUser().get(key).get("userId")
                                && businessPlan.getSelectUser().get(key).get("addOrSubtract").equals("+")){
                            //用户是否已存在
                            boolean contains = selectPersionId.contains(String.valueOf(key));
                            if(!contains) {
                                selectPersionId.add(String.valueOf(key));
                                // 构造计划施工人对象
                                BusinessPlanWorkerEntity planWorker = new BusinessPlanWorkerEntity();
                                planWorker.setPlanId(planId);
                                planWorker.setPersionId(key);
                                planWorker.setPersionName((String) businessPlan.getSelectUser().get(key).get("name"));
                                planWorker.setDay(Double.parseDouble((String) businessPlan.getSelectUser().get(key).get("day")));
                                planWorkerList.add(planWorker);
                            }
                        }
                        //判断天数为减
                        if (businessPlanWorkerEntity.getPersionId().equals(businessPlan.getSelectUser().get(key).get("userId"))
                                && businessPlan.getSelectUser().get(key).get("addOrSubtract").equals("-"))
                        {
                            if (Double.parseDouble((String) businessPlan.getSelectUser().get(key).get("day"))<=0){
                                businessPlanWorkerService.removeById(businessPlanWorkerEntity);
                                //用户是否已存在
                                boolean contains = selectPersionId.contains(String.valueOf(key));
                                if(contains) {
                                    selectPersionId.remove(String.valueOf(key));
                                }
                            }
                            businessPlanWorkerEntity.setDay(Double.parseDouble((String) businessPlan.getSelectUser().get(key).get("day")));
                            businessPlanWorkerService.updateById(businessPlanWorkerEntity);
                        }
                    }
                }

            }
            // 将计划的施工工人添加到数据库中
            businessPlanWorkerService.saveBatch(planWorkerList);

            String persionId = "";
            for (String id : selectPersionId) {
                persionId += "," + id;
            }
            plan.setPlanPersonNum(selectPersionId.size());
            plan.setSelectPersionId(persionId);
        }

        plan.setCreateTime(new Date());
        plan.setUpdateTime(new Date());
        businessPlanService.saveOrUpdate(plan);

        return R.ok().put("data", plan);
    }

    /**
     *获取天数
     */
    @RequestMapping("/selectDay")
    @RequiresPermissions("business:businessplan:list")
    public R selectDay(@RequestParam Map<String, Object> params){
		QueryWrapper<BusinessPlanWorkerEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("plan_id",params.get("id"));
		List<BusinessPlanWorkerEntity> businessPlanWorker = businessPlanWorkerService.list(wrapper);
        Map<String, Object> map = new HashMap<>();
        for (BusinessPlanWorkerEntity planWorker : businessPlanWorker) {
            map.put(planWorker.getPersionName(),planWorker.getDay());
        }
		return R.ok().put("data", map);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("business:businessplan:update")
    public R update(@RequestBody Map<String, Object> data){
        List<Map<String, Object>> dataList =  (List<Map<String, Object>>) data.get("dataList");
        List<Integer> planIdList = new ArrayList<>(); // 保存计划id列表
        List<BusinessPlanEntity> planEntityList = new ArrayList<>(); // 保存修改计划的实体类列表

        Integer type = (Integer) data.get("type");
        Integer isTotal = (Integer) data.get("isTotal");

        for (Map<String, Object> businessPlanEntity : dataList) {
            Integer planId = (Integer) businessPlanEntity.get("planId");
            planIdList.add(planId);
            BusinessPlanEntity planEntity =  new BusinessPlanEntity();
            // isTotal 如果不为null 则证明是总结向计划表返回为未总结
            if(isTotal!=null){
                planEntity.setIsTotal(isTotal);
            }
            planEntity.setId(planId);
            planEntity.setType(type);
            planEntityList.add(planEntity);
        }

        //如需要在提交时必须有施工人，应将注释去掉 type 0-已提交 2-未提交 1-已总结  功能修改此功能暂时作废
//        if(type==0){
//            for (Integer planId : planIdList) {
//                UpdateWrapper<BusinessPlanWorkerEntity> wq = new UpdateWrapper<BusinessPlanWorkerEntity>();
//                wq.eq("plan_id", planId);
//                if(businessPlanWorkerService.list(wq).stream().count()==0){
//                    // 计划没有选择施工工人直接返回
//                    return R.error(1, "请将所有明日计划添加【施工人】");
//                }
//            }
//
//        }


        businessPlanService.updateBatchById(planEntityList);

        return R.ok();
    }
    /**
     * 修改
     */
    @RequestMapping("/updateInfo")
    @RequiresPermissions("business:businessplan:updateInfo")
    public R updateInfo(@RequestBody BusinessPlanEntity businessPlanEntity){

        businessPlanService.updateById(businessPlanEntity);

        return R.ok();
    }
    /**
     * 修改
     */
    @RequestMapping("/sjUpdate")
    @RequiresPermissions("business:businessplan:sjUpdate")
    public R sjUpdate(@RequestBody BusinessPlanEntity businessPlan){
        businessPlan.setUpdateTime(new Date());
		businessPlanService.updateById(businessPlan);

        return R.ok();
    }

    /**
     * 删除
     */
    /*@RequestMapping("/delete")
    @RequiresPermissions("business:businessplan:delete")
    public R delete(@RequestBody String params){
        JSONObject jsonObject = JSONObject.parseObject(params);
		businessPlanService.removeByIds(Arrays.asList(jsonObject.getString("planIds")));

        return R.ok();
    }*/
    @RequestMapping("/delete")
    @RequiresPermissions("business:businessplan:delete")
    public R delete(@RequestBody Integer[] projectIds){
        businessPlanService.removeByIds(Arrays.asList(projectIds));

        return R.ok();
    }

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

}
