package com.gic.haoban.manage.web.controller;

import com.gic.api.base.commons.RpcResult;
import com.gic.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.dto.DictDTO;
import com.gic.haoban.manage.api.service.DictApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.DictVo;
import com.gic.mall.api.service.MallSettingService;
import com.gic.mall.api.vo.MallOrderSettingVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * Created 2020/3/26.
 *
 * @author hua
 */
@RestController
public class DictController extends WebBaseController {

    @Autowired
    private DictApiService dictApiService;
    @Autowired
    private MallSettingService mallSettingService;

    @RequestMapping("/dict-list")
    public HaobanResponse queryDictList(String dictKeys, String enterpriseId) {
        if (StringUtils.isBlank(dictKeys)) {
            return resultResponse(HaoBanErrCode.ERR_5);
        }
        String[] split = dictKeys.split(",");
        List<DictDTO> ret = dictApiService.queryList(Arrays.asList(split));
        // 添加订单提现说明
        addOrderAfterSaleTimeDict(enterpriseId, ret);
        return resultResponse(HaoBanErrCode.ERR_1, EntityUtil.changeEntityListByOrika(DictVo.class, ret));
    }

    private void addOrderAfterSaleTimeDict(String enterpriseId, List<DictDTO> ret) {
        String orderAfterSaleTimeKey = "order_after_sale_time";
        RpcResult<MallOrderSettingVo> orderSetting = mallSettingService.queryOrderSetting(enterpriseId);
        int day;
        if (Objects.isNull(orderSetting) || Objects.isNull(orderSetting.getData())) {
            // 默认7
            day = 7;
        } else {
            if (Objects.isNull(orderSetting.getData().getAfterSaleTime())) {
                day = 7;
            } else {
                day = orderSetting.getData().getAfterSaleTime();
            }
        }
        DictDTO dictDTO = new DictDTO();
        dictDTO.setDictName("提现说明");
        dictDTO.setDictKey(orderAfterSaleTimeKey);
        dictDTO.setDictContent(String.format("订单确认收货后%s天可以提现", day));
        ret.add(dictDTO);
    }

    /**
     * 根据key查询一条数据
     *
     * @param dictKey
     * @return
     */
    @RequestMapping("/find-dict-key")
    @IgnoreLogin
    public HaobanResponse queryDictByKey(String dictKey) {
        if (StringUtils.isBlank(dictKey)) {
            return resultResponse(HaoBanErrCode.ERR_5);
        }
        return resultResponse(HaoBanErrCode.ERR_1, dictApiService.findOneDictByKey(dictKey));
    }
}
