package com.kmall.admin.controller.mk.dist;

import java.util.*;

import com.kmall.admin.entity.mk.dist.MkDistEntity;
import com.kmall.admin.entity.mk.dist.MkDistSellStatisEntity;
import com.kmall.admin.service.mk.dist.MkDistSellStatisService;
import com.kmall.admin.service.mk.dist.MkDistService;
import com.kmall.admin.utils.ParamUtils;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.DateUtils;
import com.kmall.common.utils.PageUtils;
import com.kmall.common.utils.Query;
import com.kmall.common.utils.R;
import com.kmall.common.utils.excel.ExcelExport;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 购买商品生成销售分配记录统计，渠道销售统计Controller
 *
 * @author huangyq
 * @email admin@qhdswl.com
 * @date 2019-04-09 18:04:46
 */
@Controller
@RequestMapping("mkdistsellstatis")
public class MkDistSellStatisController {
    @Autowired
    private MkDistSellStatisService mkDistSellStatisService;
    @Autowired
    private MkDistService mkDistService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("mkdistsellstatis:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        params = ParamUtils.setTimeMap(params);
        //查询列表数据
        Query query = new Query(params);

        List<MkDistSellStatisEntity> mkDistSellStatisList = mkDistSellStatisService.queryList(query);
        int total = mkDistSellStatisService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(mkDistSellStatisList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("mkdistsellstatis:info")
    @ResponseBody
    public R info(@PathVariable("id") Integer id) {
        MkDistSellStatisEntity mkDistSellStatis = mkDistSellStatisService.queryObject(id);

        return R.ok().put("mkDistSellStatis", mkDistSellStatis);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("mkdistsellstatis:save")
    @ResponseBody
    public R save(@RequestBody MkDistSellStatisEntity mkDistSellStatis) {
        mkDistSellStatisService.save(mkDistSellStatis);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("mkdistsellstatis:update")
    @ResponseBody
    public R update(@RequestBody MkDistSellStatisEntity mkDistSellStatis) {
        mkDistSellStatisService.update(mkDistSellStatis);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("mkdistsellstatis:delete")
    @ResponseBody
    public R delete(@RequestBody Integer[]ids) {
        mkDistSellStatisService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        params = ParamUtils.setTimeMap(params);

        List<MkDistSellStatisEntity> list = mkDistSellStatisService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 订单导出请求
     */
    @RequiresPermissions(value = {"order:export"})
    @RequestMapping(value = "export")
    public Object export(@RequestParam Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        params = ParamUtils.setTimeMap(params);

        List<MkDistSellStatisEntity> orderList = mkDistSellStatisService.queryStatisExportList(params);

        ExcelExport ee = new ExcelExport("渠道销售统计");

//        String[] header = new String[]{"分销渠道名称","所属三方商户", "所属门店", "订单编号", "商品所属分销商", "商品名称", "商品销售价", "实际支付金额",
//                "分销分配方式", "支出分销规则(分销商:分配额度)", "支出分销商", "支出分销商额度", "支出分销商等级"};
        String[] header = new String[]{ "订单编号", "商品名称", "商品所属分销商-门店","上级分销商-门店","上级分销商等级", "上级分销商分摊金额","商品销售价", "实际支付金额",
                "分销分配方式", "支出分销规则(分销商:分配额度)", "所属三方商户", "分销渠道名称"};

        List<Map<String, Object>> list = new ArrayList<>();
        if (orderList != null && orderList.size() != 0) {
            for (MkDistSellStatisEntity mkDistSellStatisEntity : orderList) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                StringBuffer lines = new StringBuffer();
                String distIds = mkDistSellStatisEntity.getExpendDistIds();
                String distLines = mkDistSellStatisEntity.getExpendDistLines();
                String[] idsArray = distIds.split(",");
                String[] distLinesArray = distLines.split(",");
                for (int i = 0; i < idsArray.length; i++){
                    MkDistEntity distEntity = mkDistService.queryObject(Integer.parseInt(idsArray[i]));
                    lines = lines.append(distEntity.getDistName() +":"+ distLinesArray[i]+"，");
                }

                map.put("orderSn", mkDistSellStatisEntity.getOrderSn());
                map.put("goodsName", mkDistSellStatisEntity.getGoodsName());
                map.put("goodsDistName", mkDistSellStatisEntity.getGoodsDistName()+"-"+mkDistSellStatisEntity.getStoreName());
                map.put("expendDistName", mkDistSellStatisEntity.getExpendDistName()+"-"+mkDistSellStatisEntity.getChildStoreName());
                map.put("expendDistLevel", mkDistSellStatisEntity.getExpendDistLevel());
                map.put("expendDistPrice", mkDistSellStatisEntity.getExpendDistPrice());
                map.put("goodsPrice", mkDistSellStatisEntity.getGoodsPrice());
                map.put("autprice", StringUtils.isNotEmpty(String.valueOf(mkDistSellStatisEntity.getActualPrice())) ? mkDistSellStatisEntity.getActualPrice().doubleValue() : 0);
                map.put("allocType", StringUtils.isEmpty(mkDistSellStatisEntity.getAllocType())? "":
                        Dict.allocType.valueOf("item_"+mkDistSellStatisEntity.getAllocType()).getItemName());
                map.put("expendDistLines", lines.substring(0,lines.length()-1));
                map.put("thirdPartyMerchName", mkDistSellStatisEntity.getThirdPartyMerchName());
//                map.put("storeName", mkDistSellStatisEntity.getStoreName());
//                map.put("childSupplierName", mkDistSellStatisEntity.getChildSupplierName());
                map.put("distFlag", mkDistSellStatisEntity.getDistFlag());

                list.add(map);
            }
        }

        ee.addSheetByMap("渠道销售统计", list, header);
        ee.export(response);
        return R.ok();
    }
}
