package com.dxhy.base.controller;

import com.dxhy.api.model.config.Tax;
import com.dxhy.base.service.tdxrecordinvoice.BaseIRzTDxRecordInvoiceService;
import com.dxhy.base.service.tdxrecordinvoice.BaseIYqfprzService;
import com.dxhy.base.service.tdxrecordinvoice.BaseIYqsqService;
import com.dxhy.common.aspect.SysLog;
import com.dxhy.common.constant.CommonConstants;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.util.UserInfoUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 *
 * 逾期申请入口
 *
 * @author 张宏
 * @date 2019年5月8日
 */

@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaLowerCamelCaseVariableNaming"})
@RestController
@RequestMapping("yqsq")
@Slf4j
public class BaseYqsqController extends AbstractController {

    @Resource
    private BaseIYqsqService baseIYqsqService;

    @Resource
    private BaseIRzTDxRecordInvoiceService baseIRzTDxRecordInvoiceService;

    @Resource
    private BaseIYqfprzService baseIYqfprzService;

    /**
     * 逾期发票录入
     *
     * @param datalist
     *            请求参数
     * @return 返回结果
     */
    @PostMapping("/yqlr")
    public ResponseEntity<?> listYqfplr(@RequestBody String datalist) {
        if (StringHelper.isBlank(datalist)) {
            return ResponseEntity.ok(R.error("请传入操作记录！"));
        }

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

        List<String> gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
        pramsMap.put("gfsh", gfshList);
        pramsMap.put("taxList", getUserInfo().getOrg());
        pramsMap.put("datalist", datalist);
        pramsMap.put("dbName", getUserInfo().getDbName());
        pramsMap.put("company", getUserInfo().getCompany());

        try {

            return ResponseEntity.ok(R.ok().put("data", baseIYqsqService.selectByYqsqlb(pramsMap)));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 逾期发票查询
     *
     * @return 返回结果
     */
    @GetMapping("/yqlrcx")
    public ResponseEntity<?> listYqlrcx(HttpServletRequest req,
        @RequestParam(required = false, defaultValue = "1") int curr,
        @RequestParam(required = false, defaultValue = "10") int size) {
        String gfsh = req.getParameter("gfsh");
        String fplx = req.getParameter("fplx");
        String xfmc = req.getParameter("xfmc");
        String fphm = req.getParameter("fphm");
        String kprqq = req.getParameter("kprqq");
        String kprqz = req.getParameter("kprqz");

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

        pramsMap.put("dbName", getUserInfo().getDbName());
        List<String> gfshList = new ArrayList<>();
        if (!"99".equals(gfsh) && StringUtils.isNotBlank(gfsh)) {
            gfshList.add(gfsh);
        } else {
            gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
        }
        pramsMap.put("gfsh", gfshList);

        if (!StringUtils.isBlank(fplx)) {
            if (!"99".equals(fplx)) {
                pramsMap.put("fplx", fplx);
            }
        } else {
            return ResponseEntity.ok(R.error("发票类型不能为空！"));
        }

        if (!StringUtils.isBlank(xfmc)) {
            pramsMap.put("xfmc", xfmc);
        }

        if (!StringUtils.isBlank(fphm)) {
            pramsMap.put("fphm", fphm);
        }

        if (!StringUtils.isBlank(kprqq)) {
            pramsMap.put("kprqq", kprqq);
        } else {
            return ResponseEntity.ok(R.error("开票日期不能为空！"));
        }
        if (!StringUtils.isBlank(kprqz)) {
            pramsMap.put("kprqz", kprqz);
        } else {
            return ResponseEntity.ok(R.error("开票日期不能为空！"));
        }

        try {
            return ResponseEntity.ok(R.ok().put("data", baseIYqsqService.selectByCxtj(pramsMap, curr, size)));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 逾期发票查询
     *
     * @param map
     *            请求参数
     * @return 返回结果
     */
    @PostMapping("/yqcx")
    @SysLog("调用逾期发票查询接口")
    public ResponseEntity<?> listYqfpcx(@RequestBody Map<String, Object> map) {
        String gfsh = (String)map.get("gfsh");
        String fplx = (String)map.get("fplx");
        String invoiceSource = (String)map.get("invoiceSource");
        String xfmc = (String)map.get("xfmc");
        String fphm = (String)map.get("fphm");
        String kprqq = (String)map.get("kprqq");
        String kprqz = (String)map.get("kprqz");
        int curr = (int)map.get("curr");
        int size = (int)map.get("size");

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

        pramsMap.put("dbName", getUserInfo().getDbName());
        List<Tax> taxList = getUserInfo().getOrg();
        pramsMap.put("taxList", taxList);

        List<String> gfshList = new ArrayList<>();
        List<Tax> newTaxList = new ArrayList<>();
        if (!"99".equals(gfsh) && StringUtils.isNotBlank(gfsh)) {
            for (Tax tax : taxList) {
                if (gfsh.equals(tax.getTaxno())) {
                    String upgradeStatus = tax.getUpgradeStatus();
                    if ("1".equals(upgradeStatus)) {
                        gfshList.add(gfsh);
                    }
                }
            }
        } else {
            for (Tax tax : taxList) {
                String upgradeStatus = tax.getUpgradeStatus();
                if ("1".equals(upgradeStatus)) {
                    newTaxList.add(tax);
                }
            }
            gfshList = UserInfoUtil.getGfshAll(newTaxList);
        }
        pramsMap.put("gfsh", gfshList);

        if (!StringUtils.isBlank(fplx)) {
            if (!"99".equals(fplx)) {
                pramsMap.put("fplx", fplx);
            }
        } else {
            return ResponseEntity.ok(R.error("发票类型不能为空！"));
        }
        if (invoiceSource != null) {
            if (!"99".equals(invoiceSource)) {
                pramsMap.put("invoiceSource", invoiceSource);
            }
        }

        if (!StringUtils.isBlank(xfmc)) {
            pramsMap.put("xfmc", xfmc);
        }

        if (!StringUtils.isBlank(fphm)) {
            pramsMap.put("fphm", fphm);
        }

        if (!StringUtils.isBlank(kprqq)) {
            pramsMap.put("kprqq", kprqq);
        } else {
            return ResponseEntity.ok(R.error("开票日期不能为空！"));
        }
        if (!StringUtils.isBlank(kprqz)) {
            pramsMap.put("kprqz", kprqz);
        } else {
            return ResponseEntity.ok(R.error("开票日期不能为空！"));
        }

        try {
            return ResponseEntity.ok(R.ok().put("data", baseIYqfprzService.selectByYqcxtj(pramsMap, curr, size)));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 逾期发票认证
     *
     * @param map
     *            请求参数
     * @return 返回结果
     */
    @PostMapping("/yqrz")
    @SysLog("调用逾期发票认证接口")
    public ResponseEntity<?> updateYqfprz(@RequestBody Map<String, Object> map) {
        String uuids = (String)map.get("uuids");
        String dkses = (String)map.get("dkses");
        int curr = 1;
        int size = 50;
        int count = 0;
        Map<String, Object> pramsMap = new HashMap<>(16);
        pramsMap.put("name", getUserName());
        List<String> gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
        pramsMap.put("dbName", getUserInfo().getDbName());
        if (!gfshList.isEmpty()) {
            pramsMap.put("gfsh", gfshList);
        } else {
            return ResponseEntity.ok(R.error("购方信息不能为空！"));
        }
        if (!StringHelper.isBlank(uuids)) {
            pramsMap.put("uuids", uuids);
        } else {
            return ResponseEntity.ok(R.error("请先选择要认证的数据！"));
        }
        if (!StringHelper.isBlank(dkses)) {
            pramsMap.put("dkses", dkses);
        }
        try {
            return ResponseEntity
                .ok(R.ok().put("data", baseIRzTDxRecordInvoiceService.identifiByIds(pramsMap, curr, size, count)));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 逾期批量导入模板下载
     *
     * @param response
     *            请求参数
     * @throws IOException
     *             异常
     */

    @GetMapping("/yqdrmb")
    public void modelExport(HttpServletResponse response) throws IOException {

        /*
         * 文件名前缀
         */
        String fileNamePrefix = "importYqlr";
        /*
         * 文件名后缀
         */
        String fileNameSurfix = ".xls";
        /*
         * 文件名中间分隔符
         */
        String fileSplit = "_";
        // 导出文件名

        HSSFWorkbook wb = new HSSFWorkbook();

        HSSFSheet sheet = wb.createSheet("sheet1");
        sheet.setColumnWidth(0, 2500);
        sheet.setColumnWidth(1, 5000);
        sheet.setColumnWidth(2, 5000);
        sheet.setColumnWidth(3, 5000);
        sheet.setColumnWidth(4, 5000);
        sheet.setColumnWidth(5, 5000);
        sheet.setColumnWidth(6, 5000);
        sheet.setColumnWidth(7, 5000);
        HSSFRow row1 = sheet.createRow(0);
        // 创建单元格并设置单元格内容
        row1.createCell(0).setCellValue("序号");
        row1.createCell(1).setCellValue("发票代码");
        row1.createCell(2).setCellValue("发票号码");
        row1.createCell(3).setCellValue("金额");
        row1.createCell(4).setCellValue("开票日期");
        row1.createCell(5).setCellValue("税额");
        row1.createCell(6).setCellValue("销方税号");
        row1.createCell(7).setCellValue("购方税号");

        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        String ftpFileName = fileSplit + fileNamePrefix + fileSplit + DateUtils.getStringDateShort() + fileSplit
            + (new Date()).getTime() + fileNameSurfix;
        response.setHeader("Content-disposition", "attachment; filename=" + ftpFileName);
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();

    }
}
