package com.pj.tb_orders;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.pj.api.consts.FeignFactory;
import com.pj.api.dto.OrderDto;
import com.pj.api.dto.PeopleDto;
import com.pj.current.config.SystemObject;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.current.dto.PCLoginUserInfo;
import com.pj.current.satoken.StpAPPUserUtil;
import com.pj.current.satoken.StpUserUtil;
import com.pj.enummj.DeleteStatus;
import com.pj.enummj.OrderStatus;
import com.pj.tb_orders.vo.TbOrdersEmailVo;
import com.pj.tb_orders.vo.TbOrdersPrintVo;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.pj.utils.sg.*;
import com.pj.project4sp.SP;

import cn.dev33.satoken.annotation.SaCheckPermission;


/**
 * Controller: tb_orders -- 订单表
 *
 * @author qzy
 */
@RestController
@RequestMapping("/TbOrders/")
public class TbOrdersController {

    /**
     * 底层 Service 对象
     */
    @Autowired
    TbOrdersService tbOrdersService;


    @RequestMapping("addOrderByResale")
    @SaCheckPermission(TbOrders.PERMISSION_CODE_EDIT_PRICE)
    public AjaxJson addOrderByResale(Long id) {
        OrderDto orderDto = FeignFactory.levelOneServerInterface.getOrderDtoById(id);
        if (null == orderDto) throw new AjaxError("转售失败，请联系管理员！");

        //获取app登录用户
        TbOrders db = tbOrdersService.findByLevelOneOrderId(id);
        if (db != null) {
            throw new AjaxError(orderDto.getTradeNo() + "已转售，请联系管理员处理");
        }
        TbOrders orders = new TbOrders();
        orders.setResalePrice(orderDto.getUpPrice().doubleValue());
        orders.setLevelOneOrderId(id);
        orders.setGoodsId(orderDto.getGoodsId());
        orders.setGoodsName(orderDto.getGoodsNames());
        orders.setTradeAreaName(orderDto.getTradeAreaName());
        orders.setTradeAreaId(orderDto.getTradeAreaId());
        orders.setVeNo(orderDto.getVeNo())
                .setGoodsUnit(orderDto.getGoodsUnit())
                .setNetWet(orderDto.getNetWt() + "")
                .setTotalWeight(orderDto.getTotalWeight() + "")
                .setSinglePrice(orderDto.getDeclPrice().toString())
        ;

        //订单编号:EJSCDD=二级市场订单
        orders.setOrderNo(SystemObject.getREFcode("EJSCDD", new Date()));
        //订单完成状态 (0=未完成,1=已完成)
        orders.setOrderFinish(OrderStatus.ORDER_STATUS_ZERO.getCode());
        //删除状态(0=禁用,1=启用)
        orders.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());

        PeopleDto people = FeignFactory.levelOneServerInterface.getRpcById(orderDto.getBuyUserId());
        //转售订单的边民
        orders.setLeaderId(people.getId());
        orders.setLeaderName(people.getName());
        orders.setLeaderPhone(people.getPhone());
        //创建人
        PCLoginUserInfo pcLoginUserInfo = StpUserUtil.getPCLoginInfo();
        orders.setCreateBy(Long.parseLong(pcLoginUserInfo.getLoginId()));
        orders.setCreateName(pcLoginUserInfo.getLoginName());
        orders.setCreateTime(new Date());

        tbOrdersService.add(orders);

        //修改一级市场边民订单转售状态为已转售
        boolean b = FeignFactory.levelOneServerInterface.updateResaleStatus(id);
        if (!b) throw new RuntimeException("修改一级市场边民订单转售状态为已转售失败！");

        return AjaxJson.getSuccess();
    }


    @RequestMapping("addOrderByResaleBatch")
    @SaCheckPermission(TbOrders.PERMISSION_CODE_EDIT_PRICE)
    public AjaxJson addOrderByResaleBatch() {
        List<Long> ids = SoMap.getRequestSoMap().getListByComma("ids", long.class);
        for (Long id : ids) {
            this.addOrderByResale(id);
        }
        return AjaxJson.getSuccess();
    }

    /**
     * 改
     */
    @RequestMapping("update")
    @SaCheckPermission(TbOrders.PERMISSION_CODE_EDIT)
    public AjaxJson update(TbOrders t) {
        tbOrdersService.update(t);
        return AjaxJson.getSuccess();
    }

    /**
     * 查 - 根据id
     */
    @RequestMapping("getById")
    @SaCheckPermission(TbOrders.PERMISSION_CODE)
    public AjaxJson getById(Long id) {
        TbOrders t = tbOrdersService.getById(id);
        return AjaxJson.getSuccessData(t);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    @RequestMapping("getList")
    @SaCheckPermission(TbOrders.PERMISSION_CODE)
    public AjaxJson getList(@RequestParam(value = "ordersStatus", required = false) Integer ordersStatus) {
        SoMap so = SoMap.getRequestSoMap();
        List<TbOrders> list = tbOrdersService.getPCList(so.startPage(), ordersStatus);
        return AjaxJson.getPageData(so.getDataCount(), list);
    }


    /**
     * 改 - 订单完成状态 (0=未完成,1=已完成)
     */
    @RequestMapping("updateOrderFinish")
    @SaCheckPermission(TbOrders.PERMISSION_CODE_EDIT)
    public AjaxJson updateOrderFinish(Long id, Integer value) {
        int line = SP.publicMapper.updateColumnById(TbOrders.TABLE_NAME, "order_finish", value, id);
        return AjaxJson.getByLine(line);
    }

    /**
     * 查询所有统计年份
     **/
    @RequestMapping("selectYear")
    public AjaxJson selectYear() {
        SoMap so = new SoMap();
        so.put("year", tbOrdersService.selectYear());
        //运营管理者统计全部
        if (StpUserUtil.getPCLoginInfo().getType() == null || StpUserUtil.getPCLoginInfo().getType().equals("00")) {
            so.put("count", tbOrdersService.totalMoney(null));
        }
        //合作社只统计对应的互市id
        if (StpUserUtil.getPCLoginInfo().getType() != null && StpUserUtil.getPCLoginInfo().getType().equals("01")) {
            so.put("count", tbOrdersService.totalMoney(StpUserUtil.getPCLoginInfo().getTradeAreaId()));
        }
        return AjaxJson.getSuccessData(so);
    }

    /**
     * 根据年份查询每月订单交易额统计
     **/
    @RequestMapping("orderStatistics")
    public AjaxJson orderStatistics(String year) {
        SoMap so = new SoMap();
        //运营管理者统计全部
        if (StpUserUtil.getPCLoginInfo().getType() == null || StpUserUtil.getPCLoginInfo().getType().equals("00")) {
            so.put("money", tbOrdersService.orderStatistics("交易额", year, null));
            so.put("count", tbOrdersService.orderStatistics("交易量", year, null));
        }
        //合作社只统计对应的互市id
        if (StpUserUtil.getPCLoginInfo().getType() != null && StpUserUtil.getPCLoginInfo().getType().equals("01")) {
            so.put("money", tbOrdersService.orderStatistics("交易额", year, StpUserUtil.getPCLoginInfo().getTradeAreaId()));
            so.put("count", tbOrdersService.orderStatistics("交易量", year, StpUserUtil.getPCLoginInfo().getTradeAreaId()));
        }
        return AjaxJson.getSuccessData(so);
    }


    /**
     * 采购商补扣款
     */
    @RequestMapping("deduction")
    @SaCheckPermission(TbOrders.PERMISSION_CODE_DEDUCTION)
    public AjaxJson deduction(Long id) {
        tbOrdersService.deduction(id);
        return AjaxJson.getSuccess();
    }

    /**
     * 采购商补扣款
     */
    @RequestMapping("payBatch")
    @SaCheckPermission(TbOrders.PERMISSION_CODE_DEDUCTION)
    public AjaxJson payBatch() {
        List<Long> ids = SoMap.getRequestSoMap().getListByComma("ids", long.class);
        if (ids.isEmpty()) {
            return AjaxJson.getError("请选择需要补扣款的订单！");
        }
        List<TbOrders> orders = tbOrdersService.listByIds(ids);
        List<TbOrders> checkList = orders.stream().filter(tbOrders -> tbOrders.getIsPay() == 1 || tbOrders.getIsPay() == 3).collect(Collectors.toList());
        if (!checkList.isEmpty()) {
            return AjaxJson.getError("扣款订单中存在已支付或正在支付订单！");
        }
        tbOrdersService.payBatch(orders);

        return AjaxJson.getSuccess();
    }

    /**
     * 查 - 交易凭证
     */
    @RequestMapping("getSubPrint")
    @SaCheckPermission(TbOrders.PERMISSION_CODE)
    public AjaxJson getSubPrint(Long id) {
        TbOrdersPrintVo t = tbOrdersService.getSubPrint(id);
        return AjaxJson.getSuccessData(t);
    }

    /**
     * 查 - 电子协议
     */
    @RequestMapping("getSubEmail")
    @SaCheckPermission(TbOrders.PERMISSION_CODE)
    public AjaxJson getSubEmail(Long id) {
        TbOrdersEmailVo t = tbOrdersService.getSubEmail(id);
        return AjaxJson.getSuccessData(t);
    }

    /**
     * 根据一级市场订单删除二级市场订单
     */
    @RequestMapping("rpc/removeOnSaleOrderByLevelOneOrderId")
    public boolean removeOnSaleOrderByLevelOneOrderId(@RequestParam("levelOneOrderId") Long levelOneOrderId) {
        return tbOrdersService.removeOnSaleOrderByLevelOneOrderId(levelOneOrderId);
    }

    /**
     * 根据一级市场订单删除二级市场订单
     */
    @RequestMapping("rpc/removeOnSaleOrderByLevelOneOrderIds")
    public boolean removeOnSaleOrderByLevelOneOrderId(@RequestParam("levelOneOrderIds") String levelOneOrderIds) {
        return tbOrdersService.removeOnSaleOrderByLevelOneOrderIds(levelOneOrderIds);
    }
}
