package com.jpsoft.shinestar.modules.base.service.impl;

import java.util.*;
import javax.annotation.Resource;

import cn.hutool.core.date.DateUtil;
import com.jpsoft.shinestar.config.ParkingConfig;
import com.jpsoft.shinestar.modules.base.entity.ParkingInfo;
import com.jpsoft.shinestar.modules.base.service.ParkingInfoService;
import com.jpsoft.shinestar.modules.common.utils.ParkApiUtil;
import com.jpsoft.shinestar.modules.common.utils.Sign;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.jpsoft.shinestar.modules.base.dao.ParkingMerchantDAO;
import com.jpsoft.shinestar.modules.base.entity.ParkingMerchant;
import com.jpsoft.shinestar.modules.base.service.ParkingMerchantService;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.github.pagehelper.PageHelper;

@Transactional
@Slf4j
@Component(value = "parkingMerchantService")
public class ParkingMerchantServiceImpl implements ParkingMerchantService {
    @Resource(name = "parkingMerchantDAO")
    private ParkingMerchantDAO parkingMerchantDAO;

    @Autowired
    private ParkingInfoService parkingInfoService;

    @Autowired
    private ParkingConfig parkingConfig;

    @Autowired
    private ParkApiUtil parkApiUtil;

    @Override
    public ParkingMerchant get(String id) {
        // TODO Auto-generated method stub
        return parkingMerchantDAO.get(id);
    }

    @Override
    public int insert(ParkingMerchant model) {
        // TODO Auto-generated method stub
        //model.setId(UUID.randomUUID().toString());

        return parkingMerchantDAO.insert(model);
    }

    @Override
    public int update(ParkingMerchant model) {
        // TODO Auto-generated method stub
        return parkingMerchantDAO.update(model);
    }

    @Override
    public int delete(String id) {
        // TODO Auto-generated method stub
        return parkingMerchantDAO.delete(id);
    }

    @Override
    public boolean exist(String id) {
        // TODO Auto-generated method stub
        int count = parkingMerchantDAO.exist(id);

        return count > 0 ? true : false;
    }

    @Override
    public List<ParkingMerchant> list() {
        // TODO Auto-generated method stub
        return parkingMerchantDAO.list();
    }

    @Override
    public Page<ParkingMerchant> pageSearch(Map<String, Object> searchParams, int pageNumber, int pageSize, boolean count, List<Sort> sortList) {
        Page<ParkingMerchant> page = PageHelper.startPage(pageNumber, pageSize, count).doSelectPage(() -> {
            parkingMerchantDAO.search(searchParams, sortList);
        });

        return page;
    }

    @Override
    public ParkingMerchant findByMerchantNo(String merchantNo) {
        return parkingMerchantDAO.findByMerchantNo(merchantNo);
    }

    @Override
    public ParkingMerchant createMerchant(String merchantNo, String companyId, String merchantName, String money) throws Exception {

        ParkingMerchant parkingMerchant = new ParkingMerchant();

        //1、创建商户
        List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(companyId);
        if (parkingInfoList.size() == 0) {
            throw new Exception("创建商户失败");
        }
        Long parkId = parkingInfoList.get(0).getParkId();


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

        map.put("ticket_type", 2);
        map.put("support_type", 0);
        map.put("hand_input_enable", 0);
        map.put("free_limit_times", 0);
        map.put("use_fix_code", 1);
        map.put("use_limit", 0);
        map.put("ticket_unit", 4);
        map.put("default_limit", 0);
        map.put("discount_percent", 100);
        map.put("discount_money", 1);
        map.put("free_money", Integer.valueOf(money));
        map.put("validite_time", 24);

        if (StringUtils.isNotBlank(merchantNo)) {
            map.put("id", merchantNo);
            map.put("comid", parkId);
            map.put("name", merchantName);
            map.put("free_money", Integer.valueOf(money));
            net.sf.json.JSONObject jsonObject = parkApiUtil.httpRequestSecond(parkingConfig.getIp() + ":8081/cloud/shop/create", "POST", map);
            Integer state = jsonObject.getInt("state");

            if (state != 1) {
                throw new Exception("创建商户失败");
            }
            parkingMerchant = findByMerchantNo(merchantNo);
            parkingMerchant.setMerchantName(merchantName);
            parkingMerchant.setReduce(Integer.valueOf(money));
            parkingMerchant.setUpdateTime(new Date());
            update(parkingMerchant);


        } else {


            map.put("comid", parkId);
            map.put("name", merchantName);
            map.put("free_money", Integer.valueOf(money));
		/*map.put("ticket_type", 2);
		map.put("support_type", 0);
		map.put("hand_input_enable", 0);
		map.put("free_limit_times", 0);
		map.put("use_fix_code", 1);
		map.put("use_limit", 0);
		map.put("ticket_unit", 4);
		map.put("default_limit", 0);
		map.put("discount_percent", 100);
		map.put("discount_money", 1);
		map.put("validite_time", 24);*/
            net.sf.json.JSONObject jsonObject = parkApiUtil.httpRequestSecond(parkingConfig.getIp() + ":8081/cloud/shop/create", "POST", map);
            Integer state = jsonObject.getInt("state");

            if (state != 1) {
                throw new Exception("创建商户失败");
            }

            //2、查询商户
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("comid", parkId);
            net.sf.json.JSONObject jsonObject1 = parkApiUtil.httpRequestSecond(parkingConfig.getIp() + ":8081/cloud/shop/quickquery", "POST", map1);
            JSONArray jsonArray = jsonObject1.getJSONArray("rows");
            String merchantId = null;
            for (Object object : jsonArray) {
                Map<String, Object> merchantMap = (Map) object;
                String name = (String) merchantMap.get("name");
                if (name.equals(merchantName)) {
                    merchantId = String.valueOf(merchantMap.get("id"));
                    break;
                }
            }

            if (merchantId == null) {
                throw new Exception("创建商户失败");
            }

            parkingMerchant.setId(UUID.randomUUID().toString());
            parkingMerchant.setMerchantNo(merchantId);
            parkingMerchant.setMerchantName(merchantName);
            parkingMerchant.setCompanyId(companyId);
            parkingMerchant.setType("5");
            parkingMerchant.setReduce(Integer.valueOf(money));
            parkingMerchant.setCreateTime(new Date());
            insert(parkingMerchant);

        }


        return parkingMerchant;
    }

    @Override
    public void deleteMerchant(String id) throws Exception {

        ParkingMerchant parkingMerchant = parkingMerchantDAO.get(id);

        if (parkingMerchant != null) {
            List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(parkingMerchant.getCompanyId());
            if (parkingInfoList.size() == 0) {
                throw new Exception("创建负责人失败");
            }
            Long parkId = parkingInfoList.get(0).getParkId();
            HashMap<String, Object> map = new HashMap<>();
            map.put("comid", parkId);
            map.put("id", parkingMerchant.getMerchantNo());
            net.sf.json.JSONObject jsonObject = parkApiUtil.httpRequestSecond(parkingConfig.getIp() + ":8081/cloud/shop/delete", "POST", map);
            Integer state = jsonObject.getInt("state");
            if (state != 1) {
                throw new Exception("创建负责人失败");
            }

            parkingMerchant.setDelFlag(true);
            update(parkingMerchant);

        }


    }

    @Override
    public void createShopMember(ParkingMerchant parkingMerchant) throws Exception {

        List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(parkingMerchant.getCompanyId());
        if (parkingInfoList.size() == 0) {
            throw new Exception("创建负责人失败");
        }
        Long parkId = parkingInfoList.get(0).getParkId();

        //1、创建负责人
        HashMap<String, Object> map = new HashMap<>();
        map.put("comid", parkId);
        map.put("shop_id", parkingMerchant.getMerchantNo());
        map.put("nickname", "负责人");
        map.put("role_id", 39);
        map.put("auth_flag", 14);
        net.sf.json.JSONObject jsonObject = parkApiUtil.httpRequestSecond(parkingConfig.getIp() + ":8081/cloud/shopmember/create", "POST", map);
        Integer state = jsonObject.getInt("state");
        if (state != 1) {
            throw new Exception("创建负责人失败");
        }
        //2、查询负责人
        HashMap<String, Object> map1 = new HashMap<>();
        map.put("shop_id", parkingMerchant.getMerchantNo());
        net.sf.json.JSONObject jsonObject1 = parkApiUtil.httpRequestSecond(parkingConfig.getIp() + ":8081/cloud/shopmember/quickquery", "POST", map);
        JSONArray jsonArray = jsonObject1.getJSONArray("rows");
        if (jsonArray.size() == 0) {
            throw new Exception("创建负责人失败");
        }
        String operatorNo = null;
        String operatorPassword = null;
        for (Object object : jsonArray) {
            Map<String, Object> merchantMap = (Map) object;
            operatorNo = String.valueOf(merchantMap.get("id"));
            operatorPassword = (String) merchantMap.get("password");
            break;
        }
        if (StringUtils.isBlank(operatorNo) || StringUtils.isBlank(operatorPassword)) {
            throw new Exception("创建负责人失败");
        }
        parkingMerchant.setOperatorNo(operatorNo);
        parkingMerchant.setOperatorPassword(operatorPassword);

        update(parkingMerchant);

    }

    @Override
    public void giveReductionTicket(ParkingMerchant parkingMerchant) throws Exception {
        List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(parkingMerchant.getCompanyId());
        if (parkingInfoList.size() == 0) {
            throw new Exception("创建优惠券失败");
        }
        Long parkId = parkingInfoList.get(0).getParkId();

        HashMap<String, Object> map = new HashMap<>();
        map.put("parkid", parkId);
        map.put("shop_id", parkingMerchant.getMerchantNo());
        map.put("operator", parkingMerchant.getOperatorNo());
        map.put("ticketfree_limit", 0);
        map.put("addmoney", 99999999);
        map.put("ticket_money", 99999999);
        map.put("nowTime", new Date().getTime());
        net.sf.json.JSONObject jsonObject = parkApiUtil.httpRequestSecond(parkingConfig.getIp() + ":8081/cloud/shop/addmoney", "POST", map);
        Integer state = jsonObject.getInt("state");
        if (state != 1) {
            throw new Exception("创建优惠券失败");
        }

    }

    @Override
    public String createReductionTicket(String carNumber, ParkingMerchant parkingMerchant) throws Exception {
        List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(parkingMerchant.getCompanyId());
        if (parkingInfoList.size() == 0) {
            throw new Exception("生成优惠券失败");
        }
        Long parkId = parkingInfoList.get(0).getParkId();

        HashMap<String, Object> map = new HashMap<>();
        map.put("parkid", parkId);
        map.put("loginuin", parkingMerchant.getOperatorNo());
        map.put("md5pass", Sign.MD5(parkingMerchant.getOperatorPassword()));
        map.put("type", parkingMerchant.getType());
        map.put("reduce", parkingMerchant.getReduce());
        map.put("validateDate", DateUtil.format(DateUtil.offsetHour(new Date(), 24), "yyyy-MM-dd HH:mm:ss"));
        map.put("remark", "");
        net.sf.json.JSONObject jsonObject = parkApiUtil.httpRequestSecond(parkingConfig.getInterfaceUrl() + "/zld/createTicketByApi", "POST", map);
        Integer state = jsonObject.getInt("state");
        if (state != 1) {
            throw new Exception(jsonObject.getString("errmsg"));
        }

        String url = jsonObject.getString("code_url");
        Integer index = url.lastIndexOf("/");

        String code = url.substring(index + 1);
        return code;
    }

    @Override
    public void useReductionTicket(String carNumber, String code, ParkingMerchant parkingMerchant) throws Exception {
        List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(parkingMerchant.getCompanyId());
        if (parkingInfoList.size() == 0) {
            throw new Exception("使用优惠券失败");
        }
        Long parkId = parkingInfoList.get(0).getParkId();

        HashMap<String, Object> map = new HashMap<>();
        map.put("parkid", parkId);
        map.put("code", code);
        map.put("carNumber", carNumber);
        net.sf.json.JSONObject jsonObject = parkApiUtil.httpRequestSecond(parkingConfig.getInterfaceUrl() + "/zld/useTicket", "POST", map);
        Integer state = jsonObject.getInt("state");
        if (state != 1) {
            throw new Exception("使用优惠券失败");
        }

    }
}