package com.jzdsh.auto.biz;

import com.jfinal.aop.Inject;
import com.jzdsh.auto.model.*;
import com.jzdsh.util.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @ProjectName: auto
 * @Package: com.jzdsh.auto.biz
 * @ClassName: ShopService
 * @Author: Jzdsh
 * @Description: 店铺信息
 * @Date: 2020/3/21 13:52
 * @Version: 1.0
 */
@Log4j2
public class ShopService {

    @Inject
    NoticeService noticeService;

    @Inject
    UserInfoService userInfoService;

    @Inject
    ServiceCategoryService categoryService;

    @Inject
    ShopService shopService;

    @Inject
    CouponService couponService;

    @Inject
    CouponSetService couponSetService;

    @Inject
    SearchProviderService searchProviderService;

    @Inject
    SearchDealerService searchDealerService;

    @Inject
    BrandFourSService brandFourSService;

    @Inject
    CarCommercialService carCommercialService;

    @Inject
    CarSendanService carSendanService;

    @Inject
    VerifyCodeService verifyCodeService;

    @Inject
    SmsLogService smsLogService;


    public Shop getByUserId(Integer userId) {
        try {
            return Shop.dao.findFirst("select * from shop where userId = ?", userId);
        } catch (Exception e) {
            log.info("com.jzdsh.auto.biz.ShopService.findByUserId" + e);
        }
        return null;
    }


    public List< Shop > findBySearchName(String longitude, String latitude, int pageNum, int pageSize) {
        Integer offset = (pageNum - 1) * pageSize;
        try {
            return Shop.dao.template("shop.listshop", longitude, latitude, offset, pageSize).find( );
        } catch (Exception e) {
            log.info(e);
        }
        return null;
    }

    /**
     * 免费入住
     *
     * @param token
     * @param role
     * @param coName
     * @param name
     * @param city
     * @param street
     * @param mainBusiness
     * @param pMainBusiness
     * @param introduce
     * @param authPhone
     * @param referrerPhone
     * @return
     */
    public Api save(String token, String role, String coName, String name, String city, String street, String houseNumber, String mainBusiness, String pMainBusiness, String introduce, String authPhone, String referrerPhone, String paramType) {
        try {
            Shop shop = new Shop( );
            if (StringUtils.isBlank(role)) {
                role = CommonCons.ROLE_ONE + "";
            }
            UserInfo userInfo = userInfoService.getByToken(token);
            userInfo.setRole(role);
            userInfo.update( );

            Shop reShop = shopService.getByUserId(userInfo.getId( ));
            if (reShop != null) {
                reShop.update( );
                String str = "亲~ 您已获得优惠券!";
                return Api.fail(str);
            }
            //lc 20191018 增加优惠券
            couponService.saveCommonAndSharerCoupon(userInfo.getId( ), token);

            //去掉推荐人手机号 的所有空格
            if (StringUtils.isNotBlank(referrerPhone)) {
                referrerPhone = referrerPhone.replace(" ", "");
            }
            shop.setCode(getShopCode( ));
            shop.setRole(role);
            shop.setCoName(coName);
            shop.setName(name);
            shop.setMainBusiness(mainBusiness);
            shop.setPMainBusiness(pMainBusiness);
            shop.setIntroduce(introduce);
            shop.setAuthPhone(authPhone.trim( ));
            shop.setReferrerPhone(referrerPhone);
            //判断省市县不等空
            String address = "";
            if (StringUtils.isNotBlank(city)) {
                String[] split = city.split(",+");
                shop.setProvince(split[0]);
                shop.setCity(split[1]);
                shop.setDistrict(split[2]);
                //总地址 =  省+ 市 + 县 + 街道 + 门牌号
                address = city.replace(",", "") + street + houseNumber;
                String longitudeAndLatitude = MapUtils.getLongitudeLatitude(city.replace(",", "") + street);
                //根据地址 算出经纬度
                if (StringUtils.isNotBlank(longitudeAndLatitude)) {
                    String[] splits = longitudeAndLatitude.split(",+");
                    shop.setLongitude(splits[0]);
                    shop.setLatitude(splits[1]);
                } else {
                    shop.setLongitude(0 + "");
                    shop.setLatitude(0 + "");
                }
            }
            shop.setStreet(street);
            shop.setAddress(address);
            shop.setHouseNum(houseNumber);
            //是否上架  默认是上架的
            shop.setIsShelf(CommonCons.ONE);
            //入驻时间
            shop.setEnterTime(new Date( ));
            //认证状态 0未认证 1认证
            shop.setStatus(CommonCons.PROVIDER_STATUS_ZERO);
            shop.setCreateTime(new Date( ));
            shop.setRole(role);
            shop.setIsHot(CommonCons.PROVIDER_IS_HOT_ZERO);
            shop.setIsUse(CommonCons.PROVIDER_IS_USE_ONE);
            shop.setIsLine(CommonCons.ZERO);
            // 一些默认值
            shop.setStartWeek("周一");
            shop.setEndWeek("周五");
            shop.setStartTime("09:00");
            shop.setEndTime("17:00");

            if (StringUtils.isNotBlank(userInfo.getImg( ))) {
                //微信头像
                shop.setLogo(CommonUtil.wxImgSave(userInfo.getImg( )));
            } else {
                //默认logo图
                shop.setLogo(CommonCons.DEFAULT_STORE_LOGO);
            }
            //默认banner
            shop.setBanner(CommonCons.DEFAULT_STORE_BANNER);
            shop.setParamType(paramType);

            //添加 搜索表数据
            boolean roleT = CommonCons.ROLE_TWO.equals(role) && ("1".equals(paramType) || "3".equals(paramType) || "4".equals(paramType) || "5".equals(paramType));

            if (roleT) {
                ArrayList< String > pmList = new ArrayList<>( );
                if (StringUtils.isNotBlank(shop.getPMainBusiness( ))) {
                    String[] split = shop.getPMainBusiness( ).split(",");
                    for (String pmName : split) {
                        ServiceCategory pmObj = categoryService.getByNameRole(pmName, CommonCons.ROLE_TWO);
                        pmList.add(pmObj.getId( ) + "");
                    }
                }

                String[] split = shop.getMainBusiness( ).split(",");
                String sb = "";
                for (int i = 0; i < pmList.size( ); i++) {
                    for (String s : split) {
                        if (s.startsWith(pmList.get(i))) {
                            sb += (s.substring(pmList.get(i).length( ))) + ",";
                        }
                    }
                    sb = sb.substring(0, sb.lastIndexOf(","));
                    sb += ";";
                }
                shop.setMainBusiness(sb);

            }

            if (Objects.equals(CommonCons.ROLE_ONE, role)) {
                if (Objects.equals("1", paramType)) {
                    //企业类型 （以下都是默认值）
                    shop.setCoType("快修连锁店");
                    // 经营资质
                    shop.setIntelligence("三类");
                    //主营品牌
                    shop.setMainBrand("各种车型");
                } else if (Objects.equals("2", paramType)) {
                    //企业类型
                    shop.setCoType("综合修理厂");
                    // 经营资质
                    shop.setIntelligence("二类");
                } else if (Objects.equals("3", paramType)) {
                    //企业类型
                    shop.setCoType("品牌4S店");
                    // 经营资质
                    shop.setIntelligence("二类");
                    //主营品牌
                    shop.setMainBrand("专营车型");
                }
            }
            //默认是前台加入
            shop.setIsImport(CommonCons.ZERO);

            shop.save( );

            //添加公告信息
            noticeService.save(shop.getId( ), shop.getName( ), shop.getProvince( ), shop.getCity( ), shop.getDistrict( ));
            //加到搜索信息中
            threadExec(shop.getRole( ), shop.getId( ), paramType, shop.getPMainBusiness( ), shop.getMainBusiness( ));

            CouponSet couponSet = couponSetService.getByTypeUsed(CommonCons.ONE, CommonCons.COUPON_SET_TYPE_ZERO);
            String validity = Optional.ofNullable(couponSet.getValidity( )).orElse("12");
            String validityTime = LocalDate.now( ).plusMonths(Integer.valueOf(validity)).toString( );
            HashMap< Object, Object > map = new HashMap<>( );
            map.put("money", couponSet.getMoney( ) + "元优惠券");
            map.put("validityTime", "有效期至" + validityTime);

            return Api.ok(map);
        } catch (NumberFormatException e) {
            log.info("", e);
        }
        return Api.fail(null);
    }


    /**
     * 添加搜索信息执行的action
     *
     * @param roleType
     * @param shopId
     * @param paramType
     * @param pMainBusiness
     * @param mainBusiness
     */
    private void threadExec(String roleType, int shopId, String paramType, String pMainBusiness, String mainBusiness) {
        try {
            //服务商的时候

            if (Objects.equals(CommonCons.ROLE_ONE, roleType) && StringUtils.isNotBlank(mainBusiness)) {
                ScheduledThreadPoolExecutor poolExecutor = new ScheduledThreadPoolExecutor(1);
                poolExecutor.execute(( ) -> {
                    // 1 代表 小型汽车 ,2服务商用车专修
                    if ("1".equals(paramType) || "2".equals(paramType)) {
                        smallCarSave(shopId, pMainBusiness, mainBusiness, paramType);
                    }
                    // 4s 店
                    if ("3".equals(paramType)) {
                        fourS_save(shopId, mainBusiness, pMainBusiness);
                    }
                });

            }

            //当是经销商的时候   添加经销商搜索
            if (Objects.equals(CommonCons.ROLE_TWO, roleType) && StringUtils.isNotBlank(mainBusiness)) {
                ScheduledThreadPoolExecutor poolExecutor = new ScheduledThreadPoolExecutor(1);
                poolExecutor.execute(( ) -> {
                    // 1,3,4,5 代表是 普通类型 1汽配(单项件),2汽配(全车件) ,3用品改装,4汽保设备与工具,5商用车(单项件) 6商用车(全车件)
                    if ("1".equals(paramType) || "3".equals(paramType) || "4".equals(paramType) || "5".equals(paramType)) {
                        saveSearchDealer(paramType, shopId, pMainBusiness, mainBusiness);
                    }
                    //  2 代表全车件
                    if ("2".equals(paramType)) {
                        saveAllCar(shopId, pMainBusiness, mainBusiness);
                    }
                    // 6 代表商务车
                    if ("6".equals(paramType)) {
                        saveCommercial(shopId, pMainBusiness, mainBusiness);
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace( );
        }
        return;
    }

    /**
     * 小型车 商用车专修
     *
     * @param shopId
     * @param pMainBusiness
     * @param mainBusiness
     * @param paramType
     */
    private void smallCarSave(int shopId, String pMainBusiness, String mainBusiness, String paramType) {

        if (StringUtils.isBlank(pMainBusiness) || StringUtils.isBlank(mainBusiness)) {
            return;
        }
        try {
            Set< SearchProvider > spList = new HashSet<>( );
            String[] pMains = pMainBusiness.split(",");
            String[] mains = mainBusiness.split(",");
            List< String > mainList = Arrays.asList(mains);

            if (pMains.length > 0) {
                for (String main : pMains) {
                    int role = CommonCons.ROLE_ONE;
                    if ("道路救援".equals(main)) {
                        role = 3;
                    }
                    ServiceCategory category = categoryService.getByNameRole(main, role);
                    if (category != null) {
                        List< String > namesList = categoryService.getByPid(category.getId( ));
                        if (mainList != null && mainList.size( ) > 0) {
                            for (String name : mainList) {
                                if (namesList.contains(name)) {
                                    SearchProvider sp = new SearchProvider( );
                                    sp.setLevel("1");
                                    sp.setPName(main);
                                    sp.setName(name);
                                    sp.setShopId(shopId);
                                    sp.setType(paramType);
                                    spList.add(sp);
                                }
                            }
                        }
                    }

                    {
                        SearchProvider sp = new SearchProvider( );
                        sp.setLevel("2");
                        sp.setPName(main);
                        sp.setName(main);
                        sp.setShopId(shopId);
                        sp.setType(paramType);
                        spList.add(sp);
                    }
                    {
                        if (Objects.equals("2", paramType)) {
                            SearchProvider sp = new SearchProvider( );
                            sp.setLevel("3");
                            sp.setPName("商用车专修");
                            sp.setName("商用车专修");
                            sp.setShopId(shopId);
                            sp.setType(paramType);
                            spList.add(sp);
                        }
                    }
                }
            }
            List< SearchProvider > listSet = new ArrayList<>( );
            listSet.addAll(spList);
            // 有数据可添加
            if (listSet.size( ) > 0) {
                //先删除
                searchProviderService.deleteByShopId(shopId);
                searchProviderService.saveList(listSet);
            }
        } catch (Exception e) {
            log.info("", e);
        }
    }

    public void fourS_save(int shopId, String brand, String mainBusiness) {
        if (StringUtils.isBlank(mainBusiness) || StringUtils.isBlank(brand)) {
            return;
        }
        try {
            String[] split = mainBusiness.split(",");
            String[] split1 = brand.split(",");
            Set< SearchProvider > spList = new HashSet<>( );

            int i = 0;
            for (String factory : split) {
                BrandFourS brandFourS = brandFourSService.getByBrandFactory(split1[i], factory);
                if (brandFourS != null) {
                    SearchProvider sp = new SearchProvider( );
                    sp.setLevel("1");
                    sp.setPName(brandFourS.getBrand( ));
                    sp.setName(brandFourS.getFactory( ));
                    sp.setShopId(shopId);
                    sp.setType("3");
                    spList.add(sp);

                    SearchProvider sp1 = new SearchProvider( );
                    sp1.setLevel("2");
                    sp1.setPName(brandFourS.getBrand( ));
                    sp1.setName(brandFourS.getBrand( ));
                    sp1.setShopId(shopId);
                    sp1.setType("3");
                    spList.add(sp1);

                    SearchProvider sp2 = new SearchProvider( );
                    sp2.setLevel("3");
                    sp2.setPName(brandFourS.getBrand( ));
                    sp2.setName(brandFourS.getCategory( ));
                    sp2.setShopId(shopId);
                    sp2.setType("3");
                    spList.add(sp2);

                    SearchProvider sp3 = new SearchProvider( );
                    sp3.setLevel("4");
                    sp3.setPName(brandFourS.getBrand( ));
                    sp3.setName("4S店");
                    sp3.setShopId(shopId);
                    sp3.setType("3");
                    spList.add(sp3);
                }
                i++;
            }

            List< SearchProvider > listSet = new ArrayList<>( );
            listSet.addAll(spList);
            if (listSet.size( ) > 0) {
                searchProviderService.deleteByShopId(shopId);
                searchProviderService.saveList(listSet);
            }
        } catch (Exception e) {
            log.info("", e);
        }
    }


    /**
     * @param paramType
     * @param shopId
     * @param pMainBusiness
     * @param mainBusiness
     */
    public void saveSearchDealer(String paramType, Integer shopId, String pMainBusiness, String mainBusiness) {

        if (null == shopId || StringUtils.isBlank(mainBusiness) || StringUtils.isBlank(pMainBusiness)) {
            return;
        }
        String pName;
        //1汽配(单项件),2汽配(全车件) ,3用品改装,4汽保设备与工具,5商用车(单项件) 6商用车(全车件)
        Set< SearchDealer > list = new HashSet<>( );
        String[] split = mainBusiness.split(";+");
        String[] split1 = pMainBusiness.split(",");

        int i = 0;
        for (String s : split) {
            pName = split1[i];
            String[] split2 = s.split(",");
            if (split2.length > 0) {
                for (int k = 0; k < split2.length; k++) {
                    String s1 = split2[k];
                    if (s1.length( ) == 0) {
                        continue;
                    }
                    SearchDealer searchDealer = new SearchDealer( );
                    searchDealer.setShopId(shopId);
                    searchDealer.setName(s1);
                    searchDealer.setLevel("1");
                    searchDealer.setType(paramType);
                    searchDealer.setPName(pName);
                    list.add(searchDealer);
                }
            }
            i++;
        }

        int j = 0;
        if (StringUtils.isNotBlank(pMainBusiness)) {

            for (String s : split1) {
                pName = split1[j];
                SearchDealer searchDealer = new SearchDealer( );
                searchDealer.setShopId(shopId);
                searchDealer.setName(s);
                searchDealer.setLevel("2");
                searchDealer.setType(paramType);
                searchDealer.setPName(pName);
                list.add(searchDealer);
                j++;
            }
        }

        String name = "";
        String psName = "";
        if ("1".equals(paramType)) {
            name = "单项件";
            psName = "汽车配件";
        }
        if ("5".equals(paramType)) {
            name = "单项件";
            psName = "商用车";
        }

        if ("3".equals(paramType)) {
            name = "用品改装";
            psName = "用品改装";
        }

        if ("4".equals(paramType)) {
            name = "汽保设备与工具";
            psName = "汽保设备与工具";
        }
        {
            SearchDealer searchDealer = new SearchDealer( );
            searchDealer.setShopId(shopId);
            searchDealer.setName(name);
            searchDealer.setLevel("3");
            searchDealer.setType(paramType);
            searchDealer.setPName(psName);
            list.add(searchDealer);
        }

        {
            SearchDealer searchDealer = new SearchDealer( );
            searchDealer.setShopId(shopId);
            searchDealer.setName(psName);
            searchDealer.setLevel("4");
            searchDealer.setType(paramType);
            searchDealer.setPName(psName);
            list.add(searchDealer);
        }

        ArrayList< SearchDealer > listSet = new ArrayList<>( );
        listSet.addAll(list);
        if (listSet.size( ) > 0) {
            //先删除 在增加
            searchDealerService.deleteByShopId(shopId);
            searchDealerService.saveList(listSet);
        }

    }


    /**
     * 小型车保存
     *
     * @param shopId
     * @param pMainBusiness
     * @param mainBusiness
     */
    public void saveAllCar(Integer shopId, String pMainBusiness, String mainBusiness) {
        if (null == shopId || StringUtils.isBlank(mainBusiness)) {
            return;
        }

        try {
            String[] split = pMainBusiness.split(",+");
            String[] rBrand = mainBusiness.split(",+");

            List< String > brand = carSendanService.getGroupBrand( );
            List< String > factorys = carSendanService.getGroupFactory( );
            List< String > series = carSendanService.getGroupSeries( );
            Set< SearchDealer > list = new HashSet<>( );

            int ii = 0;

            for (String name : split) {
                name = name.trim( );
                String bd = rBrand[ii].trim( );
                if (brand != null && brand.contains(name)) {
                    List< CarSedan > carSedanList = carSendanService.getByBrand(bd);
                    for (CarSedan carSedan : carSedanList) {
                        repeatSaveList(list, carSedan, bd, shopId);
                    }

                } else if (factorys != null && factorys.contains(name)) {
                    List< CarSedan > carSedanList = carSendanService.getByBrandFactory(bd, name);
                    if (carSedanList != null && carSedanList.size( ) > 0) {
                        for (CarSedan carSedan : carSedanList) {
                            repeatSaveList(list, carSedan, bd, shopId);
                        }
                    }
                } else if (series != null && series.contains(name)) {

                    List< CarSedan > carSedanList = carSendanService.getByBrandSeries(bd, name);
                    if (carSedanList != null && carSedanList.size( ) > 0) {
                        for (CarSedan carSedan : carSedanList) {
                            repeatSaveList(list, carSedan, bd, shopId);
                            repeatSave(list, bd, carSedan.getFactory( ), carSedan.getSeries( ), shopId, "1", "2");
                        }
                    }
                }
                ii++;
            }
            List< SearchDealer > listSet = new ArrayList<>( );
            listSet.addAll(list);
            if (listSet.size( ) > 0) {
                searchDealerService.deleteByShopId(shopId);
                searchDealerService.saveList(listSet);
            }
        } catch (Exception e) {
            log.info("", e);
        }
    }


    /**
     * 商用车保存
     *
     * @param shopId
     * @param pMainBusiness
     * @param mainBusiness
     */
    public void saveCommercial(Integer shopId, String pMainBusiness, String mainBusiness) {
        if (null == shopId || StringUtils.isBlank(mainBusiness)) {
            return;
        }
        try {
            Set< SearchDealer > list = new HashSet<>( );

            List< String > brandList = carCommercialService.getGroupBrand( );

            List< String > factorList = carCommercialService.getGroupFactory( );

            //这个操作时间 太长 所以加入到缓存
            List< String > salesVersionList;
            if (CommonUtil.getCache("listSalenversionGroupBySalenversion") != null) {
                salesVersionList = (List< String >) CommonUtil.getCache("listSalenversionGroupBySalenversion");
            } else {
                salesVersionList = carCommercialService.getGroupSaleVersion( );
                CommonUtil.setCache("listSalenversionGroupBySalenversion", salesVersionList);
            }


            String[] split = pMainBusiness.split(",+");
            String[] brand = mainBusiness.split(",+");
            int i = 0;
            for (String name : split) {
                name = name.trim( );
                String bd = brand[i];
                //当选择品牌的时候
                if (brandList != null && brandList.contains(name)) {
                    List< CarCommercial > carCommercials = carCommercialService.getByBrand(bd);
                    if (carCommercials != null && carCommercials.size( ) > 0) {
                        for (CarCommercial carCommercial : carCommercials) {
                            repeatSaveList(list, carCommercial, bd, shopId);
                        }
                    }
                    //当选择厂家的时候
                } else if (factorList != null && factorList.contains(name)) {
                    List< CarCommercial > carCommercialList = carCommercialService.getByBrandFactory(bd, name);
                    if (carCommercialList != null && carCommercialList.size( ) > 0) {
                        for (CarCommercial carCommercial : carCommercialList) {
                            repeatSaveList(list, carCommercial, bd, shopId);
                        }
                    }
                    //当选择销售版本的时候
                } else if (salesVersionList != null && salesVersionList.contains(name)) {
                    List< CarCommercial > carCommercialList = carCommercialService.getByBrandSaleversion(bd, name);
                    // 1汽配(单项件),2汽配(全车件) ,3用品改装,4汽保设备与工具,5商用车(单项件) 6商用车(全车件)
                    if (carCommercialList != null && carCommercialList.size( ) > 0) {
                        for (CarCommercial carCommercial : carCommercialList) {
                            repeatSaveList(list, carCommercial, bd, shopId);
                            repeatSave(list, bd, carCommercial.getFactory( ), carCommercial.getSaleVersion( ), shopId, "1", "6");
                        }
                    }
                }
                i++;
            }
            //去重
            List< SearchDealer > listSet = new ArrayList<>( );
            listSet.addAll(list);
            if (listSet.size( ) > 0) {
                searchDealerService.deleteByShopId(shopId);
                searchDealerService.saveList(listSet);
            }
        } catch (Exception e) {
            log.info("", e);
        }
    }


    private Set repeatSave(Set list, String brand, String factory, String name, Integer shopId, String level, String type) {
        SearchDealer sd = new SearchDealer( );
        sd.setPName(brand + "-" + factory);
        sd.setName(name);
        sd.setShopId(shopId);
        sd.setLevel(level);
        sd.setType(type);
        list.add(sd);
        return list;
    }

    private void repeatSaveList(Set list, Object obj, String bd, Integer shopId) {

        if (obj instanceof CarCommercial) {
            CarCommercial carCommercial = (CarCommercial) obj;
            String factory = carCommercial.getFactory( );
            String category = carCommercial.getCategory( );
            repeatSave(list, bd, factory, "商用车", shopId, "5", "6");
            repeatSave(list, bd, factory, category, shopId, "4", "6");
            repeatSave(list, bd, factory, bd, shopId, "3", "6");
            repeatSave(list, bd, factory, factory, shopId, "2", "6");
        }

        if (obj instanceof CarSedan) {
            CarSedan carSedan = (CarSedan) obj;
            String factory = carSedan.getFactory( );
            String country = carSedan.getCountry( );
            repeatSave(list, bd, factory, "汽车配件", shopId, "5", "2");
            repeatSave(list, bd, factory, country, shopId, "4", "2");
            repeatSave(list, bd, factory, bd, shopId, "3", "2");
            repeatSave(list, bd, factory, factory, shopId, "2", "2");
        }


    }

    /**
     * 获取唯一店铺code
     *
     * @return
     */
    public String getShopCode( ) {
        String code = CommonUtil.getRandom(8);
        Shop shop = Shop.dao.findFirst("select * from shop where code = ?", code);
        if (shop == null) {
            return code;
        } else {
            return getShopCode( );
        }
    }


    public Api sendSMS(String phone) {

        if (StringUtils.isBlank(phone)) {
            return Api.fail("手机号码不能为空");
        }
        phone = phone.trim( );
        try {
            // 如果该手机 已有店铺  就提示不发送验证码
            Shop shop = getByAuthPhone(phone);
            if (shop != null) {
                if (CommonCons.ROLE_ONE.equals(shop.getRole( ))) {
                    return Api.fail("该手机号码已被服务商[" + shop.getName( ) + "]使用");
                } else {
                    return Api.fail("该手机号码已被经销商[" + shop.getName( ) + "]使用");
                }
            }
            //6位验证码
            String sendCoeds = CommonUtil.getRandom(6);
            String templateCode = "SMS_177547615";
            String paramString = "{\"code\":\"" + sendCoeds + "\"}";
            boolean status = HttpSender.sendSms("附近养车网", templateCode, phone, paramString);

            //短信保存到数据库中
            VerifyCode verify = verifyCodeService.getByPhone(phone);
            if (verify == null) {
                VerifyCode verifyCode = new VerifyCode( );
                verifyCode.setCode(sendCoeds);
                verifyCode.setSendTime(new Date( ));
                verifyCode.setPhone(phone);
                verifyCode.save( );
            } else {
                verify.setSendTime(new Date( ));
                verify.setCode(sendCoeds);
                verify.update( );
            }

            if (status) {
                return Api.ok("短信发送成功");
            } else {
                return Api.fail("短信限制5条/时,10条/天");
            }
        } catch (Exception e) {
            log.info("", e);
        }
        return Api.fail(null);
    }


    /**
     * 根据认证电话查询
     *
     * @param phone
     * @return
     */
    public Shop getByAuthPhone(String phone) {
        try {
            return Shop.dao.findFirst("select * from shop where authPhone = ? and userId is not null ", phone);
        } catch (Exception e) {
            log.info("", e);
        }
        return null;
    }

    /**
     * 用户绑定
     * 判断 用户 是否 认领操作还是免费入驻操作
     *
     * @param token
     * @param phone  手机号
     * @param code   验证码
     * @param isSave 是否保存手机号操作  true/false (个人中心修改手机号用)
     * @return
     */
    public Api userBinding(String token, String phone, String code, String role, Boolean isSave) {
        if (StringUtils.isBlank(token)) {
            return Api.fail("token不能为空");
        }
        if (StringUtils.isBlank(phone)) {
            return Api.fail("电话号不能为空");
        }
        if (StringUtils.isBlank(code)) {
            return Api.fail("验证码不能为空");
        }


        VerifyCode oneByPhone = verifyCodeService.getByPhone(phone);
        if (oneByPhone == null) {
            return Api.fail("该手机号验证码为空,请重新发送！");
        }

        if (oneByPhone != null) {
            long time = oneByPhone.getSendTime( ).getTime( ) / 1000;
            long nowTime = System.currentTimeMillis( ) / 1000;
            //有效期180秒5分钟
            if (nowTime - time > 180) {
                return Api.fail("验证码已过期,请重新发信验证码!");
            }
        }
        String codeNumber = oneByPhone.getCode( );
        String phoneNumber = oneByPhone.getPhone( );


        if (phone != null && !"".equals(phone) && code != null && !"".equals(code)) {
            try {
                if (codeNumber == null) {
                    return Api.fail("验证码已过期");
                }
                if (!codeNumber.equals(code)) {
                    return Api.fail("验证码错误，请您核对验证码");
                }
                if (!Objects.equals(phone, phoneNumber)) {
                    return Api.fail("手机号码与验证码接收号码不符合");
                } else {
                    if (isSave) {

                        UserInfo userInfo = userInfoService.getByToken(token);
                        smsLogService.saveLog(userInfo.getId( ), userInfo.getNickName( ), code);
                        Shop shop = getByUserId(userInfo.getId( ));
                        userInfo.setPhone(phone);
                        userInfo.update( );
                        //更新 店铺信息 ，将店铺和这个商家联系起来
                        shop.setAuthPhone(phone);
                        shop.setIsUse(CommonCons.PROVIDER_IS_USE_ONE);//启用店铺
                        shop.update( );
                        return Api.ok("更新成功!");
                    } else {
                        return getAuthInfo(token, phone, code, role);
                    }
                }
            } catch (Exception e) {
                log.error("服务商用户绑定 错误！", e);
            }
        } else {
            return Api.fail("手机号或者验证码不能为空");
        }
        return Api.fail(null);
    }


    private Api getAuthInfo(String token, String phone, String code, String roleType) {
        UserInfo userInfo = userInfoService.getByToken(token);
        if (userInfo == null) {
            return Api.fail("没有找到该用户信息！");
        }
        //短信日志
        smsLogService.saveLog(userInfo.getId( ), userInfo.getNickName( ), code);
        Shop shop = shopService.getByAuthPhoneRole(phone, roleType);
        userInfo.setPhone(phone);
        userInfo.update( );


        HashMap< String, Object > map = new HashMap<>( );
        if (shop != null) {
            //证明是认领，认领时该店铺没有关联用户
            if (shop.getUserId( ) == null) {
                userInfo.setPhone(shop.getAuthPhone( ));
                userInfo.setRole(roleType);
                userInfo.update( );
                //更新 店铺信息 ，将店铺和这个商家联系起来
                shop.setRole(roleType);
                shop.setUserId(userInfo.getId( ));
                //启用店铺
                shop.setIsUse(CommonCons.PROVIDER_IS_USE_ONE);
                shop.update( );
                //给一张优惠券
                //lc 20191018 增送一张优惠券
                couponService.saveCommonAndSharerCoupon(userInfo.getId( ), userInfo.getToken( ));
            } else if (shop.getUserId( ) != null && !userInfo.getId( ).equals(shop.getUserId( ))) {
                return Api.fail("该手机号已有店铺在使用,请修改！");
            } else if (shop.getUserId( ) != null && userInfo.getId( ).equals(shop.getUserId( ))) {
                userInfo.setPhone(phone);
                userInfo.update( );
                shop.setAuthPhone(phone);
                //启用店铺
                shop.setIsUse(CommonCons.PROVIDER_IS_USE_ONE);
                shop.update( );
            }

            map.put("userInfo", userInfo);
            map.put("provider", shop);
            // 0不存在，1存在该店铺
            map.put("exist", "1");
            return Api.ok(map);
        } else {
            map.put("userInfo", userInfo);
            map.put("exist", "0");
            return Api.ok(map);
        }

    }

    public Shop getByAuthPhoneRole(String phone, String role) {
        try {
            return Shop.dao.findFirst("select * from shop where authPhone = ? and role = ?", phone, role);
        } catch (Exception e) {
            log.info("", e);
        }
        return null;
    }
}
