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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
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.dto.BillPushDTO;
import com.jpsoft.shinestar.modules.business.dto.BillPushGoodsDTO;
import com.jpsoft.shinestar.modules.business.entity.BillPush;
import com.jpsoft.shinestar.modules.business.entity.BillPushGoods;
import com.jpsoft.shinestar.modules.business.service.BillPushGoodsService;
import com.jpsoft.shinestar.modules.business.service.BillPushService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author 墨鱼_mo
 * @date 2020-10-17 14:02
 */
@RestController
@RequestMapping("/mobile/orderInfoApi")
@Slf4j
public class OrderInfoApiController {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private CompanyPaymentInfoService companyPaymentInfoService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @Autowired
    private GoodsInfoService goodsInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private BillPushService billPushService;

    @Autowired
    private CheckinInfoService checkinInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private BillPushGoodsService billPushGoodsService;


    @PostMapping("orderInfoDetail")
    @ApiOperation(value = "通过openId查询人员(公开接口)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> orderInfoDetail(String id) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            OrderInfo orderInfo = orderInfoService.get(id);
            if (orderInfo == null) {
                throw new Exception("订单不存在");
            }
            GoodsInfo goodsInfo = goodsInfoService.get(orderInfo.getGoodsId());
            Map<String, Object> map = new HashMap<>();
            map.put("goodsInfo", goodsInfo);


            //长者信息
            PersonInfo personInfo = personInfoService.get(orderInfo.getPersonId());
            //家属信息
            PersonPopedom personPopedom = personPopedomService.get(orderInfo.getPayPopedomId());
            PersonInfo personInfo1 = personInfoService.get(personPopedom.getPersonId());

            map.put("personInfo", personInfo);
            map.put("payPersonInfo", personInfo1);
            map.put("orderInfo", orderInfo);

            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);


        } catch (Exception ex) {
            log.error(ex.getMessage());
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }


        return messageResult;


    }

    @PostMapping("orderDetail")
    @ApiOperation(value = "账单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> orderDetail(String id) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            OrderInfo orderInfo = orderInfoService.get(id);
            if (orderInfo == null) {
                throw new Exception("订单不存在");
            }

            BillPush billPush = billPushService.findByOrderId(id);

            Map<String, Object> map = new HashMap<>();
            if (billPush != null) {
            /*GoodsInfo goodsInfo = goodsInfoService.get(orderInfo.getGoodsId());
            map.put("goodsInfo",goodsInfo);*/

                //商品类别
                GoodsType goodsType = goodsTypeService.get(orderInfo.getType());
                map.put("goodsPic", goodsType.getIconPic());
                map.put("billName", billPush.getName());

                //用户信息
                PersonInfo personInfo = personInfoService.get(orderInfo.getPersonId());
                map.put("personName", personInfo.getName());
                map.put("totalFee", orderInfo.getTotalFee().toString());
                map.put("remark", billPush.getBak());
                map.put("payStatus", orderInfo.getPayStatus());

                //缴费单位
                CompanyInfo companyInfo = companyInfoService.get(billPush.getCompanyId());
                String companyName = companyInfo.getName();
                if (StringUtils.isNotBlank(companyInfo.getFullName())) {
                    companyName = companyInfo.getFullName();
                }
                map.put("companyName", companyName);
                map.put("outOrderNo", orderInfo.getOutOrderNo());
                map.put("createTime", DateUtil.format(orderInfo.getCreateTime(), "yyyy-MM-dd HH:mm"));

                //开票类型
                String invoiceName = "";
                String invoiceType = billPush.getInvoiceType();
                if (StringUtils.isNotBlank(invoiceType)){
                    invoiceName = dataDictionaryService.findNameByCatalogNameAndValue("开票类型",billPush.getInvoiceType());
                }
                map.put("invoiceType",invoiceType);
                map.put("invoiceName",invoiceName);



                //收款账户
                CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.valueOf(billPush.getCollectionAccountId()));

                map.put("cycle", companyPaymentInfo.getCycle());
                List<Map<String, Object>> mapList = new ArrayList<>();


                if (billPush.getIsOpenWechat()) {
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("text", "微信");
                    map1.put("value", "1");
                    mapList.add(map1);
                }
                if (billPush.getIsOpenAlipay()) {
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("text", "支付宝");
                    map1.put("value", "2");
                    mapList.add(map1);
                }


               /* if (StringUtils.isBlank(billPush.getCheckinInfoId())){

                    if (companyPaymentInfo.getIsOpenWechat()){
                        Map<String,Object> map1 = new HashMap<>();
                        map1.put("text","微信");
                        map1.put("value","1");
                        mapList.add(map1);
                    }

                    if (companyPaymentInfo.getIsOpenAlipay()){
                        Map<String,Object> map1 = new HashMap<>();
                        map1.put("text","支付宝");
                        map1.put("value","2");
                        mapList.add(map1);
                    }
                }else {
                    //租户
                    CheckinInfo checkinInfo = checkinInfoService.get(billPush.getCheckinInfoId());
                    if (checkinInfo.getWechatPay()){
                        Map<String,Object> map1 = new HashMap<>();
                        map1.put("text","微信");
                        map1.put("value","1");
                        mapList.add(map1);
                    }

                    if (checkinInfo.getAliPay()){
                        Map<String,Object> map1 = new HashMap<>();
                        map1.put("text","支付宝");
                        map1.put("value","2");
                        mapList.add(map1);
                    }

                }*/


                map.put("payList", mapList);
                map.put("account", companyPaymentInfo.getAccount());
                map.put("bankName", companyPaymentInfo.getBankName());
                map.put("bank", companyPaymentInfo.getBank());
                //项目
                List<BillPushGoods> billPushGoodsList = billPushGoodsService.findByBillPushId(billPush.getId());

                List<BillPushGoodsDTO> list = new ArrayList<>();
                if (billPushGoodsList.size() > 0) {
                    for (BillPushGoods billPushGoods : billPushGoodsList) {
                        GoodsInfo goodsInfo = goodsInfoService.get(billPushGoods.getGoodsId());
                        BillPushGoodsDTO billPushGoodsDTO = new BillPushGoodsDTO();
                        billPushGoodsDTO.setGoodsName(goodsInfo.getName());
                        billPushGoodsDTO.setBeginEndTime(billPushGoods.getBeginEndTime());
                        // billPushGoodsDTO.setNumStr(billPushGoods.getNumStr());

                        JSONObject detailJson = JSONObject.parseObject(billPushGoods.getDetails());
                        billPushGoodsDTO.setDetails(detailJson.getString("totalFee"));
                        billPushGoodsDTO.setStandard(detailJson.getString("standard"));
                        billPushGoodsDTO.setUnit(goodsInfo.getUnit());

                        String numStr = "";
                        try {
                            //起止详情
                            JSONObject jsonObject = JSONObject.parseObject(billPushGoods.getNumStr());

                            String start = null;
                            String end = null;
                            String total = null;
                            if (jsonObject.containsKey("start")) {
                                start = jsonObject.getString("start");
                            }
                            if (jsonObject.containsKey("end")) {
                                end = jsonObject.getString("end");
                            }
                            if (jsonObject.containsKey("total")) {
                                total = jsonObject.getString("total");
                            }
                            if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(end)) {
                                numStr = end + "-" + start + "=" + total + goodsInfo.getNumUnit();
                            }
                            if (StringUtils.isBlank(start) || StringUtils.isBlank(end)) {
                                if (StringUtils.isNotBlank(total)) {
                                    numStr = total + goodsInfo.getNumUnit();
                                } else {
                                    numStr = billPushGoods.getNumStr() + goodsInfo.getNumUnit();
                                }

                            }
                        } catch (Exception ex) {
                            numStr = billPushGoods.getNumStr() + goodsInfo.getNumUnit();
                        }


                        billPushGoodsDTO.setNumStr(numStr);

                        list.add(billPushGoodsDTO);
                    }
                }
                map.put("list", list);

                PersonInfo personInfo1 = null;
                if (StringUtils.isNotBlank(orderInfo.getPayPopedomId())) {
                    PersonPopedom personPopedom = personPopedomService.get(orderInfo.getPayPopedomId());
                    personInfo1 = personInfoService.get(personPopedom.getPersonId());
                }

                JSONObject jsonObject = new JSONObject();
                if (StringUtils.isNotBlank(orderInfo.getDetail())) {
                    jsonObject = JSONObject.parseObject(orderInfo.getDetail());
                }
                map.put("personInfo", personInfo);
                map.put("payPersonInfo", personInfo1);
                map.put("orderInfo", orderInfo);
                map.put("Detail", jsonObject);

            }
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);


        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }


        return messageResult;


    }

    @PostMapping("orderList")
    @ApiOperation(value = "账单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "状态（10：未支付，20：已支付）", required = false, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "type", value = "public（手机端管理人员查看总账单列表,个人账单不用传）", paramType = "form"),
            @ApiImplicitParam(name = "date", value = "时间（如：2020-12）", paramType = "form"),
    })
    public MessageResult<Map> orderList(String token, @RequestAttribute String subject, String status, String type, String date, @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            Map<String, Object> map = new HashMap<>();
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));

            if (!"public".equals(type)) {


                if ("10".equals(status)) {
                    Map<String, Object> searchParams = new HashMap<>();
                    searchParams.put("personId", personInfo.getId());
                    searchParams.put("payStatus", 10);
                    searchParams.put("status", "1");
                    List<Sort> sortList = new ArrayList<>();
                    sortList.add(new Sort("create_time", "desc"));
                    Page<OrderInfo> page = orderInfoService.pageSearch(searchParams, pageIndex, pageSize, false, sortList);
                    List<OrderInfo> list = page.getResult();
                    List<OrderDTO> orderDTOList = new ArrayList<>();
                    if (list.size() > 0) {
                        for (OrderInfo orderInfo : list) {
                            GoodsType goodsType = goodsTypeService.get(orderInfo.getType());
                            OrderDTO orderDTO = new OrderDTO();
                            orderDTO.setId(orderInfo.getId());
                            orderDTO.setIconPic(goodsType.getIconPic());
                            orderDTO.setGoodName(orderInfo.getBody());
                            orderDTO.setGoodTypeName(goodsType.getGoodsName());
                            orderDTO.setTotalFee(orderInfo.getTotalFee());
                            orderDTO.setCreateTime(orderInfo.getCreateTime());
                            orderDTO.setColor(goodsType.getColor());
                            orderDTOList.add(orderDTO);

                        }
                    }
                    map.put("totalPage", page.getPages());
                    map.put("pageNumber", page.getPageNum());
                    map.put("pageSize", page.getPageSize());
                    map.put("data", orderDTOList);
                    map.put("recordsTotal", page.getTotal());
                    map.put("recordsFiltered", page.getTotal());

                    messageResult.setData(map);
                    messageResult.setCode(200);
                    messageResult.setResult(true);
                }
                if ("20".equals(status)) {
                    Map<String, Object> searchParams = new HashMap<>();
                    searchParams.put("personId", personInfo.getId());
                    searchParams.put("payStatus", 20);
                    searchParams.put("status", "1");
                    List<Sort> sortList = new ArrayList<>();
                    sortList.add(new Sort("pay_time", "desc"));
                    Page<OrderInfo> page = orderInfoService.pageSearch(searchParams, pageIndex, pageSize, false, sortList);
                    List<OrderInfo> list = page.getResult();
                    List<OrderDTO> orderDTOList = new ArrayList<>();

                    if (list.size() > 0) {
                        for (OrderInfo orderInfo : list) {
                            GoodsType goodsType = goodsTypeService.get(orderInfo.getType());
                            OrderDTO orderDTO = new OrderDTO();
                            orderDTO.setId(orderInfo.getId());
                            orderDTO.setIconPic(goodsType.getIconPic());
                            orderDTO.setGoodName(orderInfo.getBody());
                            orderDTO.setGoodTypeName(goodsType.getGoodsName());
                            orderDTO.setTotalFee(orderInfo.getTotalFee());
                            orderDTO.setPayTime(orderInfo.getPayTime());
                            orderDTO.setPayName(orderInfo.getPayName());
                            orderDTO.setPayNameStr(orderInfo.getPayNameStr());
                            orderDTO.setColor(goodsType.getColor());
                            int month = DateUtil.month(new Date());
                            int payMonth = DateUtil.month(orderInfo.getPayTime());
                            if (month == payMonth) {
                                orderDTO.setMonth("本月");
                            } else {
                                orderDTO.setMonth(payMonth + 1 + "月");
                            }

                            orderDTOList.add(orderDTO);

                        }
                    }

                    map.put("totalPage", page.getPages());
                    map.put("pageNumber", page.getPageNum());
                    map.put("pageSize", page.getPageSize());
                    map.put("data", orderDTOList);
                    map.put("recordsTotal", page.getTotal());
                    map.put("recordsFiltered", page.getTotal());

                    messageResult.setData(map);
                    messageResult.setCode(200);
                    messageResult.setResult(true);

                }

            } else {

                if (StringUtils.isBlank(date)) {
                    throw new Exception("选择时间");
                }

                //账单推送时间区间
                Date beginOfMonth =  DateUtil.beginOfMonth(DateUtil.parse(date,"yyyy-MM"));
                Date endOfMonth = DateUtil.endOfMonth(DateUtil.parse(date,"yyyy-MM"));



                CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
                //公司账户
                List<CompanyPaymentInfo> companyPaymentInfoList = companyPaymentInfoService.findByFinancePersonId(personInfo.getId());
                //账户ids
           //     List<Long> paymentIds = new ArrayList<>();
                List<BillPushDTO> billPushDTOList = new ArrayList<>();
                if (companyPaymentInfoList.size() > 0) {
                    /*for (CompanyPaymentInfo companyPaymentInfo : companyPaymentInfoList) {
                        if (!paymentIds.contains(companyPaymentInfo.getId())) {
                            paymentIds.add(companyPaymentInfo.getId());
                        }
                    }*/

                    Map<String, Object> searchParams = new HashMap<>();
                    searchParams.put("companyPaymentInfoList", companyPaymentInfoList);
                    if (StringUtils.isNotBlank(status)) {
                        searchParams.put("payStatus", status);
                    }
                    searchParams.put("beginPushTime",DateUtil.format(beginOfMonth,"yyyy-MM-dd HH:mm:ss"));
                    searchParams.put("endPushTime",DateUtil.format(endOfMonth,"yyyy-MM-dd HH:mm:ss"));
                    searchParams.put("notStatus1", "0");
                    searchParams.put("notStatus2", "3");
                    List<Sort> sortList = new ArrayList<>();
                    sortList.add(new Sort("a.create_time", "desc"));
                    Page<BillPush> page = billPushService.pageSearch(searchParams, pageIndex, pageSize, sortList);


                    if (page.getResult().size() > 0) {

                        List<BillPush> billPushes = page.getResult();
                        for (BillPush billPush : billPushes) {
                            BillPushDTO billPushDTO = new BillPushDTO();
                            CompanyInfo companyInfo1 = companyInfoService.get(billPush.getCompanyId());
                            OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());
                            if (companyInfo1 != null) {
                                billPushDTO.setCompanyName(companyInfo1.getName());
                            }
                            billPushDTO.setTotalFee(orderInfo.getTotalFee());
                            billPushDTO.setPushTime(billPush.getPushTime());

                            billPushDTO.setPayStatus(orderInfo.getPayStatus());
                            billPushDTO.setOrderId(orderInfo.getId());

                           /* int month = DateUtil.month(new Date());
                            int payMonth = DateUtil.month(orderInfo.getPayTime());
                            if (month == payMonth) {
                                billPushDTO.setMonth("本月");
                            } else {
                                billPushDTO.setMonth(payMonth + 1 + "月");
                            }*/
                            billPushDTOList.add(billPushDTO);
                        }
                    }


                    map.put("totalPage", page.getPages());
                    map.put("pageNumber", page.getPageNum());
                    map.put("pageSize", page.getPageSize());
                    map.put("data", billPushDTOList);
                    map.put("recordsTotal", page.getTotal());
                    map.put("recordsFiltered", page.getTotal());
                } else {
                    map.put("totalPage", 0);
                    map.put("pageNumber", pageIndex);
                    map.put("pageSize", pageSize);
                    map.put("data", billPushDTOList);
                    map.put("recordsTotal", 0);
                    map.put("recordsFiltered", 0);
                }


                messageResult.setData(map);
                messageResult.setCode(200);
                messageResult.setResult(true);

            }


        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }


        return messageResult;


    }
}
