package com.jpsoft.shinestar.modules.base.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.dto.OrderDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.entity.CameraPurchaser;
import com.jpsoft.shinestar.modules.business.service.CameraPurchaserService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.*;
import com.jpsoft.shinestar.modules.pay.weixin.WxPayController;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/base/order")
@Slf4j
public class OrderController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @Autowired
    private GoodsInfoService goodsInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private OrderLogService orderLogService;

    @Autowired
    private UserService userService;

    @Autowired
    private OSSConfig ossConfig;
    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private CameraPurchaserService cameraPurchaserService;


    @ApiOperation(value = "分页列表")
    @RequestMapping(value = "pageList", method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String goodName, String goodTypeId, String outOrderNo, String payStatus,
            String name, String companyId,String createTimeRanges,String transactionId,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestParam(value="field",defaultValue="pay_time") String field,
            @RequestParam(value="direction",defaultValue="desc") String direction,
            @RequestAttribute String subject) {

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String, Object> searchParams = new HashMap<>();

        boolean goodsFlag = false;

        //商品相关查询
        Map<String, Object> goodsSearchParams = new HashMap<>();

        if (StringUtils.isNotEmpty(goodName)) {
            goodsFlag = true;
            goodsSearchParams.put("name", "%" + goodName + "%");
        }

        if (StringUtils.isNotEmpty(goodTypeId)) {
            goodsFlag = true;
            goodsSearchParams.put("goodTypeId", goodTypeId);
        }

        if (goodsFlag) {
            List<String> goodsIdList = goodsInfoService.findBySearch(goodsSearchParams);


            if (goodsIdList.size() == 0) {
                goodsIdList.add("-1");
            }
            searchParams.put("goodsIdList", goodsIdList);
        }


        if (StringUtils.isNotEmpty(outOrderNo)) {
            searchParams.put("outOrderNo", "%" + outOrderNo + "%");
        }

        if (StringUtils.isNotEmpty(payStatus)) {
            searchParams.put("payStatus", payStatus);
        }

        Map<String, Object> personSearchParams = new HashMap<>();

        boolean flag = false;

        if (StringUtils.isNotEmpty(name)) {
            personSearchParams.put("name", "%" + name + "%");
            flag = true;
        }

        if(flag){
            List<Long> personIdList = personInfoService.findByOrderProperty(personSearchParams);

            if (personIdList.size() == 0) {
                personIdList.add(Long.valueOf("-1"));
            }

            searchParams.put("personIdList", personIdList);
        }

        if (StringUtils.isNotEmpty(companyId)) {
            searchParams.put("companyId", companyId);
        }

        if (StringUtils.isNotEmpty(createTimeRanges)) {
            String[] timeRangeArray = createTimeRanges.split(",");
            String beginTime = "";
            String endTime = "";
            if (timeRangeArray.length == 1) {
                beginTime = timeRangeArray[0];
                beginTime += " 00:00:00";
            } else if (timeRangeArray.length == 2) {
                beginTime = timeRangeArray[0];
                endTime = timeRangeArray[1];
                beginTime += " 00:00:00";
                endTime += " 23:59:59";
            }

            searchParams.put("beginTime", beginTime);
            searchParams.put("endTime", endTime);
        }

        if (StringUtils.isNotEmpty(transactionId)) {
            searchParams.put("transactionId", "%"+transactionId+"%");
        }

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort(field,direction));
        sortList.add(new Sort("create_time", "desc"));

        Page<OrderInfo> page = orderInfoService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);

        Page<OrderDTO> pageDto = new Page<>();

        for (OrderInfo order : page) {
            OrderDTO orderDTO = new OrderDTO();

            String orderId = order.getId();

            orderDTO.setId(orderId);

            String typeName = "";

            GoodsType goodsType = goodsTypeService.get(order.getType());

            if (goodsType!=null){
                typeName = goodsType.getGoodsName();
            }

            if (StringUtils.isNotEmpty(order.getPayName())) {
                if ("wechat".equals(order.getPayName())) {
                    orderDTO.setPayName("微信");
                } else if ("alipay".equals(order.getPayName())) {
                    orderDTO.setPayName("支付宝");
                } else {
                    orderDTO.setPayName("现金");
                }
            }

            GoodsInfo goodsInfo = goodsInfoService.get(order.getGoodsId());

            if (goodsInfo != null) {
                orderDTO.setGoodName(goodsInfo.getName());
                orderDTO.setCost(order.getPayFee());
            }

            PersonInfo personInfo = personInfoService.get(order.getPersonId());

            if (personInfo != null) {
                orderDTO.setName(personInfo.getName());
                orderDTO.setContactPhone(personInfo.getPhone());
            }

            CompanyInfo companyInfo = companyInfoService.get(order.getCompanyId());
            if(companyInfo!=null) {
                orderDTO.setCompanyName(companyInfo.getName());
            }
            else{
                orderDTO.setCompanyName("");
            }

            orderDTO.setGoodTypeName(typeName);

            orderDTO.setGoodNum("1");

            orderDTO.setPayFee(order.getPayFee());

            orderDTO.setOutOrderNo(order.getOutOrderNo());

            orderDTO.setTransactionId(order.getTransactionId());

            orderDTO.setCreateTime(order.getCreateTime());

            orderDTO.setPayTime(order.getPayTime());

            orderDTO.setStatus(order.getStatus());

            orderDTO.setPayStatus(order.getPayStatus());

            pageDto.add(orderDTO);
        }

        pageDto.setPageSize(page.getPageSize());
        pageDto.setTotal(page.getTotal());
        pageDto.setPageNum(page.getPageNum());


        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(pageDto));

        return msgResult;
    }


    @ApiOperation(value = "获取信息")
    @GetMapping("detail/{id}")
    public MessageResult<OrderDTO> detail(@PathVariable("id") String id) {
        MessageResult<OrderDTO> msgResult = new MessageResult<>();

        try {
            OrderDTO orderDTO = new OrderDTO();

            OrderInfo orderInfo = orderInfoService.get(id);

            if (orderInfo != null) {
                orderDTO.setOutOrderNo(orderInfo.getOutOrderNo());
                orderDTO.setTransactionId(orderInfo.getTransactionId());
                orderDTO.setCreateTime(orderInfo.getCreateTime());
                orderDTO.setPayTime(orderInfo.getPayTime());

                PersonInfo person = personInfoService.get(orderInfo.getPersonId());
                if (person != null) {
                    orderDTO.setName(person.getName());
                    orderDTO.setContactPhone(person.getPhone());
                } else {
                    orderDTO.setName("");
                    orderDTO.setContactPhone("");
                    orderDTO.setCompanyName("");
                }

                CompanyInfo companyInfo = companyInfoService.get(orderInfo.getCompanyId());
                if(companyInfo!=null) {
                    orderDTO.setCompanyName(companyInfo.getName());
                }
                else{
                    orderDTO.setCompanyName("");
                }

                msgResult.setResult(true);
                msgResult.setData(orderDTO);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        } catch (Exception ex) {

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value = "获取商品信息")
    @GetMapping("goodsList/{id}")
    public MessageResult<List<OrderDTO>> goodsList(@PathVariable("id") String id) {
        MessageResult<List<OrderDTO>> msgResult = new MessageResult<>();

        List<OrderDTO> list = new ArrayList<>();

        try {
            OrderDTO orderDTO = new OrderDTO();

            OrderInfo orderInfo = orderInfoService.get(id);

            if (orderInfo != null) {
                GoodsInfo goodsInfo = goodsInfoService.get(orderInfo.getGoodsId());

                if (goodsInfo != null) {
                    orderDTO.setGoodName(goodsInfo.getName());
                    String goodTypeName = "";
                    if (goodsInfo.getType().equals("1")) {
                        goodTypeName = "校车服务";
                    } else if (goodsInfo.getType().equals("2")) {
                        goodTypeName = "保险服务";
                    } else if (goodsInfo.getType().equals("3")) {
                        goodTypeName = "虹膜";
                    } else if (goodsInfo.getType().equals("4")) {
                        goodTypeName = "AI课程";
                    } else {
                        goodTypeName = "移动充值";
                    }
                    orderDTO.setGoodTypeName(goodTypeName);

                    orderDTO.setCost(orderInfo.getPayFee());

                }
                orderDTO.setId(orderInfo.getId());
                orderDTO.setPayFee(orderInfo.getPayFee());
                orderDTO.setPayStatus(orderInfo.getPayStatus());
                orderDTO.setPayStatusStr(orderInfo.getPayStatusStr());
                orderDTO.setGoodNum("1");

                if (StringUtils.isNotEmpty(orderInfo.getPayName())) {

                    if ("wechat".equals(orderInfo.getPayName())) {
                        orderDTO.setPayName("微信");
                    } else if ("alipay".equals(orderInfo.getPayName())) {
                        orderDTO.setPayName("支付宝");
                    } else {
                        orderDTO.setPayName("现金");
                    }
                }


                list.add(orderDTO);

                msgResult.setResult(true);
                msgResult.setData(list);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        } catch (Exception ex) {

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value = "获取订单操作日志")
    @GetMapping("orderLog/{id}")
    public MessageResult<List<OrderLog>> orderLog(@PathVariable("id") String id) {
        MessageResult<List<OrderLog>> msgResult = new MessageResult<>();

        List<OrderLog> list = orderLogService.findByOrderId(id);

        msgResult.setResult(true);
        msgResult.setData(list);

        return msgResult;
    }


    @ApiOperation(value = "修改订单状态")
    @PostMapping("updateOrder")
    public MessageResult<Integer> updateOrder(String id, Integer payStatus, String isOff, @RequestAttribute String subject) {
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            User user = userService.get(subject);

            OrderInfo order = orderInfoService.get(id);

            order.setPayStatus(payStatus);

            if ("0".equals(isOff)) {
                affectCount = orderInfoService.updateAndPay(order, payStatus, user);
            } else {
                affectCount = orderInfoService.updateAndPayIsOff(order, user);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


}
