package com.jpsoft.shinestar.modules.base.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.WorkShiftCompany;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.WorkShiftCompanyService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.base.entity.WorkShiftInfo;
import com.jpsoft.shinestar.modules.base.service.WorkShiftInfoService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/base/workShiftInfo")
public class WorkShiftInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WorkShiftInfoService workShiftInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private WorkShiftCompanyService workShiftCompanyService;

    @Autowired
    private ValueOperations<String,Object> valueOperations;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<WorkShiftInfo> create(){
        MessageResult<WorkShiftInfo> msgResult = new MessageResult<>();

        WorkShiftInfo workShiftInfo = new WorkShiftInfo();

        msgResult.setData(workShiftInfo);
        msgResult.setResult(true);

        return msgResult;
    }


    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<WorkShiftInfo> add(@RequestBody WorkShiftInfo workShiftInfo,@RequestAttribute String subject){
        MessageResult<WorkShiftInfo> msgResult = new MessageResult<>();

        try {
            Date now = new Date();
            workShiftInfo.setId(UUID.randomUUID().toString());
            workShiftInfo.setCreateBy(subject);
            workShiftInfo.setCreateTime(now);
            workShiftInfo.setDelFlag(false);

//            String workTimeRange = workShiftInfo.getWorkTimeRange();
//            String closingTimeRange = workShiftInfo.getClosingTimeRange();
//
//            String[] workTimeArray = workTimeRange.split(",");
//            if(workTimeArray.length == 2){
//                workShiftInfo.setWorkStartTime(workTimeArray[0]);
//                workShiftInfo.setWorkEndTime(workTimeArray[1]);
//            }
//
//            String[] closingTimeArray = closingTimeRange.split(",");
//            if(closingTimeArray.length == 2){
//                workShiftInfo.setClosingStartTime(closingTimeArray[0]);
//                workShiftInfo.setClosingEndTime(closingTimeArray[1]);
//            }

            int affectCount = workShiftInfoService.insert(workShiftInfo);

            if (affectCount > 0) {
                //班次编号存入缓存
                valueOperations.set("shift_number_" + workShiftInfo.getId(), workShiftInfo.getNumber());

                List<CompanyInfo> list = workShiftInfo.getCompanyList();
                int count = workShiftInfoService.updateAndInsert(workShiftInfo,list);

                if(count>0){
                    msgResult.setResult(true);
                    msgResult.setData(workShiftInfo);
                }
                else{
                    msgResult.setResult(false);
                    msgResult.setMessage("数据库添加失败");
                }
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<WorkShiftInfo> edit(@PathVariable("id") String id){
        MessageResult<WorkShiftInfo> msgResult = new MessageResult<>();

        try {
            WorkShiftInfo workShiftInfo = workShiftInfoService.get(id);

            if (workShiftInfo != null) {
                List<WorkShiftCompany> workShiftCompanyList = workShiftCompanyService.findByShiftId(workShiftInfo.getId());

                List<CompanyInfo> companyList = new ArrayList<>();

                for (WorkShiftCompany workShiftCompany:workShiftCompanyList) {
                    CompanyInfo companyInfo = companyInfoService.get(workShiftCompany.getCompanyId());
                    companyList.add(companyInfo);
                }
                workShiftInfo.setCompanyList(companyList);

                msgResult.setResult(true);
                msgResult.setData(workShiftInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<WorkShiftInfo> update(@RequestBody WorkShiftInfo workShiftInfo,@RequestAttribute String subject){
        MessageResult<WorkShiftInfo> msgResult = new MessageResult<>();

        try {
            Date now = new Date();
            workShiftInfo.setUpdateBy(subject);
            workShiftInfo.setUpdateTime(now);

//            String workTimeRange = workShiftInfo.getWorkTimeRange();
//            String closingTimeRange = workShiftInfo.getClosingTimeRange();
//
//            String[] workTimeArray = workTimeRange.split(",");
//            if(workTimeArray.length == 2){
//                workShiftInfo.setWorkStartTime(workTimeArray[0]);
//                workShiftInfo.setWorkEndTime(workTimeArray[1]);
//            }
//
//            String[] closingTimeArray = closingTimeRange.split(",");
//            if(closingTimeArray.length == 2){
//                workShiftInfo.setClosingStartTime(closingTimeArray[0]);
//                workShiftInfo.setClosingEndTime(closingTimeArray[1]);
//            }

            int affectCount = workShiftInfoService.update(workShiftInfo);

            if (affectCount > 0) {
                //班次编号修改后存入缓存
                valueOperations.set("shift_number_" + workShiftInfo.getId(), workShiftInfo.getNumber());

                List<CompanyInfo> list = workShiftInfo.getCompanyList();

                int count = workShiftInfoService.updateAndInsert(workShiftInfo,list);

                if(count>0) {
                    msgResult.setResult(true);
                    msgResult.setData(workShiftInfo);
                }
                else {
                    msgResult.setResult(false);
                    msgResult.setMessage("数据库更新失败");
                }
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="删除用户")
    @PostMapping("delete/{id}")
    public MessageResult<WorkShiftInfo> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<WorkShiftInfo> msgResult = new MessageResult<>();

        try {
            WorkShiftInfo workShiftInfo = workShiftInfoService.get(id);

            workShiftInfo.setDelFlag(true);
            workShiftInfo.setUpdateBy(subject);
            workShiftInfo.setUpdateTime(new Date());

            int affectCount = workShiftInfoService.update(workShiftInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();
        try {
            int affectCount = 0;

            for (String id : idList) {
                WorkShiftInfo workShiftInfo = workShiftInfoService.get(id);
                workShiftInfo.setDelFlag(true);
                workShiftInfo.setUpdateBy(subject);
                workShiftInfo.setUpdateTime(new Date());

                affectCount += workShiftInfoService.update(workShiftInfo);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String name,
            @RequestParam(name="pageIndex",defaultValue = "1") int pageIndex,
            @RequestParam(name="pageSize",defaultValue = "10") int pageSize,
            HttpServletRequest request){
        String subject = (String)request.getAttribute("subject");

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParms = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("CAST( number_ AS SIGNED )","asc"));

        if (StringUtils.isNotEmpty(name)) {
            searchParms.put("name","%" + name + "%");
        }

        Page<WorkShiftInfo> page = workShiftInfoService.pageSearch(searchParms,pageIndex,pageSize,sortList);

        for (WorkShiftInfo workShiftInfo:page) {
            List<WorkShiftCompany> workShiftCompanyList = workShiftCompanyService.findByShiftId(workShiftInfo.getId());

            List<CompanyInfo> companyList = new ArrayList<>();

            for (WorkShiftCompany workShiftCompany:workShiftCompanyList) {
                CompanyInfo companyInfo = companyInfoService.get(workShiftCompany.getCompanyId());
                companyList.add(companyInfo);
            }

            String companyNames = companyList.stream()
                    .map((companyInfo)->companyInfo.getName())
                    .collect(Collectors.joining(","));
            workShiftInfo.setCompanyNames(companyNames);
        }

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="部门班次列表")
    @RequestMapping(value = "shiftList",method = RequestMethod.POST)
    public MessageResult<List> shiftList(
            @RequestParam(name="companyId",defaultValue = "") String companyId,
            HttpServletRequest request){
        MessageResult<List> msgResult = new MessageResult<>();

        if (StringUtils.isNotEmpty(companyId)) {
            //可以查所选单位下面所有的排班 like
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            List<String> parentIds = Arrays.asList(companyInfo.getCode().split(","));
            List<WorkShiftInfo> list = workShiftInfoService.findByCompanyIds(parentIds);
            for(WorkShiftInfo wsi : list){
                if("0".equals(wsi.getNumber())){
                    wsi.setWorkTime("");
                    wsi.setClosingTime("");
                }
            }

            msgResult.setData(list);
        }else{
            msgResult.setData(null);
        }

        msgResult.setResult(true);
        return msgResult;
    }

    @ApiOperation(value="后勤部门班次列表")
    @RequestMapping(value = "shiftHqList",method = RequestMethod.POST)
    public MessageResult<List> shiftHqList(
            @RequestParam(name="companyId",defaultValue = "") String companyId,
            HttpServletRequest request){
        MessageResult<List> msgResult = new MessageResult<>();

        if (StringUtils.isNotEmpty(companyId)) {
            //可以查所选单位下面所有的排班 like
            List<WorkShiftInfo> list = new ArrayList<>();
//            if ("hq1".equals(companyId) || "hq2".equals(companyId)) {
//                //外勤1 0,46,47
//                WorkShiftInfo workShiftInfo0 = workShiftInfoService.findByNumber("0");
//                if(workShiftInfo0 != null) {
//                    workShiftInfo0.setWorkTime("");
//                    workShiftInfo0.setClosingTime("");
//                    list.add(workShiftInfo0);
//                }
//
//                WorkShiftInfo workShiftInfo46 = workShiftInfoService.findByNumber("46");
//                if(workShiftInfo46 != null) {
//                    list.add(workShiftInfo46);
//                }
//
//                WorkShiftInfo workShiftInfo47 = workShiftInfoService.findByNumber("47");
//                if(workShiftInfo47 != null) {
//                    list.add(workShiftInfo47);
//                }
//            }
            if ("hq1".equals(companyId)) {
                CompanyInfo companyInfo = companyInfoService.findByName("后勤1");
                list = workShiftInfoService.findByCompanyId(companyInfo.getId());
                for(WorkShiftInfo wsi : list){
                    if("0".equals(wsi.getNumber())){
                        wsi.setWorkTime("");
                        wsi.setClosingTime("");
                    }
                }
            } else if("hq2".equals(companyId)){
                CompanyInfo companyInfo = companyInfoService.findByName("后勤2");
                list = workShiftInfoService.findByCompanyId(companyInfo.getId());
                for(WorkShiftInfo wsi : list){
                    if("0".equals(wsi.getNumber())){
                        wsi.setWorkTime("");
                        wsi.setClosingTime("");
                    }
                }
            } else {
                CompanyInfo companyInfo = companyInfoService.get(companyId);
                List<String> parentIds = Arrays.asList(companyInfo.getCode().split(","));
                list = workShiftInfoService.findByCompanyIds(parentIds);
                for(WorkShiftInfo wsi : list){
                    if("0".equals(wsi.getNumber())){
                        wsi.setWorkTime("");
                        wsi.setClosingTime("");
                    }
                }
            }



            msgResult.setData(list);
        }else{
            msgResult.setData(null);
        }

        msgResult.setResult(true);
        return msgResult;
    }
}
