package com.fjs.scenic.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjs.scenic.dto.InputInfoDto;
import com.fjs.scenic.entity.system.InpIncome;
import com.fjs.scenic.entity.system.InputInfo;
import com.fjs.scenic.service.system.InpIncomeService;
import com.fjs.scenic.service.system.InputInfoService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.fjs.scenic.utils.HttpReq;
import com.fjs.scenic.utils.ReturnResult;
import com.google.gson.JsonObject;

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

/**
 * @author wgd
 * @date 2020-05-18
 * 领导查询
 */
@RestController
@RequestMapping("/api/leader")
@Api(description = "领导查询")
public class LeaderQueryController {
    @Autowired
    private InputInfoService inputInfoService;
    @Autowired
    private InpIncomeService inpIncomeService;
    private Logger log = LoggerFactory.getLogger(LeaderQueryController.class);
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${pw.api}")
    private String url;


    @ApiOperation(value = "景区所有汇总数据", notes = "景区所有汇总数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "所选时间", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping(value = "/getSupplierSummary")
    public ReturnResult getSupplierSummary(String time) {

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("date_end", time);

        JSONObject jsonData = null;

        try {
            jsonData = HttpReq.sendPost(url, "SupplierSummary", jsonObject.toString());
        } catch (Exception e) {
            log.error(e.getMessage());
            return ReturnResult.error(e.getMessage());
        }

        String code = (String) jsonData.get("code");

        if (code.equals("200")) {
            // 获取解密json数据
            String dataStr = null;

            try {
                dataStr = HttpReq.getDataStr(jsonData);
                jsonData = JSONObject.parseObject(dataStr);
            } catch (Exception e) {
                log.error(e.getMessage());
                return ReturnResult.error(e.getMessage());
            }
            return ReturnResult.ok(jsonData);

        } else {

            return ReturnResult.error(jsonData.get("describe"));

        }

    }


    @ApiOperation(value = "旅行社列表", notes = "旅社社列表")
    @GetMapping(value = "/getTravel")
    public ReturnResult getTravelByList() {

        JsonObject jsonObject = new JsonObject();

        JSONObject jsonData = null;

        try {
            jsonData = HttpReq.sendPost(url, "travelList", jsonObject.toString());
        } catch (Exception e) {
            log.error(e.getMessage());
            return ReturnResult.error(e.getMessage());
        }

        String code = (String) jsonData.get("code");

        if (code.equals("200")) {
            // 获取解密json数据
            String dataStr = null;

            try {
                dataStr = HttpReq.getDataStr(jsonData);
            } catch (Exception e) {
                log.error(e.getMessage());
                return ReturnResult.error(e.getMessage());
            }

            return ReturnResult.ok(JSONArray.parseArray(dataStr));

        } else {

            return ReturnResult.error(jsonData.get("describe"));

        }

    }

    @ApiOperation(value = "景区列表", notes = "景区列表")
    @GetMapping(value = "/getSupplier")
    public ReturnResult getSupplierByList(HttpServletRequest request) {
        String token = request.getHeader("token");
        String suplierIds = redisTemplate.opsForValue().get(token);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("service", suplierIds);

        JSONObject jsonData = null;

        try {
            jsonData = HttpReq.sendPost(url, "supplierList", jsonObject.toString());
        } catch (Exception e) {
            log.error(e.getMessage());
            return ReturnResult.error(e.getMessage());
        }

        String code = (String) jsonData.get("code");

        if (code.equals("200")) {
            // 获取解密json数据
            String dataStr = null;

            try {
                dataStr = HttpReq.getDataStr(jsonData);

            } catch (Exception e) {
                log.error(e.getMessage());
                return ReturnResult.error(e.getMessage());
            }
            JSONArray objects = JSONArray.parseArray(dataStr);
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("SZSCENICNAME", "全部景区");
            jsonObject1.put("ISCENICID", suplierIds);
            objects.add(jsonObject1);
            return ReturnResult.ok(objects);

        } else {

            return ReturnResult.error(jsonData.get("describe"));

        }

    }


    @ApiOperation(value = "旅行社申报", notes = "旅行社申报")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间段", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "travel", value = "旅行社", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping(value = "/getTravelTeam")
    public ReturnResult getTravelTeamByInfo(String time, String travel) {

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("date_end", time);
        jsonObject.addProperty("travel", travel);

        JSONObject jsonData = null;

        try {
            jsonData = HttpReq.sendPost(url, "travelTeamDeclare", jsonObject.toString());
        } catch (Exception e) {
            log.error(e.getMessage());
            return ReturnResult.error(e.getMessage());
        }

        String code = (String) jsonData.get("code");

        if (code.equals("200")) {
            // 获取解密json数据
            String dataStr = null;

            try {
                dataStr = HttpReq.getDataStr(jsonData);
                jsonData = JSONObject.parseObject(dataStr);
            } catch (Exception e) {
                log.error(e.getMessage());
                return ReturnResult.error(e.getMessage());
            }
            return ReturnResult.ok(jsonData);

        } else {

            return ReturnResult.error(jsonData.get("describe"));

        }

    }

    @ApiOperation(value = "售检票查询", notes = "售检票查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "codeVal", value = "订单编号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "card", value = "身份证号码", required = false, dataType = "String", paramType = "query")})
    @GetMapping(value = "/getCheckOutQuery")
    public ReturnResult getCheckOutQuery(String codeVal, String card) {

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("code", codeVal);
        jsonObject.addProperty("card", card);

        JSONObject jsonData = null;

        try {
            jsonData = HttpReq.sendPost(url, "ticketquery", jsonObject.toString());
        } catch (Exception e) {
            log.error(e.getMessage());
            return ReturnResult.error(e.getMessage());
        }

        String code = (String) jsonData.get("code");
        Object objects = null;
        if (code.equals("200")) {
            // 获取解密json数据
            String dataStr;
            try {
                dataStr = HttpReq.getDataStr(jsonData);

                if (dataStr.contains("[")) {
                    objects = JSONArray.parseArray(dataStr);
                } else {
                    objects = JSONObject.parseObject(dataStr);
                }

            } catch (Exception e) {
                log.error(e.getMessage());
                return ReturnResult.error(e.getMessage());
            }

            return ReturnResult.ok(objects);

        } else {

            return ReturnResult.error(jsonData.get("describe"));

        }

    }

    @ApiOperation(value = "游客查询", notes = "游客查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "年月时时间", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "service", value = "服务商", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "flag", value = "日（day）、周（week）、月（month）、年（year）", required = true, dataType = "String", paramType = "query"),
    })
    @GetMapping(value = "/getToursitQueryMin")
    public ReturnResult getToursitQueryMin(String time, String service, String flag) {

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("date_end", time);
        jsonObject.addProperty("service", service);
        jsonObject.addProperty("flag", flag);

        JSONObject jsonData = null;

        try {
            jsonData = HttpReq.sendPost(url, "touristquerymin", jsonObject.toString());
        } catch (Exception e) {
            log.error(e.getMessage());
            return ReturnResult.error(e.getMessage());
        }

        String code = (String) jsonData.get("code");

        if (code.equals("200")) {
            //获取解密json数据
            String dataStr;
            try {
                dataStr = HttpReq.getDataStr(jsonData);
            } catch (Exception e) {
                log.error(e.getMessage());
                return ReturnResult.error(e.getMessage());
            }

            jsonData = JSONArray.parseObject(dataStr);

            String reserveStr = jsonData.getString("reserveStr");

            String pigStr = jsonData.getString("pigStr");

            String txStr = jsonData.getString("txStr");

            String reserveNum = jsonData.getString("reserveNum");

            String maxFlowNum = jsonData.getString("maxFlowNum");

            String ryrs = jsonData.getString("ryrs");

            JSONArray jo1 = JSONArray.parseArray(reserveStr);

            JSONArray jo2 = JSONObject.parseArray(pigStr);

            JSONArray jo3 = JSONArray.parseArray(txStr);

            JSONObject jo4 = JSONObject.parseObject(reserveNum);

            JSONObject jo5 = JSONObject.parseObject(maxFlowNum);

            JSONObject jo6 = JSONObject.parseObject(ryrs);

            jsonData.put("reserveStr", jo1);
            jsonData.put("pigStr", jo2);
            jsonData.put("txStr", jo3);
            jsonData.put("reserveNum", jo4);
            jsonData.put("maxFlowNum", jo5);
            jsonData.put("ryrs", jo6);

            return ReturnResult.ok(jsonData);

        } else {

            return ReturnResult.error(jsonData.get("describe"));

        }

    }

    @ApiOperation(value = "入园查询", notes = "入园查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "年月时时间", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "service", value = "服务商", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "flag", value = "传day,week,month,year", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping(value = "/getYkcxDa")
    public ReturnResult getYkcxDa(String time, String service, String flag) throws Exception {

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("date_end", time);
        jsonObject.addProperty("service", service);
        jsonObject.addProperty("flag", flag);
        JSONObject jsonData = HttpReq.sendPost(url, "touristquerymax", jsonObject.toString());
        String code = (String) jsonData.get("code");
        if (code.equals("200")) {
            //获取解密json数据
            String dataStr = HttpReq.getDataStr(jsonData);
            return ReturnResult.ok(JSONObject.parseObject(dataStr));
        } else {
            return ReturnResult.error(jsonData.get("describe"));
        }
    }


    @ApiOperation(value = "销售查询", notes = "销售查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "年月时日", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "service", value = "服务商id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "flag", value = "传day,week,month,year", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping(value = "/getSalequery")
    public ReturnResult getSalequery(String time, String service, String flag) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("date_end", time);
        jsonObject.addProperty("service", service);
        jsonObject.addProperty("flag", flag);

        JSONObject jsonData = null;
        try {
            jsonData = HttpReq.sendPost(url, "salequery", jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String code = (String) jsonData.get("code");
        if (code.equals("200")) {
            //获取解密json数据
            String dataStr = null;
            try {
                dataStr = HttpReq.getDataStr(jsonData);
            } catch (Exception e) {
                e.printStackTrace();
                return ReturnResult.error(e.getMessage());
            }
            JSONObject jsonObject1 = JSONObject.parseObject(dataStr);
            JSONArray s1 = JSONArray.parseArray(jsonObject1.getString("s1"));
            JSONArray s2 = JSONArray.parseArray(jsonObject1.getString("s2"));
            JSONArray s3 = JSONArray.parseArray(jsonObject1.getString("s3"));
            JSONObject s4 = JSONObject.parseObject(jsonObject1.getString("s4"));
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("s1", s1);
            jsonObject2.put("s2", s2);
            jsonObject2.put("s3", s3);
            //jsonObject2.put("team",s4.get("team"));
            jsonObject2.put("ycsc", s4.get("ycsc"));
            jsonObject2.put("rzqjzs", s4.get("rzqjzs"));
            jsonObject2.put("zsblh", s4.get("zsblh"));
            return ReturnResult.ok(jsonObject2);
        } else {
            return ReturnResult.error(jsonData.get("describe"));
        }
    }

    @ApiOperation(value = "预计各项人数", notes = "预计各项人数")
    @GetMapping(value = "/expectService")
    @ApiImplicitParam(name = "time", value = "年月日", required = true, dataType = "String", paramType = "query")
    public ReturnResult expectService(String time) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("date_end", time);
        JSONObject jsonData = null;
        try {
            jsonData = HttpReq.sendPost(url, "expectService", jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String code = (String) jsonData.get("code");
        if (code.equals("200")) {
            //获取解密json数据
            String dataStr = null;
            try {
                dataStr = HttpReq.getDataStr(jsonData);
            } catch (Exception e) {
                e.printStackTrace();
                return ReturnResult.error(e.getMessage());
            }

            JSONObject jsonObject1 = JSONObject.parseObject(dataStr);

            JSONArray lxsdata = jsonObject1.getJSONArray("lxsdata");

            JSONArray all = new JSONArray();

            //去重操作
            Set<String> usidSet = new HashSet<String>();
            for (int i = 0; i < lxsdata.size(); i++) {
                JSONObject jo = lxsdata.getJSONObject(i);
                usidSet.add(jo.getString("USID"));
            }

            Iterator<String> iterator = usidSet.iterator();


            while (iterator.hasNext()) {

                JSONObject newjo = new JSONObject();

                String nextKey = iterator.next();

                //旅行社最大人次数量
                BigDecimal bdMaxPnum = new BigDecimal(0);
                //入住黔江
                BigDecimal bdZrqjNum = new BigDecimal(0);
                //入住濯水
                BigDecimal bdZrzsNum = new BigDecimal(0);

                String corpname = "";

                String kydStr = "";

                for (int i = 0; i < lxsdata.size(); i++) {

                    JSONObject jo = lxsdata.getJSONObject(i);

                    String usid = jo.getString("USID");

                    if (nextKey.equals(usid)) {

                        bdMaxPnum = bdMaxPnum.add(jo.getBigDecimal("MAXPNUM"));

                        corpname = jo.getString("CORPNAME");

                        bdZrqjNum = jo.getBigDecimal("ZRQJ");

                        bdZrzsNum = jo.getBigDecimal("ZRZS");

                        String kyd = jo.getString("KYD");

                        if (kydStr.indexOf(kyd) == -1) {
                            kydStr += kyd + ",";
                        }

                    }

                }

                kydStr = kydStr.substring(0, kydStr.length() - 1);

                newjo.put("CORPNAME", corpname);
                newjo.put("MAXPNUM", bdMaxPnum);
                newjo.put("ZRQJ", bdZrqjNum);
                newjo.put("ZRZS", bdZrzsNum);


                String kydInfo[] = kydStr.split(",");

                JSONArray contentJa = new JSONArray();

                //循环客源地数据
                for (String kydFor : kydInfo) {

                    JSONArray typeJa = new JSONArray();

                    JSONObject contentjo = new JSONObject();

                    BigDecimal bdKydNum = new BigDecimal(0);

                    for (int i = 0; i < lxsdata.size(); i++) {

                        JSONObject jo = lxsdata.getJSONObject(i);

                        String usid = jo.getString("USID");

                        String kyd = jo.getString("KYD");

                        if (nextKey.equals(usid) && kydFor.equals(kyd)) {

                            bdKydNum = bdKydNum.add(jo.getBigDecimal("KYDPNUM"));

                            JSONObject typeJo = new JSONObject();

                            String typeName = jo.getString("TYPENAME");
                            BigDecimal rs = jo.getBigDecimal("RS");

                            typeJo.put("NAME", typeName);
                            typeJo.put("RS", rs);

                            typeJa.add(typeJo);

                        }

                    }

                    contentjo.put("KYD", kydFor);
                    contentjo.put("KYDPNUM", bdKydNum);
                    contentjo.put("TEAMTYPE", typeJa);

                    contentJa.add(contentjo);
                }

                newjo.put("CONTENT", contentJa);

                all.add(newjo);
            }

            jsonObject1.remove("lxsdata");
            jsonObject1.put("lxsdata", all);

            return ReturnResult.ok(jsonObject1);
        } else {
            return ReturnResult.error(jsonData.get("describe"));
        }
    }

    @ApiOperation(value = "日报", notes = "日报")
    @GetMapping(value = "/dailyReport")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "年月时时间", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "company", value = "小南海", required = false, dataType = "String", paramType = "query")
    })
    public ReturnResult dailyReport(String time, String company) {
        Map<String, Object> result = new HashMap<>();
        result.put("allTotal", 0);
        result.put("scenics", new ArrayList<>());
        result.put("allPersonTimes", 0);
        List<InputInfo> inputInfos = new ArrayList<>();
        if (StringUtils.isEmpty(company)) {
            inputInfos = inputInfoService.list(new LambdaQueryWrapper<InputInfo>().eq(InputInfo::getStaticDate, time));
        } else {
            inputInfos = inputInfoService.list(new LambdaQueryWrapper<InputInfo>()
                    .eq(InputInfo::getStaticDate, time)
                    .eq(InputInfo::getCompany, company));
        }

        if (inputInfos.isEmpty()) {
            return ReturnResult.ok(result);
        }
        int total = 0;
        int allPersonTimes = 0;
        List<InputInfoDto> scenics = new ArrayList<InputInfoDto>();
        for (InputInfo inputInfo : inputInfos) {
            InputInfoDto inputInfoDto = new InputInfoDto();
            total += inputInfo.getTotal();
            allPersonTimes += inputInfo.getPersonTimes();
            List<InpIncome> inpIncomes = inpIncomeService.list(new LambdaQueryWrapper<InpIncome>()
                    .eq(InpIncome::getInputInfoId, inputInfo.getId()));
            BeanUtil.copyProperties(inputInfo, inputInfoDto);
            inputInfoDto.setIncome(inpIncomes);
            scenics.add(inputInfoDto);
        }
        result.put("allTotal",total);
        result.put("scenics", scenics);
        result.put("allPersonTimes", allPersonTimes);
        return ReturnResult.ok(result);
    }
}
