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

import cn.hutool.core.collection.CollUtil;
import cn.superdesk.uniorder.common.bizScene.invoice.customer.InvoiceApplyCustomerScene;
import cn.superdesk.uniorder.common.exception.UnifiedOrderRuntimeException;
import cn.superdesk.uniorder.common.exception.constants.ExceptionMsg;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dto.param.invoice.customer.InvoiceApplyCustomerQueryCriteria;
import cn.superdesk.uniorder.dto.param.invoice.customer.InvoiceApplyCustomerQueryCriteriaV2_1;
import cn.superdesk.uniorder.dto.vo.invoice.customer.InvoiceApplyCustomerHeadDataVoV2_1;
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: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 7/29/20 7:31 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 7/29/20 7:31 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "积分结算-发票管理", tags = {"积分结算-发票管理"})
@Slf4j
@RestController
@RequestMapping("/invoice/manager/customer/score")
public class InvoiceManagerCustomerScoreController extends BaseController {

    @Autowired
    private InvoiceApplyCustomerDubboConsumerService invoiceApplyCustomerDubboConsumerService;

    /**
     * 积分结算-发票管理-列表
     * <p>
     * /invoice/manager/customer/score/findInvoiceListByPage
     *
     * @return
     */
    @ApiOperation(value = "积分结算-发票管理-列表 - 积分结算2.0需求已整改-mark by linjinyu at 20211119")
    @RequestMapping(value = "/findInvoiceListByPage", method = RequestMethod.POST)
    public R<List<InvoiceApplyCustomerPageVo>> findInvoiceByPage(@RequestBody InvoiceApplyCustomerQueryCriteria queryCriteria) {

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

//		criteria.setMakeInvoiceStatus(Arrays.asList(InvoiceApplyMakeInvoiceStatusEnum.已开票.getKey(), InvoiceApplyMakeInvoiceStatusEnum.重新开票.getKey()));
        queryCriteria.setInvoiceProgressingStatus(InvoiceApplyCustomerScene.statusV2_0Last_List_InvoiceProgressingSceneManagerList());

        response = invoiceApplyCustomerDubboConsumerService.findViewByPageFocusScore(queryCriteria, queryCriteria.getPageNumber(), queryCriteria.getPageSize(), getToken());
        return response;
    }

    /**
     * 积分结算-发票管理-头
     * <p>
     * /invoice/manager/customer/score/findInvoiceHeadData
     *
     * @return
     */
    @ApiOperation(value = "积分结算-发票管理-头 - 积分结算2.0需求已整改-mark by linjinyu at 20211119")
    @RequestMapping(value = "/findInvoiceHeadData", method = RequestMethod.POST)
    public R findInvoiceHeadData(@RequestBody InvoiceApplyCustomerQueryCriteria queryCriteria) {

//		criteria.setMakeInvoiceStatus(Arrays.asList(InvoiceApplyMakeInvoiceStatusEnum.已开票.getKey(), InvoiceApplyMakeInvoiceStatusEnum.重新开票.getKey()));

        queryCriteria.setInvoiceProgressingStatus(InvoiceApplyCustomerScene.statusV2_0Last_List_InvoiceProgressingSceneManagerList());

        return new R(invoiceApplyCustomerDubboConsumerService.findViewHeadDataFocusScore(queryCriteria, getToken()));
    }

    /****************************************** 积分结算2.1 start ******************************************/


    @ApiOperation(value = "op页面List-积分结算-发票管理-积分结算2.1 已适配")
    @RequestMapping(value = "/findInvoiceListByPage/V2_1", method = RequestMethod.POST)
    public R<List<InvoiceApplyCustomerPageVo>> findInvoiceListByPageV2_1(@RequestBody InvoiceApplyCustomerQueryCriteriaV2_1 queryCriteria) {

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

        if (CollUtil.isEmpty(queryCriteria.getInvoiceProgressingStatusSelected())) {
            queryCriteria.setInvoiceProgressingStatusSelected(
                    InvoiceApplyCustomerScene.statusV2_1Begin_List_InvoiceProgressingSceneManagerList()
            );
        }

        result = invoiceApplyCustomerDubboConsumerService.findInvoiceListByPageFocusScoreV2_1(queryCriteria, getToken());

        return result;
    }

    @ApiOperation(value = "op页面Head-积分结算-发票管理-积分结算2.1 已适配")
    @RequestMapping(value = "/findInvoiceHeadData/V2_1", method = RequestMethod.POST)
    public R<InvoiceApplyCustomerHeadDataVoV2_1> findInvoiceHeadDataV2_1(@RequestBody InvoiceApplyCustomerQueryCriteriaV2_1 queryCriteria) {

        if (CollUtil.isEmpty(queryCriteria.getInvoiceProgressingStatusSelected())) {
            queryCriteria.setInvoiceProgressingStatusSelected(
                    InvoiceApplyCustomerScene.statusV2_1Begin_List_InvoiceProgressingSceneManagerList()
            );
        }

        return ResponseResultOuterUtils.createSuccesResult(
                "",
                invoiceApplyCustomerDubboConsumerService.findInvoiceHeadDataFocusScoreV2_1(queryCriteria, getToken())
        );
    }

    /****************************************** 积分结算2.1   end ******************************************/

    /**
     * opt 寄票登记
     * /invoice/manager/customer/score/sendInvoiceRegister
     *
     * @return
     */
    @ApiOperation(value = "opt 寄票登记 - 积分结算2.0需求未整改-mark by linjinyu at 20211119")
    @RequestMapping(value = "/sendInvoiceRegister", method = RequestMethod.POST)
    public R sendInvoiceRegister() {

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

//		mailTickRegisterList: [{"id":6412,"expressCompanyId":-1,"expressNo":"dd"}]

        log.info("sendInvoiceRegister params :\n{}", sendInvoiceRegisterListJson);

        List<Map> sendInvoiceRegisterList = com.alibaba.fastjson.JSON.parseArray(sendInvoiceRegisterListJson, Map.class);

        invoiceApplyCustomerDubboConsumerService.sendInvoiceRegister(sendInvoiceRegisterList, getToken());

        return ResponseResultOuterUtils.createSuccesResult();
    }

//	/**
//	 * opt 重新开票 (过 20200730 1711)
//	 * /invoice/manager/customer/score/invoiceAgain
//	 *
//	 * @return
//	 */
//	@ApiOperation(value = "opt 重新开票 - 积分结算2.0需求未整改-mark by linjinyu at 20211119")
//	@RequestMapping(value = "/invoiceAgain", method = RequestMethod.POST)
//	public R invoiceAgain() {
//
//		Map<String, Object> params = new HashMap<>();
//		// 发票申请Id
//		params.put("id", getString("id"));
//
//		log.info("sendInvoiceRegister params :\n{}", params);
//
//		invoiceApplyCustomerDubboConsumerService.opAgain(getToken(), params);
//		return ResponseResultOuterUtils.createSuccesResult();
//	}


    /**
     * 积分结算-发票管理-导入发票信息(批量操作)
     * /invoice/manager/customer/score/importInvoiceExcel
     *
     * @param excelFile
     * @return
     * @throws Exception
     */
    @Deprecated
    @ApiOperation(value = "积分结算-发票管理-导入发票信息(批量操作) - 积分结算2.0需求未整改-mark by linjinyu at 20211119")
    @RequestMapping(value = "/importInvoiceExcel", method = RequestMethod.POST)
    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;
    }

    /**
     * 积分结算-发票管理-导入寄票信息(批量操作)
     * /invoice/manager/customer/score/importSendInvoiceExcel
     *
     * @param excelFile
     * @return
     * @throws Exception
     */
    @Deprecated
    @ApiOperation(value = "积分结算-发票管理-导入寄票信息(批量操作) 积分结算2.0需求未整改-mark by linjinyu at 20211119")
    @RequestMapping(value = "/importSendInvoiceExcel", method = RequestMethod.POST)
    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;
    }
}
