package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConst;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.common.utils.WxUtils;
import com.hai.config.WeChatQrcodeUtils;
import com.hai.entity.*;
import com.hai.goods.service.GoodsRegionFreightService;
import com.hai.model.ResponseData;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.util.crypto.SHA1;
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.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(value = "/common")
@Api(value = "共用接口")
public class CommonController {

    Logger log = LoggerFactory.getLogger(CommonController.class);

    @Resource
    private CommonService commonService;

    @Resource
    private SecConfigService secConfigService;

    @Resource
    private BsCompanyService bsCompanyService;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private BsIntegralRebateService bsIntegralRebateService;

    @Resource
    private GoodsRegionFreightService goodsRegionFreightService;

    @RequestMapping(value = "/getDredgeProvince", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询已开通的省份")
    public ResponseData getDredgeProvince() {
        try {
            List<BsCompany> list = bsCompanyService.getCompany(new HashMap<>());
            List<Map<String, Object>> mapList = new ArrayList<>();
            Map<String, Object> map;
            if (list.size() > 0) {
                for (BsCompany company : list) {
                    map = new HashMap<>();
                    if (StringUtils.isNotBlank(company.getRegionId())) {
                        map.put("companyId", company.getId());
                        map.put("regionId", company.getRegionId());
                        SecRegion secRegion = commonService.getRegionsById(Long.parseLong(company.getRegionId()));
                        if (secRegion != null) {
                            map.put("regionName", secRegion.getRegionName());
                        }
                        mapList.add(map);
                    }
                }
            }
            return ResponseMsgUtil.success(mapList);
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getRegionsByParentId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "分级查询区域信息")
    public ResponseData getRegionsByParentId(@RequestParam(name = "regionId", required = false) Long regionId) {
        try {
            if (regionId == null) {
                return ResponseMsgUtil.success(commonService.getCities());
            }
            return ResponseMsgUtil.success(commonService.getRegionsByParentId(regionId));
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getParentInfosByRegionId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询父级区域信息")
    public ResponseData getParentInfosByRegionId(@RequestParam(name = "regionId", required = true) Long regionId) {
        try {
            return ResponseMsgUtil.success(commonService.getParentInfoByRegionId(regionId));
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getRegionsById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询区域详细信息")
    public ResponseData getRegionsById(@RequestParam(name = "regionId", required = true) Long regionId) {
        try {
            return ResponseMsgUtil.success(commonService.getRegionsById(regionId));
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/getDictionaries", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询数据字典")
    public ResponseData getDictionaries() {
        try {
            return ResponseMsgUtil.success(commonService.getDictionaries());
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/getDictionaryByCodeType", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据 码值类型 查询数据字典")
    public ResponseData getDictionaryByCodeType(@RequestParam(name = "codeType", required = true) String codeType) {
        try {

            return ResponseMsgUtil.success(commonService.getDictionarys(codeType));

        } catch (Exception e) {
            log.error("CommonController --> getDictionaryByCodeType() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/mappingSysNameOl", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据 码值类型 查询数据字典")
    public ResponseData mappingSysNameOl(@RequestParam(name = "codeType", required = true) String codeType) {
        try {

            return ResponseMsgUtil.success(commonService.mappingSysNameOl(codeType));

        } catch (Exception e) {
            log.error("CommonController --> getDictionaryByCodeType() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getDictionaryByCodeTypeOl", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据 码值类型 查询数据字典")
    public ResponseData getDictionaryByCodeTypeOl(@RequestParam(name = "codeType", required = true) String codeType) {
        try {

            return ResponseMsgUtil.success(secConfigService.findByCodeType(codeType));

        } catch (Exception e) {
            log.error("CommonController --> getDictionaryByCodeType() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateDictionary", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据 码值类型 查询数据字典")
    public ResponseData updateDictionary(@RequestParam(name = "codeType", required = true) String codeType, @RequestParam(name = "codeValue", required = true) String codeValue) {
        try {

            SecConfig secConfig = secConfigService.findByCodeType(codeType);
            secConfig.setCodeValue(codeValue);
            secConfigService.updateSecConfig(secConfig);

            return ResponseMsgUtil.success("修改成功");
        } catch (Exception e) {
            log.error("CommonController --> getDictionaryByCodeType() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getDictionaryByCodeTypeAndExt", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据 码值类型 查询数据字典")
    public ResponseData getDictionaryByCodeTypeAndExt(@RequestParam(name = "codeType", required = true) String codeType, String ext1) {
        try {

            return ResponseMsgUtil.success(commonService.getDictionarysAndExt(codeType, ext1));

        } catch (Exception e) {
            log.error("CommonController --> getDictionaryByCodeType() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getIdAndNameByCodeType", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据 码值类型 查询数据字典的id和name")
    public ResponseData getIdAndNameByCodeType(@RequestParam(name = "codeType", required = true) String codeType) {
        try {

            return ResponseMsgUtil.success(commonService.getIdAndName(codeType));

        } catch (Exception e) {
            log.error("CommonController --> getIdAndNameByCodeType() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getDictionaryByCodeTypeAndValue", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据码值类型及value查询数据字典")
    public ResponseData getDictionaryByCodeType(@RequestParam(name = "codeType", required = true) String codeType, @RequestParam(name = "codeValue", required = true) String codeValue) {
        try {

            return ResponseMsgUtil.success(commonService.mappingSysCode(codeType, codeValue));

        } catch (Exception e) {
            log.error("CommonController --> getDictionaryByCodeTypeAndValue() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/findSecConfigByType", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据码值类型查询数据")
    public ResponseData findSecConfigByType(@RequestParam(name = "codeType", required = true) String codeType) {
        try {

            return ResponseMsgUtil.success(commonService.findSecConfigByType(codeType));

        } catch (Exception e) {
            log.error("CommonController --> getDictionaryByCodeTypeAndValue() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/findByLatAndLng", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取定位信息")
    public ResponseData findByLatAndLng(@RequestParam(name = "lng", required = true) String lng, @RequestParam(name = "lat", required = true) String lat) {
        try {


            JSONObject jsonObjectR = commonService.findByLatAndLng(lng, lat);

            if (!jsonObjectR.getString("status").equals("0")) {
                log.error("findByLatAndLng error!", "定位错误，请重新定位");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "定位错误，请重新定位");
            }

            JSONObject object = jsonObjectR.getJSONObject("result").getJSONObject("addressComponent");


            ApiCity apiCity = commonService.findCityByName(object.getString("city"));

            if (apiCity == null) {
                log.error("findByLatAndLng error!", "当前城市暂未开通任何服务");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前城市暂未开通任何服务，请选择其他城市");
            }

            BsCompany company = bsCompanyService.selectCompanyByRegion(apiCity.getProvinceCode());

            if (company == null) {
                log.error("findByLatAndLng error!", "当前城市暂未开通任何服务");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前城市暂未开通任何服务，请选择其他城市");
            }

            JSONObject jsonObject = new JSONObject();

            jsonObject.put("cityName", apiCity.getCityName());
            jsonObject.put("provinceName", apiCity.getProvinceName());
            jsonObject.put("regionId", company.getRegionId());
            jsonObject.put("companyName", company.getName());
            jsonObject.put("companyId", company.getId());

            return ResponseMsgUtil.success(jsonObject);

        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/baiduApiMapSearch", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取定位信息")
    public ResponseData baiduApiMapSearch(
            @RequestParam(name = "lng", required = true) String lng,
            @RequestParam(name = "lat", required = true) String lat,
            @RequestParam(name = "query", required = false) String query) {
        try {


            if (query == null) {
                JSONObject map = commonService.findByLatAndLng(lng, lat);
                if (!map.getString("status").equals("0")) {
                    log.error("findByLatAndLng error!", "定位错误，请重新定位");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "定位错误，请重新定位");
                }
                query = map.getJSONObject("result").getString("formatted_address");
            }

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

            map.put("query" , query);
            map.put("location", lat+","+lng);

            JSONObject jsonObjectR = commonService.baiduApiMapSearch(map);

            if (!jsonObjectR.getString("status").equals("0")) {
                log.error("findByLatAndLng error!", "定位错误，请重新定位");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "定位错误，请重新定位");
            }


            return ResponseMsgUtil.success(jsonObjectR.getJSONArray("results"));

        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/findCompanyByCityName", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取定位信息")
    public ResponseData findCompanyByCityName(@RequestParam(name = "cityName", required = true) String cityName) {
        try {

            ApiCity apiCity = commonService.findCityByName(cityName);

            if (apiCity == null) {
                log.error("findByLatAndLng error!", "当前城市暂未开通任何服务");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前城市暂未开通任何服务，请选择其他城市");
            }

            BsCompany company = bsCompanyService.selectCompanyByRegion(apiCity.getProvinceCode());

            if (company == null) {
                log.error("findByLatAndLng error!", "当前城市暂未开通任何服务");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前城市暂未开通任何服务，请选择其他城市");
            }

            JSONObject jsonObject = new JSONObject();

            jsonObject.put("cityName", apiCity.getCityName());
            jsonObject.put("provinceName", apiCity.getProvinceName());
            jsonObject.put("regionId", company.getRegionId());
            jsonObject.put("companyName", company.getName());
            jsonObject.put("companyId", company.getId());

            return ResponseMsgUtil.success(jsonObject);

        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getRebateIntegral", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询可获取返利积分")
    public ResponseData getRebateIntegral(@RequestBody JSONObject object) {
        try {

            System.out.println(object);

            if (object.getInteger("type") == null || object.getLong("companyId") == null || object.getBigDecimal("price") == null) {
                log.error("CommonController -> getRebateIntegral() error!", "请求参数校验失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR);
            }

            // 查询订单来源
            Map<String, Object> map = new HashMap<>();
            map.put("type", object.getInteger("type"));
            map.put("companyId", object.getLong("companyId"));

            BsIntegralRebate bsIntegralRebate = bsIntegralRebateService.findIntegralRebateByMap(map);

            if (bsIntegralRebate == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂无积分返利活动");
            }

            BigDecimal integralNum = object.getBigDecimal("price").multiply(bsIntegralRebate.getPercentage()).setScale(0, BigDecimal.ROUND_HALF_UP);

            return ResponseMsgUtil.success(integralNum);

        } catch (Exception e) {
            log.error("CommonController -> getRebateIntegral() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getRegional", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取区域信息")
    public ResponseData getRegional() {
        try {

            Object data = redisUtil.get("regional");

            if (data == null) {

                List<JSONObject> jsonObjects = commonService.getRegional("code" , "name" , "childs");
                redisUtil.set("regional", jsonObjects);

                return ResponseMsgUtil.success(jsonObjects);

            } else {
                return ResponseMsgUtil.success(data);
            }


        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getRegionFreight", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取区域运费")
    public ResponseData getRegionFreight(@RequestParam(name = "regionId", required = true) String regionId) {
        try {

            return ResponseMsgUtil.success(goodsRegionFreightService.getRegionFreight(regionId));

        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getIndustry", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取行业信息")
    public ResponseData getIndustry() {
        try {

            JSONObject object = commonService.getIndustry();
            return ResponseMsgUtil.success(object.getJSONArray("return_data"));

        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getMapStore", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取地图门店")
    public ResponseData getMapStore(
            @RequestParam(name = "distance", required = true) Double distance,
            @RequestParam(name = "type", required = true) Integer type,
            @RequestParam(name = "name", required = false) String name,
            @RequestParam(name = "childId", required = false) Long childId,
            @RequestParam(name = "longitude", required = true) String longitude,
            @RequestParam(name = "latitude", required = true) String latitude
    ) {
        try {

            return ResponseMsgUtil.success(commonService.getMapStore(name , childId , latitude , longitude , distance , type));

        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/gaoDeApiMapSearch", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取定位信息")
    public ResponseData gaoDeApiMapSearch(
            @RequestParam(name = "query", required = false) String query) {
        try {

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

            map.put("keywords" , query);
            map.put("extensions" , "all");

            JSONObject jsonObject = commonService.gaoDeApiMapSearch(map);

            return ResponseMsgUtil.success(jsonObject.getJSONArray("tips"));

        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
