package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.TuanYouConfig;
import com.hai.entity.SecConfig;
import com.hai.entity.SecDictionary;
import com.hai.model.*;
import com.hai.service.CommonService;
import com.hai.service.SecConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@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 RedisUtil redisUtil;

	@RequestMapping(value="/getRedisValueByType",method= RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询redis中的value")
	public ResponseData getRedisValueByType(@RequestParam(name = "key", required = true) String key){
		try {

			return ResponseMsgUtil.success(redisUtil.get(key));

		} catch (Exception e) {
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value="/getProvinceList",method= RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询省级列表")
	public ResponseData getProvinceList(){
		try {

			return ResponseMsgUtil.success(commonService.getProvinceList());

		} 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 {
			List<SecDictionary> list = commonService.getDictionarys(codeType);
			if (list != null && list.size() > 0) {
				list = list.stream().sorted(Comparator.comparingDouble(entry -> entry.getSortId())).collect(Collectors.toList());
			}
			return ResponseMsgUtil.success(list);

		} 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="/editConfig",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "添加配置")
	public ResponseData editConfig(@RequestBody JSONObject body) {
		try {
			if (body == null
					|| StringUtils.isBlank(body.getString("codeType"))
					|| StringUtils.isBlank(body.getString("codeValue"))
			) {
				log.error("OrderController --> orderToPay() ERROR", "");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
			}

			SecConfig config = secConfigService.findByCodeType(body.getString("codeType"));
			if (config == null) {
				config = new SecConfig();
				config.setCodeType(body.getString("codeType"));
				config.setCodeValue(body.getString("codeValue"));
				secConfigService.insertSecConfig(config);

			} else {
				config.setCodeValue(body.getString("codeValue"));
				secConfigService.updateSecConfig(config);
			}

			return ResponseMsgUtil.success("修改成功");
		} catch (Exception e) {
			log.error("CommonController --> editConfig() 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="/getHLTBalance",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询汇联通余额")
	public ResponseData getHLTBalance(
			@RequestParam(name = "codeType", required = true) String codeType
	) {
		try {

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

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

	@RequestMapping(value="/addHLTBalance",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "新增余额")
	public ResponseData addHLTBalance(@RequestBody JSONObject object) {
		try {
			commonService.addHLTBalance(object.getString("codeType") , object.getBigDecimal("price"));
			return ResponseMsgUtil.success("修改成功");

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

	@RequestMapping(value="/getIndexCount",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询统计")
	public ResponseData getIndexCount() {
		try {
			return ResponseMsgUtil.success(commonService.getIndexCount());

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

	@RequestMapping(value="/getLineCount",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询折线图统计数据")
	public ResponseData getLineCount() {
		try {
			LineCountModel lineCountModel = commonService.getLineCount();

			LineCountReturnModel lineCountReturnModel = new LineCountReturnModel();

			lineCountReturnModel.setDate(conversionData(lineCountModel.getOrderPriceSum()));
			lineCountReturnModel.setUserCount(conversionCountData(lineCountModel.getUserCount()));
			lineCountReturnModel.setOrderCount(conversionCountData(lineCountModel.getOrderCount()));
			lineCountReturnModel.setOrderRechargeCount(conversionCountData(lineCountModel.getOrderRechargeCount()));
			lineCountReturnModel.setOrderRechargePriceSum(conversionSumData(lineCountModel.getOrderRechargePriceSum()));
			lineCountReturnModel.setOrderPriceSum(conversionSumData(lineCountModel.getOrderPriceSum()));

			return ResponseMsgUtil.success(lineCountReturnModel);

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

	private BigDecimal[] conversionSumData(List<OrderSumModel> list) {
		BigDecimal[] data = new BigDecimal[7];
		for (int i = 0; i <list.size() ; i++) {
			data[i] = list.get(i).getPrice();
		}
		return data;
	}

	private String[] conversionData(List<OrderSumModel> list) throws Exception {
		String[] data = new String[7];
		for (int i = 0; i <list.size() ; i++) {
			data[i] = DateUtil.date2String(list.get(i).getDatetime() , "yyyy-MM-dd");
		}
		return data;
	}

	private Long[] conversionCountData(List<DateCountModel> list) {
		Long[] data = new Long[7];
		for (int i = 0; i <list.size() ; i++) {
			data[i] = list.get(i).getNum();
		}
		return data;
	}

    @RequestMapping(value = "/queryCompanyAccountInfo2JD", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询团油余额")
    public ResponseData queryCompanyAccountInfo2JD() {
        try {

            return ResponseMsgUtil.success(TuanYouConfig.queryCompanyAccountInfo2JD().getJSONArray("result"));
        } catch (Exception e) {
            log.error("HighOrderController --> queryCompanyAccountInfo2JD() 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 {
            System.out.println("请求经度==================" + lng);
            System.out.println("请求纬度==================" + lat);
            JSONObject object = commonService.findByLatAndLng(lng , lat);
            System.out.println("请求经纬度========" + object);
            return ResponseMsgUtil.success(object);

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


}
