package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConst;
import com.bweb.excel.listener.ImportCompleteGasOrderReceiptListener;
import com.bweb.excel.model.ImportCompleteGasOrderReceiptModel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsAgentMer;
import com.hfkj.entity.BsGasOrderReceipt;
import com.hfkj.model.AgentMerAllot;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.model.UserSessionObject;
import com.hfkj.model.order.ExportGasOrderModel;
import com.hfkj.model.order.ExportGasOrderReceiptModel;
import com.hfkj.service.agent.BsAgentMerService;
import com.hfkj.service.gas.BsGasOrderReceiptService;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
import com.hfkj.sysenum.gas.GasOrderReceiptStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;

@Controller
@RequestMapping(value = "/gasOrderReceipt")
@Api(value = "加油订单业务")
public class BsGasOrderReceiptController {
    private static Logger log = LoggerFactory.getLogger(BsGasOrderReceiptController.class);
    @Resource
    private BsGasOrderReceiptService gasOrderReceiptService;
    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/success",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "开票成功")
    public ResponseData success(@RequestBody JSONObject body) {
        try {
            if (body == null
                || StringUtils.isBlank(body.getString("applyNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            gasOrderReceiptService.success(body.getString("applyNo"));

            return ResponseMsgUtil.success("申请成功");

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/fail",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "开票失败")
    public ResponseData fail(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("applyNo"))
                    || StringUtils.isBlank(body.getString("remark"))
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            gasOrderReceiptService.fail(body.getString("applyNo"),body.getString("remark"));

            return ResponseMsgUtil.success("申请成功");

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/queryReceiptList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询申请列表")
    public ResponseData queryReceiptList(@RequestParam(name = "orderNo", required = false) String orderNo,
                                         @RequestParam(name = "merName", required = false) String merName,
                                         @RequestParam(name = "contactsPhone", required = false) String contactsPhone,
                                         @RequestParam(name = "status", required = false) Integer status,
                                         @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                         @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                         @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                         @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String,Object> param = new HashMap<>();
            SecUserSessionObject sessionObject = userCenter.getSessionModel(SecUserSessionObject.class);
            if (sessionObject.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type1.getCode())) {

            } else if (sessionObject.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type4.getCode())) {
                param.put("agentId", sessionObject.getAccount().getObjectId());

            } else if (sessionObject.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type5.getCode())) {
                param.put("agentStaffId", sessionObject.getAccount().getObjectId());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
            }
            param.put("orderNo", orderNo);
            param.put("merName", merName);
            param.put("contactsPhone", contactsPhone);
            param.put("status", status);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(gasOrderReceiptService.getList(param)));

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/export",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出")
    public ResponseData export(@RequestParam(name = "orderNo", required = false) String orderNo,
                                         @RequestParam(name = "merName", required = false) String merName,
                                         @RequestParam(name = "contactsPhone", required = false) String contactsPhone,
                                         @RequestParam(name = "status", required = false) Integer status,
                                         @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                         @RequestParam(name = "createTimeE", required = false) Long createTimeE) {
        try {
            Map<String,Object> param = new HashMap<>();
            SecUserSessionObject sessionObject = userCenter.getSessionModel(SecUserSessionObject.class);
            if (sessionObject.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type1.getCode())) {

            } else if (sessionObject.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type4.getCode())) {
                param.put("agentId", sessionObject.getAccount().getObjectId());

            } else if (sessionObject.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type5.getCode())) {
                param.put("agentStaffId", sessionObject.getAccount().getObjectId());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
            }
            param.put("orderNo", orderNo);
            param.put("merName", merName);
            param.put("contactsPhone", contactsPhone);
            param.put("status", status);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

            // 查询数据
            List<BsGasOrderReceipt> dataList = gasOrderReceiptService.getList(param);
            List<ExportGasOrderReceiptModel> exportList = new ArrayList<>();
            ExportGasOrderReceiptModel exportModel;
            for (BsGasOrderReceipt data : dataList) {
                exportModel = new ExportGasOrderReceiptModel();
                exportModel.setOrderNo(data.getOrderNo());
                exportModel.setMerName(data.getMerName());
                exportModel.setOilNo(data.getOilNo());
                exportModel.setCompanyName(data.getCompanyName());
                exportModel.setTaxNo(data.getTaxNo());
                exportModel.setAmount(data.getAmount());
                exportModel.setContactsPhone(data.getContactsPhone());
                exportModel.setEmail(data.getEmail());
                exportModel.setCreateTime(data.getCreateTime());
                exportModel.setStatus(GasOrderReceiptStatusEnum.getNameByType(data.getStatus()).getManageName());
                exportList.add(exportModel);
            }   
            String fileUrl = CommonSysConst.getSysConfig().getFilesystem() + "/temporary/";
            String pathName = System.currentTimeMillis()+".xlsx";
            File file = new File(fileUrl);
            if (!file.exists()) {
                file.mkdirs();
            }
            EasyExcel.write(fileUrl+pathName)
                    .head(ExportGasOrderReceiptModel.class)
                    .sheet("加油订单开票")
                    .doWrite(exportList);
            return ResponseMsgUtil.success(pathName);

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/importComplete",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "导入完成开票的订单")
    public ResponseData importComplete(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("fileUrl"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            ImportCompleteGasOrderReceiptListener importDeviceListener = new ImportCompleteGasOrderReceiptListener();
            importDeviceListener.initData(gasOrderReceiptService);
            EasyExcel.read(SysConst.getSysConfig().getFileUrl()+File.separator+body.getString("fileUrl"), ImportCompleteGasOrderReceiptModel.class, importDeviceListener).sheet().doRead();

            return ResponseMsgUtil.success(importDeviceListener.getErrorData());

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
