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

import com.slodon.b2b2c.aop.VendorLogger;
import com.slodon.b2b2c.core.constant.ExpressConst;
import com.slodon.b2b2c.core.controller.BaseController;
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.AssertUtil;
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.model.seller.StoreBindExpressModel;
import com.slodon.b2b2c.model.system.ExpressModel;
import com.slodon.b2b2c.seller.example.StoreBindExpressExample;
import com.slodon.b2b2c.seller.pojo.StoreBindExpress;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.system.pojo.Express;
import com.slodon.b2b2c.util.FaceSheet100NeedField;
import com.slodon.b2b2c.util.FaceSheetNeedField;
import com.slodon.b2b2c.vo.seller.StoreBindExpressVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author slodon
 */
@Api(tags = "seller-物流公司管理")
@RestController
@RequestMapping("v3/seller/seller/express")
public class SellerBindExpressController extends BaseController {

    @Resource
    private StoreBindExpressModel storeBindExpressModel;
    @Resource
    private ExpressModel expressModel;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("默认物流公司列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "expressName", value = "物流名称", paramType = "query"),
            @ApiImplicitParam(name = "expressState", value = "是否启用：1-启用，0-不启用", paramType = "query"),
            @ApiImplicitParam(name = "createTimeAfter", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "createTimeBefore", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<StoreBindExpressVO>> getList(HttpServletRequest request, String expressName, Integer expressState,
                                                          Date createTimeAfter, Date createTimeBefore) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        StoreBindExpressExample example = new StoreBindExpressExample();
        example.setExpressNameLike(expressName);
        example.setExpressState(expressState);
        example.setCreateTimeAfter(createTimeAfter);
        example.setCreateTimeBefore(createTimeBefore);
        example.setStoreId(vendor.getStoreId());
        List<StoreBindExpress> list = storeBindExpressModel.getStoreBindExpressList(example, pager);
        List<StoreBindExpressVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            String expressType = stringRedisTemplate.opsForValue().get("express_type");
            list.forEach(storeBindExpress -> {
                StoreBindExpressVO vo = new StoreBindExpressVO(storeBindExpress);
                if ("1".equals(expressType)) {
                    //快递鸟
                    vo.setIsSupportFaceSheet(FaceSheetNeedField.isHasExpressCode(storeBindExpress.getExpressCode()) ? 1 : 0);
                    vo.setNeedFields(FaceSheetNeedField.getNeedFieldMap(storeBindExpress.getExpressCode()));
                } else {
                    //快递100
                    vo.setIsSupportFaceSheet(FaceSheet100NeedField.isHasExpressCode(storeBindExpress.getExpressCode()) ? 1 : 0);
                    vo.setNeedFields(FaceSheet100NeedField.getNeedFieldMap(storeBindExpress.getExpressCode()));
                }
                vos.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("添加物流公司")
    @VendorLogger(option = "添加物流公司")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "expressIds", value = "从平台获取的物流公司id串，以逗号隔开", required = true)
    })
    @PostMapping("add")
    public JsonResult<Integer> addExpress(HttpServletRequest request, @RequestParam("expressIds") String expressIds) {
        //参数校验
        AssertUtil.notEmpty(expressIds, "请选择要添加的物流公司id");
        AssertUtil.notFormatFrontIds(expressIds, "expressIds格式错误");
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        String[] expressIdArr = expressIds.split(",");
        for (String expressId : expressIdArr) {
            //根据物流公司id获取物流公司信息
            Express express = expressModel.getExpressByExpressId(Integer.parseInt(expressId));
            //物流公司未启用
            AssertUtil.isTrue(!express.getExpressState().equals(ExpressConst.EXPRESS_STATE_OPEN),
                    "物流公司：" + express.getExpressName() + "未启用，无法添加");
            StoreBindExpress storeBindExpress = new StoreBindExpress();
            storeBindExpress.setStoreId(vendor.getStoreId());
            storeBindExpress.setExpressId(express.getExpressId());
            storeBindExpress.setExpressName(express.getExpressName());
            storeBindExpress.setExpressCode(express.getExpressCode());
            storeBindExpress.setExpressWebsite(express.getWebsite());
            storeBindExpress.setTemplateId(express.getTemplateId());
            storeBindExpressModel.saveStoreBindExpress(storeBindExpress);
        }
        return SldResponse.success("添加成功");
    }

    @ApiOperation("开启/关闭物流公司")
    @VendorLogger(option = "开启/关闭物流公司")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bindId", value = "物流公司绑定id", required = true),
            @ApiImplicitParam(name = "expressState", value = "是否启用：1-启用，0-不启用", required = true),
    })
    @PostMapping("openOrCloseExpress")
    public JsonResult<Integer> openOrCloseExpress(HttpServletRequest request,
                                                  @RequestParam("bindId") Integer bindId,
                                                  @RequestParam("expressState") Integer expressState) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        AssertUtil.isTrue(StringUtil.isNullOrZero(bindId), "请选择要开启/关闭的物流公司");
        //根据bindId获取物流公司信息
        StoreBindExpress storeBindExpress = storeBindExpressModel.getStoreBindExpressByBindId(bindId);
        AssertUtil.notNull(storeBindExpress, "快递公司为空");
        AssertUtil.isTrue(!vendor.getStoreId().equals(storeBindExpress.getStoreId()), "非法操作");
        storeBindExpressModel.openOrCloseExpress(bindId, expressState);

        if (expressState.equals(ExpressConst.EXPRESS_STATE_CLOSE)) {
            return SldResponse.success("物流公司已关闭");
        } else {
            return SldResponse.success("物流公司已开启");
        }
    }

    @ApiOperation("删除快递公司")
    @VendorLogger(option = "删除快递公司")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bindId", value = "物流公司绑定id", required = true)
    })
    @PostMapping("del")
    public JsonResult<Integer> delExpress(HttpServletRequest request, @RequestParam("bindId") Integer bindId) {
        String logMsg = "店铺绑定快递公司id:" + bindId;
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        //根据bindId获取物流公司信息
        StoreBindExpress storeBindExpress = storeBindExpressModel.getStoreBindExpressByBindId(bindId);
        AssertUtil.notNull(storeBindExpress, "快递公司为空");
        AssertUtil.isTrue(!vendor.getStoreId().equals(storeBindExpress.getStoreId()), "非法操作");

        storeBindExpressModel.deleteStoreBindExpress(bindId);
        return SldResponse.success("删除成功", logMsg);
    }

    @ApiOperation("电子面单配置")
    @VendorLogger(option = "电子面单配置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bindId", value = "物流公司绑定id", required = true),
            @ApiImplicitParam(name = "customerName", value = "快递鸟客户帐号(对应快递100的partnerId)"),
            @ApiImplicitParam(name = "customerPwd", value = "快递鸟客户密码(对应快递100的partnerKey)"),
            @ApiImplicitParam(name = "sendSite", value = "快递鸟所属网点(对应快递100的net)"),
            @ApiImplicitParam(name = "sendStaff", value = "快递鸟网点信息(对应快递100的checkMan)"),
            @ApiImplicitParam(name = "monthCode", value = "快递鸟月结号"),
            @ApiImplicitParam(name = "payType", value = "快递鸟支付类型 1 现付 2 到付 3 月结 4 第三方支付(仅顺丰支持)"),
            @ApiImplicitParam(name = "templateSize", value = "快递鸟电子面单模板大小,参考快递鸟模板样式表(非必填)"),
            @ApiImplicitParam(name = "templateId", value = "快递100 模板id"),
            @ApiImplicitParam(name = "partnerName", value = "快递100 电子面单客户账户名称"),
            @ApiImplicitParam(name = "code", value = "快递100 电子面单承载编号"),
            @ApiImplicitParam(name = "expType", value = "快递100 产品类型")
    })
    @PostMapping("sheetConfig")
    public JsonResult<Object> sheetConfig(HttpServletRequest request, Integer bindId, String customerName, String customerPwd,
                                          String sendSite, String sendStaff, String monthCode, Integer payType, String templateSize,
                                          String templateId, String partnerName, String code, String expType) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        StoreBindExpress express = storeBindExpressModel.getStoreBindExpressByBindId(bindId);
        AssertUtil.notNull(express, "快递公司不存在");
        AssertUtil.isTrue(!vendor.getStoreId().equals(express.getStoreId()), "非法操作");

        StoreBindExpress storeBindExpress = new StoreBindExpress();
        storeBindExpress.setBindId(bindId);
        storeBindExpress.setCustomerName(customerName);
        storeBindExpress.setCustomerPwd(customerPwd);
        storeBindExpress.setSendSite(sendSite);
        storeBindExpress.setSendStaff(sendStaff);
        storeBindExpress.setMonthCode(monthCode);
        storeBindExpress.setPayType(payType);
        storeBindExpress.setTemplateSize(templateSize);
        storeBindExpress.setTemplateId(templateId);
        storeBindExpress.setPartnerName(partnerName);
        storeBindExpress.setCode(code);
        storeBindExpress.setExpType(expType);
        storeBindExpressModel.updateStoreBindExpress(storeBindExpress);
        return SldResponse.success("配置成功", "店铺绑定快递公司id:" + bindId);
    }

}
