package com.slodon.b2b2c.controller.seller.seller;

import com.slodon.b2b2c.aop.VendorLogger;
import com.slodon.b2b2c.core.constant.StoreConst;
import com.slodon.b2b2c.core.constant.VendorConst;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.enums.WebSiteConstant;
import com.slodon.b2b2c.goods.example.GoodsCategoryExample;
import com.slodon.b2b2c.goods.pojo.GoodsCategory;
import com.slodon.b2b2c.model.goods.GoodsCategoryModel;
import com.slodon.b2b2c.model.seller.*;
import com.slodon.b2b2c.model.system.SettingModel;
import com.slodon.b2b2c.seller.dto.StoreApplyDTO;
import com.slodon.b2b2c.seller.example.*;
import com.slodon.b2b2c.seller.pojo.*;
import com.slodon.b2b2c.starter.redisson.SlodonLock;
import com.slodon.b2b2c.system.pojo.Setting;
import com.slodon.b2b2c.vo.seller.ProcessVO;
import com.slodon.b2b2c.vo.seller.StoreApplyDetailVO;
import com.slodon.b2b2c.vo.seller.StoreGoodsCateVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author slodon
 */
@Api(tags = "seller-商户入驻申请相关接口")
@RestController
@RequestMapping("v3/seller/seller/apply")
public class SellerApplyController extends BaseController {

    @Resource
    private StoreApplyModel storeApplyModel;
    @Resource
    private StoreNameModel storeNameModel;
    @Resource
    private StoreCertificateModel storeCertificateModel;
    @Resource
    private StoreGradeModel storeGradeModel;
    @Resource
    private StoreBindCategoryModel storeBindCategoryModel;
    @Resource
    private GoodsCategoryModel goodsCategoryModel;
    @Resource
    private VendorModel vendorModel;
    @Resource
    private SlodonLock slodonLock;
    @Resource
    private SettingModel settingModel;

    @ApiOperation("保存入驻信息")
    @VendorLogger(option = "保存入驻信息")
    @PostMapping("saveApply")
    public JsonResult<Object> saveApply(HttpServletRequest request, @RequestBody StoreApplyDTO storeApplyDTO) throws Exception {
        String logMsg = "店铺名称" + storeApplyDTO.getSiteInfoList().get(0).getStoreName();
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        //对商户加锁，防止同一商户在重复申请商家
        String vendorLockKey = "vendor-" + vendor.getVendorId();
        slodonLock.lock(vendorLockKey);
        try {
            AssertUtil.isTrue(storeApplyDTO.getEnterType() == StoreConst.APPLY_TYPE_COMPANY
                    && StringUtils.isEmpty(storeApplyDTO.getCompanyName()), "请填写公司名称");

            //判断手机号是否重复
            VendorExample vendorMobileExample = new VendorExample();
            vendorMobileExample.setVendorMobile(storeApplyDTO.getContactPhone());
            vendorMobileExample.setIsAllowLoginNotEquals(VendorConst.LOGOUT_ALLOW_LOGIN);
            vendorMobileExample.setVendorIdNotEquals(vendor.getVendorId());
            List<Vendor> vendorList = vendorModel.getVendorList(vendorMobileExample, null);

            AssertUtil.isTrue(!CollectionUtils.isEmpty(vendorList), "该手机号已被其他账号绑定，请重新填写");

            //先根据vendorId查询数据库中的申请，判断是否是第一次申请
            StoreApplyExample example = new StoreApplyExample();
            example.setVendorId(vendor.getVendorId());
            List<StoreApply> storeApplies = storeApplyModel.getStoreApplyList(example, null);
            if (!CollectionUtils.isEmpty(storeApplies)) {
                //数据库里已存在该商家的申请，说明是审核失败，重新提交申请
                StoreCertificateExample storeCertificateExample = new StoreCertificateExample();
                storeCertificateExample.setVendorId(vendor.getVendorId());
                List<StoreCertificate> storeCertificateList = storeCertificateModel.getStoreCertificateList(storeCertificateExample, null);
                storeApplyDTO.setCertificateId(storeCertificateList.get(0).getCertificateId());
                storeApplyDTO.setApplyId(storeApplies.get(0).getApplyId());
                //更新申请信息
                storeApplyModel.updateStoreApplyInfo(storeApplyDTO, vendor);
            } else {
                //数据库里没有改用户的申请，插入新的数据
                storeApplyModel.saveStoreApplyInfo(storeApplyDTO, vendor);
            }
        } finally {
            slodonLock.unlock(vendorLockKey);
        }
        return SldResponse.success("申请成功提交", logMsg);
    }

    @ApiOperation("获取开店时长列表")
    @GetMapping("openTime")
    public JsonResult<Object> openTime(HttpServletRequest request) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        return SldResponse.success(Arrays.asList(1, 2, 3));
    }

    @ApiOperation("获取审核进程接口")
    @GetMapping("process")
    public JsonResult<ProcessVO> process(HttpServletRequest request) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        StoreApplyExample storeApplyExample = new StoreApplyExample();
        storeApplyExample.setVendorId(vendor.getVendorId());
        List<StoreApply> storeApplyList = storeApplyModel.getStoreApplyList(storeApplyExample, null);

        ProcessVO vo = new ProcessVO();
        if (CollectionUtils.isEmpty(storeApplyList)) {
            //用户未入驻过
            vo.setApplyStep(0);
            vo.setStateValue("未入驻");
            return SldResponse.success(vo);
        }
        //根据等级id获取等级名称
        StoreGrade storeGrade = storeGradeModel.getStoreGradeByGradeId(storeApplyList.get(0).getStoreGradeId());
        vo = new ProcessVO(storeGrade, storeApplyList.get(0));
        vo.setPrice(storeGrade.getPrice() + "元/年");
        vo.setApplyYear(storeApplyList.get(0).getApplyYear() + "年");
        vo.setPayAmount("￥" + new BigDecimal(storeGrade.getPrice()).multiply(new BigDecimal(storeApplyList.get(0).getApplyYear())));
        //审核状态信息
        if (storeApplyList.get(0).getState() == StoreConst.STATE_1_SEND_APPLY || storeApplyList.get(0).getState() == StoreConst.STATE_2_DONE_APPLY) {
            List<Setting> webSiteList = settingModel.getSiteSetting();

            //待审核或审核通过，支付凭证信息
            //获取经营类目列表
            StoreBindCategoryExample storeBindCategoryExample = new StoreBindCategoryExample();
            storeBindCategoryExample.setCreateVendorId(storeApplyList.get(0).getVendorId());
            List<StoreBindCategory> storeBindCategoryList = storeBindCategoryModel.getStoreBindCategoryList(storeBindCategoryExample, null);

            GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
            List<GoodsCategory> goodsCategoryList = goodsCategoryModel.getGoodsCategoryList(goodsCategoryExample, null);

            List<StoreGoodsCateVO> storeGoodsCateVOList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(storeBindCategoryList)) {
                storeBindCategoryList.forEach(storeBindCategory -> {
                    StoreGoodsCateVO storeGoodsCateVO = new StoreGoodsCateVO(storeBindCategory);
                    storeGoodsCateVO.setWebSiteName(webSiteList.stream().filter(setting -> setting.getValue().equals(storeBindCategory.getWebSite())).findFirst().map(Setting::getTitle).orElse(""));
                    storeGoodsCateVO.setGoodsCateName1(goodsCategoryList.stream().filter(goodsCategory -> goodsCategory.getCategoryId().equals(storeBindCategory.getGoodsCategoryId1())).findFirst().map(GoodsCategory::getCategoryName).orElse(""));
                    storeGoodsCateVO.setGoodsCateName2(goodsCategoryList.stream().filter(goodsCategory -> goodsCategory.getCategoryId().equals(storeBindCategory.getGoodsCategoryId2())).findFirst().map(GoodsCategory::getCategoryName).orElse(""));
                    storeGoodsCateVO.setGoodsCateName3(goodsCategoryList.stream().filter(goodsCategory -> goodsCategory.getCategoryId().equals(storeBindCategory.getGoodsCategoryId3())).findFirst().map(GoodsCategory::getCategoryName).orElse(""));
                    storeGoodsCateVOList.add(storeGoodsCateVO);
                });
                vo.setStoreGoodsCateVOList(storeGoodsCateVOList);
            }
            if (storeApplyList.get(0).getState() == StoreConst.STATE_1_SEND_APPLY) {
                vo.setStateValue("您的申请已提交，平台将在3个工作日内给出审核结果");
            } else {
                vo.setStateValue("您的审核已通过");
            }
        } else if (storeApplyList.get(0).getState() == StoreConst.STATE_3_FAIL_APPLY) {
            vo.setStateValue("您的店铺入驻审核未通过");
        } else {
            vo.setStateValue("恭喜您成功入驻南京江北新区跨境出海服务营销平台");
        }
        return SldResponse.success(vo);
    }

    @ApiOperation("获取入驻详情接口")
    @GetMapping("applyDetail")
    public JsonResult<StoreApplyDetailVO> getDetail(HttpServletRequest request) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        //获取商家申请信息
        StoreApplyExample storeApplyExample = new StoreApplyExample();
        storeApplyExample.setVendorId(vendor.getVendorId());
        StoreApply storeApply = storeApplyModel.getStoreApplyList(storeApplyExample, null).get(0);

        //获取申请资质信息
        StoreCertificateExample storeCertificateExample = new StoreCertificateExample();
        storeCertificateExample.setVendorId(storeApply.getVendorId());
        List<StoreCertificate> storeCertificateList = storeCertificateModel.getStoreCertificateList(storeCertificateExample, null);
        StoreApplyDetailVO vo = new StoreApplyDetailVO(storeApply, storeCertificateList.get(0));

        StoreNameExample storeNameExample = new StoreNameExample();
        storeNameExample.setStoreId(storeApply.getStoreId());
        List<StoreName> storeNameList = storeNameModel.getStoreNameList(storeNameExample, null);

        //根据等级id获取等级名称
        StoreGrade storeGrade = storeGradeModel.getStoreGradeByGradeId(storeApply.getStoreGradeId());
        if (storeGrade != null) {
            vo.setStoreGradeName(storeGrade.getGradeName());
        }

        List<Setting> webSiteList = settingModel.getSiteSetting();

        //获取经营类目信息
        StoreBindCategoryExample storeBindCategoryExample = new StoreBindCategoryExample();
        storeBindCategoryExample.setCreateVendorId(storeApply.getVendorId());
        List<StoreBindCategory> storeBindCategoryList = storeBindCategoryModel.getStoreBindCategoryList(storeBindCategoryExample, null);

        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        List<GoodsCategory> goodsCategoryList = goodsCategoryModel.getGoodsCategoryList(goodsCategoryExample, null);

        List<StoreGoodsCateVO> storeGoodsCateVOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(storeBindCategoryList)) {
            storeBindCategoryList.forEach(storeBindCategory -> {
                StoreGoodsCateVO storeGoodsCateVO = new StoreGoodsCateVO(storeBindCategory);
                if (WebSiteConstant.MEMBER_OVERSEA.equals(storeBindCategory.getWebSite())) {
                    storeGoodsCateVO.setStoreName(storeApply.getStoreName());
                } else {
                    storeGoodsCateVO.setStoreName(storeNameList.stream()
                            .filter(name -> name.getWebSite().equals(storeBindCategory.getWebSite()))
                            .findFirst()
                            .map(StoreName::getStoreName)
                            .orElse(""));
                    storeGoodsCateVO.setId(storeNameList.stream()
                            .filter(name -> name.getWebSite().equals(storeBindCategory.getWebSite()))
                            .findFirst()
                            .map(StoreName::getId)
                            .orElse(null));
                }
                storeGoodsCateVO.setWebSiteName(webSiteList.stream().filter(setting -> setting.getValue().equals(storeBindCategory.getWebSite())).findFirst().map(Setting::getTitle).orElse(""));
                storeGoodsCateVO.setGoodsCateName1(goodsCategoryList.stream().filter(goodsCategory -> goodsCategory.getCategoryId().equals(storeBindCategory.getGoodsCategoryId1())).findFirst().map(GoodsCategory::getCategoryName).orElse(""));
                storeGoodsCateVO.setGoodsCateName2(goodsCategoryList.stream().filter(goodsCategory -> goodsCategory.getCategoryId().equals(storeBindCategory.getGoodsCategoryId2())).findFirst().map(GoodsCategory::getCategoryName).orElse(""));
                storeGoodsCateVO.setGoodsCateName3(goodsCategoryList.stream().filter(goodsCategory -> goodsCategory.getCategoryId().equals(storeBindCategory.getGoodsCategoryId3())).findFirst().map(GoodsCategory::getCategoryName).orElse(""));
                storeGoodsCateVOList.add(storeGoodsCateVO);
            });
            vo.setStoreGoodsCateVOList(storeGoodsCateVOList);
        }
        return SldResponse.success(vo);
    }
}
