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

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.google.gson.JsonObject;
import com.jpsoft.shinestar.modules.base.dto.CanteenInfoDTO;
import com.jpsoft.shinestar.modules.base.entity.CanteenDining;
import com.jpsoft.shinestar.modules.base.service.CanteenDiningService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.base.entity.CanteenInfo;
import com.jpsoft.shinestar.modules.base.service.CanteenInfoService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/base/canteenInfo")
@Api(description = "食堂信息")
public class CanteenInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CanteenInfoService canteenInfoService;

    @Autowired
    private CanteenDiningService canteenDiningService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

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

        try {
            CanteenInfo canteenInfo = new CanteenInfo();

            canteenInfo.setId(UUID.randomUUID().toString());
            canteenInfo.setName(canteenInfoDTO.getName());
            canteenInfo.setAddress(canteenInfoDTO.getAddress());
            canteenInfo.setCreateBy(subject);
            canteenInfo.setCreateTime(new Date());
            canteenInfo.setDelFlag(false);

            int affectCount = canteenInfoService.insert(canteenInfo);

            if (affectCount > 0) {

                if(StringUtils.isNotEmpty(canteenInfoDTO.getDiningTimeRange1())){
                    String diningTimeRange1 = canteenInfoDTO.getDiningTimeRange1();
                    String diningTime1 = arrToString(diningTimeRange1);

                    saveCanteenDining(canteenInfo.getId(),subject,"1",diningTime1,canteenInfoDTO.getOutsourcerDiningFee1());
                }

                if(StringUtils.isNotEmpty(canteenInfoDTO.getDiningTimeRange2())){
                    String diningTimeRange2 = canteenInfoDTO.getDiningTimeRange2();
                    String diningTime2 = arrToString(diningTimeRange2);

                    saveCanteenDining(canteenInfo.getId(),subject,"2",diningTime2,canteenInfoDTO.getOutsourcerDiningFee2());
                }

                if(StringUtils.isNotEmpty(canteenInfoDTO.getDiningTimeRange3())){
                    String diningTimeRange3 = canteenInfoDTO.getDiningTimeRange3();
                    String diningTime3 = arrToString(diningTimeRange3);

                    saveCanteenDining(canteenInfo.getId(),subject,"3",diningTime3,canteenInfoDTO.getOutsourcerDiningFee3());
                }

                if(StringUtils.isNotEmpty(canteenInfoDTO.getDiningTimeRange4())){
                    String diningTimeRange4 = canteenInfoDTO.getDiningTimeRange4();
                    String diningTime4 = arrToString(diningTimeRange4);

                    saveCanteenDining(canteenInfo.getId(),subject,"4",diningTime4,canteenInfoDTO.getOutsourcerDiningFee4());
                }

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

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

        return msgResult;
    }

    private Integer saveCanteenDining(String canteenInfoId,String subject,String diningType,String diningTime1,BigDecimal outsourcerDiningFee1){

        CanteenDining canteenDining = new CanteenDining();
        canteenDining.setId(UUID.randomUUID().toString());
        canteenDining.setCanbteenId(canteenInfoId);
        canteenDining.setCreateBy(subject);
        canteenDining.setCreateTime(new Date());
        canteenDining.setDelFlag(false);
        canteenDining.setDiningType(diningType);
        canteenDining.setDiningTime(diningTime1);
        BigDecimal bd = BigDecimal.ONE;
        canteenDining.setDiningFee(bd);
        canteenDining.setOutsourcerDiningFee(outsourcerDiningFee1);

        int count = canteenDiningService.insert(canteenDining);

        return count;
    }

    private String arrToString(String timeRange){
        String str = "";
        String[] timeRangeArray = timeRange.split(",");
        if(timeRangeArray.length == 2) {
            String start = timeRangeArray[0];
            String end = timeRangeArray[1];
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("start",start);
            jsonObject.put("end",end);

            str = jsonObject.toString();
        }

        return str;
    }

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

        CanteenInfo canteenInfo = new CanteenInfo();

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

        return msgResult;
    }

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

        try {
            CanteenInfo canteenInfo = canteenInfoService.get(id);

//            if(StringUtils.isNotEmpty(canteenInfo.getLunchTime())){
//                JSONObject jsonObject = JSONObject.fromObject(canteenInfo.getLunchTime());
//                String start = (String)jsonObject.get("start");
//                String end = (String)jsonObject.get("end");
//                canteenInfo.setLunchTimeRange(start + "," + end);
//            }
//
//            if(StringUtils.isNotEmpty(canteenInfo.getDinnerTime())){
//                JSONObject jsonObject = JSONObject.fromObject(canteenInfo.getDinnerTime());
//                String start = (String)jsonObject.get("start");
//                String end = (String)jsonObject.get("end");
//                canteenInfo.setDinnerTimeRange(start + "," + end);
//            }
//
//            if(StringUtils.isNotEmpty(canteenInfo.getMidnightTime())){
//                JSONObject jsonObject = JSONObject.fromObject(canteenInfo.getMidnightTime());
//                String start = (String)jsonObject.get("start");
//                String end = (String)jsonObject.get("end");
//                canteenInfo.setMidnightTimeRange(start + "," + end);
//            }

            if (canteenInfo != null) {
                List<CanteenDining> list = canteenDiningService.findByCanteenId(canteenInfo.getId());

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

                for (CanteenDining canteenDining:list) {

                    JSONObject jsonObject = JSONObject.fromObject(canteenDining.getDiningTime());
                    String start = (String)jsonObject.get("start");
                    String end = (String)jsonObject.get("end");
                    canteenDining.setDiningTimeRange(start + "," + end);

                    canteenDiningMap.put("diningTimeRange"+ canteenDining.getDiningType(),canteenDining.getDiningTimeRange());
                    canteenDiningMap.put("outsourcerDiningFee"+ canteenDining.getDiningType(),canteenDining.getOutsourcerDiningFee());
                }

                canteenInfo.setCanteenDiningObjMap(canteenDiningMap);

                canteenInfo.setCanteenDiningList(list);

                msgResult.setResult(true);
                msgResult.setData(canteenInfo);
            } 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<CanteenInfo> update(@RequestBody CanteenInfoDTO canteenInfoDTO,@RequestAttribute String subject){
        MessageResult<CanteenInfo> msgResult = new MessageResult<>();

        try {
            CanteenInfo canteenInfo = canteenInfoService.get(canteenInfoDTO.getId());

            Date now = new Date();

            canteenInfo.setName(canteenInfoDTO.getName());
            canteenInfo.setAddress(canteenInfoDTO.getAddress());
            canteenInfo.setUpdateBy(subject);
            canteenInfo.setUpdateTime(now);

            int affectCount = canteenInfoService.update(canteenInfo);

//            if(StringUtils.isNotEmpty(canteenInfo.getLunchTimeRange())){
//                String lunchTimeRange = canteenInfo.getLunchTimeRange();
//                String lunchTime = arrToString(lunchTimeRange);
//                canteenInfo.setLunchTime(lunchTime);
//
//            }
//
//            if(StringUtils.isNotEmpty(canteenInfo.getDinnerTimeRange())){
//                String dinnerTimeRange = canteenInfo.getDinnerTimeRange();
//                String dinnerTime = arrToString(dinnerTimeRange);
//                canteenInfo.setDinnerTime(dinnerTime);
//            }
//
//            if(StringUtils.isNotEmpty(canteenInfo.getMidnightTimeRange())){
//                String midnightTimeRange = canteenInfo.getMidnightTimeRange();
//                String midnightTime = arrToString(midnightTimeRange);
//                canteenInfo.setMidnightTime(midnightTime);
//            }

            if (affectCount > 0) {
                List<CanteenDining> list = canteenDiningService.findByCanteenId(canteenInfo.getId());
                for (CanteenDining canteenDining:list) {
                    canteenDining.setDelFlag(true);
                    canteenDining.setUpdateBy(subject);
                    canteenDining.setUpdateTime(now);
                    canteenDiningService.update(canteenDining);
                }

                if(StringUtils.isNotEmpty(canteenInfoDTO.getDiningTimeRange1())){
                    String diningTimeRange1 = canteenInfoDTO.getDiningTimeRange1();
                    String diningTime1 = arrToString(diningTimeRange1);

                    saveCanteenDining(canteenInfo.getId(),subject,"1",diningTime1,canteenInfoDTO.getOutsourcerDiningFee1());
                }

                if(StringUtils.isNotEmpty(canteenInfoDTO.getDiningTimeRange2())){
                    String diningTimeRange2 = canteenInfoDTO.getDiningTimeRange2();
                    String diningTime2 = arrToString(diningTimeRange2);

                    saveCanteenDining(canteenInfo.getId(),subject,"2",diningTime2,canteenInfoDTO.getOutsourcerDiningFee2());
                }

                if(StringUtils.isNotEmpty(canteenInfoDTO.getDiningTimeRange3())){
                    String diningTimeRange3 = canteenInfoDTO.getDiningTimeRange3();
                    String diningTime3 = arrToString(diningTimeRange3);

                    saveCanteenDining(canteenInfo.getId(),subject,"3",diningTime3,canteenInfoDTO.getOutsourcerDiningFee3());
                }

                if(StringUtils.isNotEmpty(canteenInfoDTO.getDiningTimeRange4())){
                    String diningTimeRange4 = canteenInfoDTO.getDiningTimeRange4();
                    String diningTime4 = arrToString(diningTimeRange4);

                    saveCanteenDining(canteenInfo.getId(),subject,"4",diningTime4,canteenInfoDTO.getOutsourcerDiningFee4());
                }

                msgResult.setResult(true);
                msgResult.setData(canteenInfo);
            } 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<CanteenInfo> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<CanteenInfo> msgResult = new MessageResult<>();

        try {
            CanteenInfo canteenInfo = canteenInfoService.get(id);

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

            int affectCount = canteenInfoService.update(canteenInfo);

            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) {
                CanteenInfo canteenInfo = canteenInfoService.get(id);
                canteenInfo.setDelFlag(true);
                canteenInfo.setUpdateBy(subject);
                canteenInfo.setUpdateTime(new Date());

                affectCount += canteenInfoService.update(canteenInfo);
            }

            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 Map<String,Object> pageList(
            String name,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            HttpServletRequest request){
        String subject = (String)request.getAttribute("subject");

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

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

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("create_time","desc"));

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


        Page<CanteenInfo> page = canteenInfoService.pageSearch(searchParams,pageIndex,pageSize,sortList);


        List<CanteenInfo> canteenInfoList = new ArrayList<>();

        for (CanteenInfo canteenInfo:page) {
            List<CanteenDining> list = canteenDiningService.findByCanteenId(canteenInfo.getId());


            Map<String,List<String>> map = new HashMap<>();

            for (CanteenDining canteenDining:list) {
                JSONObject jsonObject = JSONObject.fromObject(canteenDining.getDiningTime());
                String start = (String)jsonObject.get("start");
                String end = (String)jsonObject.get("end");
                canteenDining.setDiningTimeRange(start + "-" + end);

                String diningTypeName = dataDictionaryService.findNameByCatalogNameAndValue("就餐类型",canteenDining.getDiningType());

                canteenDining.setDiningTypeName(diningTypeName+"时间");

                List<String> numberList1 = new ArrayList<>();
                numberList1.add(canteenDining.getDiningTimeRange());

                List<String> numberList2 = new ArrayList<>();
                numberList2.add(canteenDining.getOutsourcerDiningFee().toString());

                map.put("diningTypeName"+canteenDining.getDiningType(),numberList1);
                map.put("outsourcerDiningFee"+ canteenDining.getDiningType(),numberList2);
            }


            canteenInfo.setCanteenDiningMap(map);

            canteenInfoList.add(canteenInfo);


//            if(StringUtils.isNotEmpty(canteenInfo.getLunchTime())){
//                JSONObject jsonObject = JSONObject.fromObject(canteenInfo.getLunchTime());
//                String start = (String)jsonObject.get("start");
//                String end = (String)jsonObject.get("end");
//                canteenInfo.setLunchTimeRange(start + "-" + end);
//            }
//
//            if(StringUtils.isNotEmpty(canteenInfo.getDinnerTime())){
//                JSONObject jsonObject = JSONObject.fromObject(canteenInfo.getDinnerTime());
//                String start = (String)jsonObject.get("start");
//                String end = (String)jsonObject.get("end");
//                canteenInfo.setDinnerTimeRange(start + "-" + end);
//            }
//
//            if(StringUtils.isNotEmpty(canteenInfo.getMidnightTime())){
//                JSONObject jsonObject = JSONObject.fromObject(canteenInfo.getMidnightTime());
//                String start = (String)jsonObject.get("start");
//                String end = (String)jsonObject.get("end");
//                canteenInfo.setMidnightTimeRange(start + "-" + end);
//            }
        }

        dataMap.put("recordsTotal", page.getTotal());
        dataMap.put("totalPage", page.getPages());
        dataMap.put("canteenInfoList", canteenInfoList);


        return dataMap;
    }


    @ApiOperation(value="获取动态头部列表")
    @RequestMapping(value = "getTableHead",method = RequestMethod.POST)
    public MessageResult<Object> getTableHead() {

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

        List<DataDictionary> list = dataDictionaryService.findByCatalogName("就餐类型");

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

        for (DataDictionary dataDictionary:list) {
            Map<String,String> map = new HashMap<>();
            map.put("prop","diningTypeName"+ dataDictionary.getValue());
            map.put("col",dataDictionary.getName()+"时间");

            headList.add(map);

            Map<String,String> map1 = new HashMap<>();
            map1.put("prop","outsourcerDiningFee"+ dataDictionary.getValue());
            map1.put("col",dataDictionary.getName() + "金额（元）");

            headList.add(map1);
        }

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

        return msgResult;
    }


    @ApiOperation(value="获取动态编辑字段")
    @RequestMapping(value = "getEditHead",method = RequestMethod.POST)
    public MessageResult<Object> getEditHead() {

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

        List<DataDictionary> list = dataDictionaryService.findByCatalogName("就餐类型");

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

        for (DataDictionary dataDictionary:list) {
            Map<String,String> map = new HashMap<>();
            map.put("key1","diningTypeName"+ dataDictionary.getValue());
            map.put("value1",dataDictionary.getName()+"时间");

            map.put("key2","outsourcerDiningFee"+ dataDictionary.getValue());
            map.put("value2",dataDictionary.getName() + "金额（元）");

            headList.add(map);
        }

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

        return msgResult;
    }
}
