package cn.superdesk.uniorder.controller.invoice.customer;


import cn.superdesk.uniorder.common.exception.UnifiedOrderRuntimeException;
import cn.superdesk.uniorder.common.exception.constants.ExceptionMsg;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.invoice.customer.InvoiceApply;
import cn.superdesk.uniorder.dto.vo.invoice.customer.InvoiceApplyCustomerPageVo;
import cn.superdesk.uniorder.dubbo.consumer.invoice.customer.InvoiceApplyCustomerDubboConsumerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description: 客户结算-发票管理
 * @Author: linjinyu
 * @CreateDate: 7/9/20 5:45 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 7/9/20 5:45 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "客户结算-发票管理", tags = {"客户结算-发票管理"})
@Slf4j
@RestController
@RequestMapping("/invoice/manager/customer/unified")
public class InvoiceManagerCustomerUnifiedController extends BaseController {

    @Autowired
    private InvoiceApplyCustomerDubboConsumerService invoiceApplyCustomerDubboConsumerService;

    /**
     * 客户结算-发票管理-列表
     *
     * @return
     */
    @ApiOperation(value = "客户结算-发票管理-列表")
    @RequestMapping(value = "/findInvoiceByPage", method = RequestMethod.POST)
    @ResponseBody
    public R<List<InvoiceApplyCustomerPageVo>> findInvoiceByPage() {

        R<List<InvoiceApplyCustomerPageVo>> response = new R<>();

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

        params.put("invoiceNumber", getString("invoiceNumber"));
        params.put("timeField", getString("timeField"));//时间查询字段

        params.put("startTime", getString("startTime"));//开始时间
        params.put("endTime", getString("endTime"));//结束时间

        params.put("invoiceStatus", getBtye("invoiceStatus"));//发票状态 0未邮寄 1已邮寄 2已作废
        params.put("backAccountStatus", getBtye("backAccountStatus"));//回款状态 0未回款 1部分回款 2全部回款
        params.put("keywordsField", getString("keywordsField"));//关键字查询字段
        params.put("keywords", getString("keywords"));//关键字查询字段
        params.put("invoiceTitle", getString("invoiceTitle"));//开票抬头
        params.put("companyName", getString("companyName"));//企业名称
        params.put("makeInvoiceStatus", new String[]{"1", "2"});//开票状态
        //addressRealname
        params.put("addressRealname", getString("addressRealname"));//收件人
        params.put("merchName", getString("merchName"));//商户名称
        params.put("purchaser", getString("purchaser"));//采购人/买家信息

        params.put("backtimestar", getString("backtimestar"));
        params.put("backtimeend", getString("backtimeend"));

        log.info("findViewByPageFocusUnified -> params: \n{}", AnJsonUtils.toJson(params));

        response = invoiceApplyCustomerDubboConsumerService.findViewByPageFocusUnified(getToken(), params, getPageNum(), getPageSize());
        return response;
    }

    /**
     * 客户结算-发票管理-头
     *
     * @return
     */
    @ApiOperation(value = "客户结算-发票管理-头")
    @RequestMapping(value = "/findInvoiceData", method = RequestMethod.POST)
    @ResponseBody
    public R findInvoiceData() {

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

        params.put("invoiceNumber", getString("invoiceNumber"));
        params.put("timeField", getString("timeField"));//时间查询字段
        params.put("startTime", getString("startTime"));//开始时间
        params.put("endTime", getString("endTime"));//结束时间
        params.put("invoiceStatus", getBtye("invoiceStatus"));//发票状态 0未邮寄 1已邮寄 2已作废
        params.put("backAccountStatus", getBtye("backAccountStatus"));//回款状态 0未回款 1部分回款 2全部回款
        params.put("keywordsField", getString("keywordsField"));//关键字查询字段
        params.put("keywords", getString("keywords"));//关键字查询字段
        params.put("invoiceTitle", getBtye("invoiceTitle"));//开票抬头
        params.put("companyName", getBtye("companyName"));//企业名称
        params.put("makeInvoiceStatus", new String[]{"1", "2"});//开票状态
        params.put("backtimestar", getString("backtimestar"));
        params.put("backtimeend", getString("backtimeend"));

        log.info("findViewHeadDataFocusUnified -> params: \n{}", AnJsonUtils.toJson(params));

        return new R(invoiceApplyCustomerDubboConsumerService.findViewHeadDataFocusUnified(getToken(), params));
    }


    /**
     * 客户结算-发票管理-导入发票信息(批量操作)
     *
     * @param excelFile
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "客户结算-发票管理-导入发票信息(批量操作)")
    @RequestMapping(value = "/importInvoiceExcel", method = RequestMethod.POST)
    @ResponseBody
    public R<String> importInvoiceExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {

        R<String> response = new R<>();

        String fileName = excelFile.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = excelFile.getInputStream();
        Workbook    wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet == null) {
            throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "Excel文件无内容");
        }
        int rowCounts = sheet.getLastRowNum();

        List<Map<String, Object>> list = new ArrayList<>();

        //通过mobile分类
        for (int i = 1; i <= rowCounts; i++) {

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

            sheet.getRow(i).getCell(0).setCellType(CellType.STRING);
            String invoiceApplySn = sheet.getRow(i).getCell(0).getStringCellValue();

            sheet.getRow(i).getCell(1).setCellType(CellType.STRING);
            String invoiceNumber = sheet.getRow(i).getCell(1).getStringCellValue();

            excelMap.put("invoiceApplySn", invoiceApplySn);
            excelMap.put("invoiceNumber", invoiceNumber);

            list.add(excelMap);
        }

        String errorMsg = invoiceApplyCustomerDubboConsumerService.importInvoiceExcel(list, getToken());

        if (StringUtils.isBlank(errorMsg)) {
            response.setCode(200);
            response.setSuccess(true);
            response.setMessage("操作成功");
        } else {
            response.setCode(500);
            response.setSuccess(false);
            response.setData(errorMsg);
            response.setMessage(errorMsg);
        }


        return response;
    }

    /**
     * 客户结算-发票管理-导入寄票信息(批量操作)
     *
     * @param excelFile
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "客户结算-发票管理-导入寄票信息(批量操作)")
    @RequestMapping(value = "/importSendInvoiceExcel", method = RequestMethod.POST)
    @ResponseBody
    public R<String> importSendInvoiceExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {

        R<String> response = new R<>();

        String fileName = excelFile.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = excelFile.getInputStream();
        Workbook    wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet == null) {
            throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "Excel文件无内容");
        }
        int rowCounts = sheet.getLastRowNum();

        List<Map<String, Object>> list = new ArrayList<>();
        // 通过mobile分类
        for (int i = 1; i <= rowCounts; i++) {
            Map<String, Object> excelMap = new HashMap<>();
            sheet.getRow(i).getCell(0).setCellType(CellType.STRING);
            String invoiceNumber = sheet.getRow(i).getCell(0).getStringCellValue();

            sheet.getRow(i).getCell(1).setCellType(CellType.STRING);
            String expressCompanyName = sheet.getRow(i).getCell(1).getStringCellValue();
            try {
                sheet.getRow(i).getCell(2).setCellType(CellType.STRING);
                String expressNo = sheet.getRow(i).getCell(2).getStringCellValue();
                excelMap.put("expressNo", expressNo);
            } catch (Exception e) {
                if (!expressCompanyName.equals("超级前台")) {
                    response.setCode(String.valueOf(e.hashCode()));
                    response.setSuccess(false);
                    response.setMessage("发票单号不可为空！");
                    return response;
                }
            }
            excelMap.put("invoiceNumber", invoiceNumber);
            excelMap.put("expressCompanyName", expressCompanyName);
            list.add(excelMap);
        }
        String errorMsg = invoiceApplyCustomerDubboConsumerService.importSendInvoiceExcel(list, getToken());

        if (StringUtils.isBlank(errorMsg)) {
            response.setCode(200);
            response.setSuccess(true);
            response.setMessage("操作成功");
        } else {
            response.setCode(500);
            response.setSuccess(false);
            response.setData(errorMsg);
            response.setMessage(errorMsg);
        }

        return response;
    }


    /**
     * 寄票登记
     *
     * @return
     */
    @ApiOperation(value = "寄票登记")
    @RequestMapping(value = "/sendInvoiceRegister", method = RequestMethod.POST)
    @ResponseBody
    public R sendInvoiceRegister() {

        String sendInvoiceRegisterListJson = request.getParameter("mailTickRegisterList");

        log.info("sendInvoiceRegister==>sendInvoiceRegisterListJson:" + sendInvoiceRegisterListJson);

        //		mailTickRegisterList: [{"id":6412,"expressCompanyId":-1,"expressNo":"dd"}]
        List<Map> sendInvoiceRegisterList = com.alibaba.fastjson.JSON.parseArray(sendInvoiceRegisterListJson, Map.class);

        invoiceApplyCustomerDubboConsumerService.sendInvoiceRegister(sendInvoiceRegisterList, getToken());

        return new R();
    }

//    /**
//     * 重新开票
//     *
//     * @return
//     */
//    @Deprecated
//    @ApiOperation(value = "重新开票")
//    @RequestMapping(value = "/invoiceAgain", method = RequestMethod.POST)
//    @ResponseBody
//    public R invoiceAgain() {
//        Map<String, Object> params = new HashMap<>();
//
//        // 发票申请Id
//        params.put("id", getString("id"));
//        invoiceApplyCustomerDubboConsumerService.opAgain(getToken(), params);
//        return new R();
//    }


    @ApiOperation(value = "设置备注2")
    @RequestMapping(value = "/setRemark2", method = RequestMethod.POST)
    @ResponseBody
    public R setRemark2() {

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

        // 发票申请Id
        Long invoiceApplyId = getLong("invoiceApplyId");
        // 备注2
        String remark2 = getString("remark2");

        InvoiceApply invoiceApply4SetRemark2 = new InvoiceApply();
        invoiceApply4SetRemark2.setId(invoiceApplyId);
        invoiceApply4SetRemark2.setRemark2(remark2);
        int ret = invoiceApplyCustomerDubboConsumerService.updateInvoiceApplyByPrimaryKeySelective(invoiceApply4SetRemark2);

        log.info("更新 备注2 结果: {}", ret);

        return new R();
    }

    /**
     *
     * 积分结算 > 发票管理 > 寄票登记 在用
     * 快递搜索
     *
     * @return
     */
    @ApiOperation(value = "快递搜索")
    @RequestMapping(value = "/findExpressCompany", method = RequestMethod.POST)
    @ResponseBody
    public R findExpressCompany() {
        Map<String, Object> params = new HashMap<>();
        return new R(invoiceApplyCustomerDubboConsumerService.findExpressCompany());
    }

}
