package com.slodon.b2b2c.controller.member.front.advich;

import com.alibaba.fastjson.JSON;
import com.slodon.b2b2c.core.constant.EnquiryConst;
import com.slodon.b2b2c.core.constant.MemberConst;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.i18n.Language;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.enums.WebSiteConstant;
import com.slodon.b2b2c.goods.example.GoodsExample;
import com.slodon.b2b2c.goods.pojo.Goods;
import com.slodon.b2b2c.member.example.MemberEnquiryExample;
import com.slodon.b2b2c.member.pojo.Member;
import com.slodon.b2b2c.member.pojo.MemberEnquiry;
import com.slodon.b2b2c.model.goods.GoodsModel;
import com.slodon.b2b2c.model.member.advich.CountryModel;
import com.slodon.b2b2c.model.member.advich.MemberEnquiryModel;
import com.slodon.b2b2c.model.seller.StoreModel;
import com.slodon.b2b2c.model.seller.StoreNameModel;
import com.slodon.b2b2c.seller.example.StoreNameExample;
import com.slodon.b2b2c.seller.pojo.Store;
import com.slodon.b2b2c.seller.pojo.StoreName;
import com.slodon.b2b2c.system.dto.EnquiryAddDTO;
import com.slodon.b2b2c.system.example.CountryExample;
import com.slodon.b2b2c.system.pojo.Country;
import com.slodon.b2b2c.vo.member.CountryPhoneCodeVO;
import com.slodon.b2b2c.vo.member.MemberEnquiryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.Collator;
import java.util.*;

/**
 * @author cyan
 */
@Api(tags = "front-询盘管理")
@RestController
@RequestMapping("v3/member/front/enquiry")
@Slf4j
public class MemberEnquiryController extends BaseController {

    @Resource
    private MemberEnquiryModel memberEnquiryModel;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private GoodsModel goodsModel;

    @Resource
    private StoreModel storeModel;

    @Resource
    private StoreNameModel storeNameModel;

    @Resource
    private CountryModel countryModel;

    /**
     * 存储询盘信息
     *
     * @param request
     * @param enquiryAddDTO
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public JsonResult<Object> addEnquiry(HttpServletRequest request, EnquiryAddDTO enquiryAddDTO) throws Exception {
        log.info("********** addEnquiry - enquiryAddDTO:{} *************", JSON.toJSONString(enquiryAddDTO));
        if (StringUtil.isEmpty(enquiryAddDTO.getName()) || StringUtil.isEmpty(enquiryAddDTO.getMessage()) ||
                StringUtil.isEmpty(enquiryAddDTO.getPageUrl()) || StringUtil.isEmpty(enquiryAddDTO.getItemType())) {
            return SldResponse.fail("提交失败,请重试");
        }
        // 增加Integer参数长度校验，防止数据库int类型溢出
        if (enquiryAddDTO.getQuantity() != null && (enquiryAddDTO.getQuantity() > Integer.MAX_VALUE || enquiryAddDTO.getQuantity() < Integer.MIN_VALUE)) {
            return SldResponse.fail("数量超出范围，请重试");
        }
        enquiryAddDTO.setWebSite(WebUtil.getWebSite(request));
        Integer key = memberEnquiryModel.saveEnquiry(request, enquiryAddDTO);
        return SldResponse.success("提交成功",key);
    }

    /**
     * 存储询盘信息
     *
     * @param request
     * @param enquiryAddDTO
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public JsonResult<Object> saveEnquiry(HttpServletRequest request, EnquiryAddDTO enquiryAddDTO) throws Exception {
        log.info("********** saveEnquiry - enquiryAddDTO:{} *************", JSON.toJSONString(enquiryAddDTO));
        if (StringUtil.isEmpty(enquiryAddDTO.getName()) || StringUtil.isEmpty(enquiryAddDTO.getMessage()) ||
                StringUtil.isEmpty(enquiryAddDTO.getPageUrl()) || StringUtil.isEmpty(enquiryAddDTO.getItemType())) {
            return SldResponse.fail("提交失败,请重试");
        }
        // 增加Integer参数长度校验，防止数据库int类型溢出
        if (enquiryAddDTO.getQuantity() != null && (enquiryAddDTO.getQuantity() > Integer.MAX_VALUE || enquiryAddDTO.getQuantity() < Integer.MIN_VALUE)) {
            return SldResponse.fail("数量超出范围，请重试");
        }
        enquiryAddDTO.setWebSite(WebUtil.getWebSite(request));
        Integer key = memberEnquiryModel.saveEnquiry(request, enquiryAddDTO);
        return SldResponse.success("提交成功",key);
    }

    @ApiOperation("询盘列表列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<MemberEnquiryVO>> getList(HttpServletRequest request, String keyword) {
        Member member = UserUtil.getUser(request, Member.class);
        String webSite = WebUtil.getWebSite(request);
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        MemberEnquiryExample example = new MemberEnquiryExample();
        example.setCreateUid(member.getMemberId());
        example.setKeyword(keyword);
        example.setWebSite(webSite);
        example.setPager(pager);
        List<MemberEnquiry> list = memberEnquiryModel.getEnquiryList(example, pager);
        ArrayList<MemberEnquiryVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(memberEnquiry -> {
                String itemName = "";
                if (EnquiryConst.ENQUIRY_ITEM_TYPE_GOODS.equals(memberEnquiry.getItemType())) {
                    GoodsExample example1 = new GoodsExample();
                    example1.setDefaultProductId(memberEnquiry.getItemId());
                    List<Goods> goods = goodsModel.getGoodsList(example1, null);
                    if (!CollectionUtils.isEmpty(goods)) {
                        itemName = goods.get(0).getGoodsName();
                    }
                }
                if (EnquiryConst.ENQUIRY_ITEM_TYPE_SHOP.equals(memberEnquiry.getItemType())) {
                    Store store = storeModel.getStoreByStoreId(memberEnquiry.getStoreId());
                    itemName = store.getStoreName();
                    if (!WebSiteConstant.MEMBER_OVERSEA.equals(webSite)) {
                        StoreNameExample storeNameExample = new StoreNameExample();
                        storeNameExample.setStoreId(store.getStoreId());
                        storeNameExample.setWebSite(webSite);
                        StoreName storeName = storeNameModel.getStoreNameByExample(storeNameExample);
                        itemName = storeName != null ? storeName.getStoreName() : store.getStoreName();
                    }

                }
                memberEnquiry.setItemName(itemName);
                vos.add(new MemberEnquiryVO(memberEnquiry, webSite));
            });
        }
        return SldResponse.success(new PageVO<>(vos, example.getPager()));
    }

    /**
     * 世界国家区号
     *
     * @param request
     * @return
     */
    @GetMapping("phoneCode")
    public JsonResult<List<CountryPhoneCodeVO>> getPhoneCode(HttpServletRequest request) {
        String  webSite = WebUtil.getWebSite(request);
        CountryExample example = new CountryExample();
        example.setOrderBy("id asc");
        ArrayList<CountryPhoneCodeVO> vos = new ArrayList<>();
        List<Country> list = countryModel.getPhoneCodeList(example, null);
        Collections.sort(list,new Comparator<Country>(){
            @Override
            public int compare(Country o1, Country o2) {
                String s1=o1.getName();
                String s2=o2.getName();
                return Collator.getInstance(Locale.UK).compare(s1, s2);
            }
        });
        if (!WebSiteConstant.MEMBER_OVERSEA.equals(webSite)){
            Collections.sort(list,new Comparator<Country>(){
                @Override
                public int compare(Country o1, Country o2) {
                    String s1=o1.getZhName();
                    String s2=o2.getZhName();
                    return Collator.getInstance(Locale.SIMPLIFIED_CHINESE).compare(s1, s2);
                }
            });
        }
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(country -> {
                vos.add(new CountryPhoneCodeVO(country, webSite));
            });
        }
        return SldResponse.success(vos);
    }

}
