package cn.pluss.platform.controller;

import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.ProjectConstant;
import cn.pluss.platform.entity.MerchantBaseInfo;
import cn.pluss.platform.entity.MerchantOrder;
import cn.pluss.platform.entity.MerchantProfit;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.mapper.MerchantProfitMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantProfit.MerchantProfitService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/merchantProfit")
@Api(value = "MerchantProfit控制类", tags = {"MerchantProfit接口"})
public class MerchantProfitController {

    @Resource
    private MerchantProfitService merchantProfitService;
    @Resource
    private MerchantBaseInfoService merchantBaseInfoService;
    @Resource
    private MerchantOrderService merchantOrderService;
    @Resource
    private MerchantProfitMapper merchantProfitMapper;
    @Resource
    private UserAppService userAppService;

    @GetMapping
    @ApiOperation(tags = {"页面-商户推广_交易明细"}, value = "获取全部", notes = "返回分页过后的数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "查询页码", paramType = "query", dataType = "Integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query", dataType = "Integer", defaultValue = "0")
    })
    public Result<PageInfo<MerchantProfit>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam String merchantName, // 商户名称
            @RequestParam String level,  //等级       1   2  3
            @RequestParam String type,//商户所属  不传全部  1直接  2 间接 3 二级间接
            @RequestParam String startTime,
            @RequestParam String endTime,
            @RequestParam(required = false, value = "agentStaffIds[]") String[] agentStaffIds) throws ParseException {

        UserApp userApp = userAppService.queryUserAppByToken();

        Long userId = userApp.getUserId();

        if (size == null || size == 0) {
            size = ProjectConstant.PAGE_SIZE;
        }
        if (page == null || page == 0) {
            page = 1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", size);
        map.put("offset", (page - 1) * size);

        if ("agent_staff".equals(userApp.getUserType())) {
            map.put("agentStaffId", userApp.getUserId());
        } else {
            if (agentStaffIds != null && agentStaffIds.length > 0) {
                String id = agentStaffIds[0];
                map.put("userId", userId);
                if ("-1".equals(id)) {
                    map.put("self", true);
                } else {
                    map.put("agentStaffIds", agentStaffIds);
                }
            }
            map.put("userId", userId);
        }
        if (StringUtil.isNotEmpty(merchantName)) {
            map.put("merchantName", merchantName);
        }
        if (StringUtil.isNotEmpty(level)) {
            map.put("level", level);
        }
        if (StringUtil.isNotEmpty(type)) {
            map.put("type", type);
        } else {
            map.put("retype", "1");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd ahh:mm:ss");

        if (StringUtils.isNotEmpty(startTime) ) {
            if (((startTime.contains("上午")) || (startTime.contains("下午")))) {
                map.put("startTime", sdf2.parse(startTime));
            } else {
                map.put("startTime", sdf.parse(startTime));
            }
        }

        if (StringUtils.isNotEmpty(endTime) ) {
            if (((endTime.contains("上午")) || (endTime.contains("下午")))) {
                map.put("endTime", sdf2.parse(endTime));
            } else {
                map.put("endTime", sdf.parse(endTime));
            }
        }

        List<MerchantProfit> merchantProfitList = merchantProfitService.queryMerchantProfitPage(map);

        if (merchantProfitList != null && merchantProfitList.size() > 0) {

            List<Map<String, Object>> rateInfoMapList = merchantProfitMapper.queryMerchantProfitRate(merchantProfitList, userApp.getUserId().toString());

            // 商户code列表
            List<String> merchantCodeList = new ArrayList<>();
            //  订单number列表
            List<String> orderNumberList = new ArrayList<>();
            for (MerchantProfit m : merchantProfitList) {
                merchantCodeList.add(m.getMerchantCode());
                orderNumberList.add(m.getOrderNumber());
            }

            QueryWrapper<MerchantBaseInfo> queryMerchantBaseInfo = new QueryWrapper<MerchantBaseInfo>().in("merchantCode", merchantCodeList);
            List<MerchantBaseInfo> merchantBaseInfoList = merchantBaseInfoService.list(queryMerchantBaseInfo);

            QueryWrapper<MerchantOrder> queryMerchantOrder = new QueryWrapper<MerchantOrder>().in("orderNumber", orderNumberList);
            List<MerchantOrder> merchantOrderList = merchantOrderService.list(queryMerchantOrder);

            for (MerchantProfit m : merchantProfitList) {

                m.setMerchantLogo(null);
                m.setPayTypeName(m.getPayTypeName().replaceAll("乐刷|随行|随行付", ""));
                for (MerchantBaseInfo merchantBaseInfo : merchantBaseInfoList) {
                    if (merchantBaseInfo.getMerchantCode().equals(m.getMerchantCode())) {
                        m.setUserName(merchantBaseInfo.getContactName());
                        m.setPhone(merchantBaseInfo.getContactMobile());
                        m.setMerchantName(merchantBaseInfo.getAlias());
                    }
                }

                for (MerchantOrder merchantOrder : merchantOrderList) {
                    if (merchantOrder.getOrderNumber().equals(m.getOrderNumber())) {
                        m.setRate(merchantOrder.getRate());
                        break;
                    }
                }


                if (m.getRate() == null) {
                    m.setRate(new BigDecimal(38));
                } else {
                    // TODO 暂去掉小数点后第三位，需要等 安卓app 1.7.0更新以后才可以去掉
                    m.setRate(m.getRate().round(new MathContext(2, RoundingMode.DOWN)));
                }

                // 针对普通推广者
                if (m.getProfitRate() == null) {
                    if (m.getUserType().equals("promoter")) {
                        switch (m.getMerchantParentLevel()) {
                            case "1":
                                m.setProfitRate(6);
                                break;
                            case "2":
                                m.setProfitRate(8);
                                break;
                            case "3":
                                m.setProfitRate(10);
                                break;
                            default:
                                break;
                        }
                    } else {

                        for (Map<String, Object> rateMap : rateInfoMapList) {
                            // Long和int无法equals
                            if ((m.getId() + "").equals(rateMap.get("id") + "")) {
                                m.setProfitRate((int) rateMap.get("rateCur"));
                            }
                        }
                    }
                }
            }
        }


        Integer count = merchantProfitService.queryMerchantProfitPageCount(map);

        //返回参数
        PageInfo<MerchantProfit> pager = new PageInfo<>(count.longValue(), (long) StringUtil.getPageCount(count, size), page.longValue(), size.longValue(), merchantProfitList);
        return ResultGenerator.genSuccessResult(pager);
    }

    @PostMapping
    @ApiOperation(value = "添加数据", notes = "添加新的数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantProfit", value = "待添加的MerchantProfit实例", paramType = "body", dataType = "MerchantProfit", required = true)
    })
    public Result add(@RequestBody MerchantProfit merchantProfit) {
        merchantProfitService.saveMerchantProfit(merchantProfit);
        return ResultGenerator.genSuccessResult();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据", notes = "根据id删除数据", httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id实例", paramType = "path", dataType = "Integer", required = true)
    })
    public Result delete(@PathVariable Long id) {
        MerchantProfit merchantProfit = new MerchantProfit();
        merchantProfit.setId(id);
        merchantProfitService.deleteMerchantProfit(merchantProfit);
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping
    @ApiOperation(value = "更新数据", notes = "根据内容更新数据", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantProfit", value = "更新的MerchantProfit实例", paramType = "body", dataType = "MerchantProfit", required = true)
    })
    public Result update(@RequestBody MerchantProfit merchantProfit) {
        merchantProfitService.updateMerchantProfit(merchantProfit);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "获取单个值", notes = "查看单个项目的内容", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id", paramType = "path", required = true, dataType = "Integer", defaultValue = "0")
    })
    public Result<MerchantProfit> detail(@PathVariable Long id) {
        MerchantProfit merchantProfit = new MerchantProfit();
        merchantProfit.setId(id);
        merchantProfit = merchantProfitService.queryMerchantProfit(merchantProfit);
        return ResultGenerator.genSuccessResult(merchantProfit);
    }
}

