package com.dxhy.extend.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.dxhy.auth.client.annotation.IgnoreClientToken;
import com.dxhy.auth.client.annotation.IgnoreUserToken;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.vo.TaxOrgCode;
import com.dxhy.common.vo.UserInfo;
import com.dxhy.extend.entity.PullRecordReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dxhy.common.aspect.SysLog;
import com.dxhy.common.constant.CommonConstants;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.util.UserInfoUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.R;
import com.dxhy.extend.service.pool.ExtInvoicePoolService;

import lombok.extern.slf4j.Slf4j;

/**
 * 票池采集-lxx
 *
 * @author dxhy
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@RestController
@RequestMapping("modules/invoicepool")
@Slf4j
public class ExtInvoicePoolController extends AbstractController {

    @Resource
    private ExtInvoicePoolService extInvoicePoolService;

    /**
     * 增值税发票采集
     *
     * @param pramsMap
     *            查询条件
     * @return 返回
     */
    @RequestMapping("/listAddTaxInvoice")
    @SysLog("增值税发票采集")
    public ResponseEntity<R> listAddTaxInvoice(@RequestBody Map<String, Object> pramsMap) {
        pramsMap.put("dbName", getUserInfo().getDbName());

        List<String> gfshList = new ArrayList<>();
        if (!"99".equals(pramsMap.get("gfsh")) && pramsMap.get("gfsh") != null && !"".equals(pramsMap.get("gfsh"))) {
            gfshList.add(pramsMap.get("gfsh").toString());
        } else {
            gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
            if (gfshList.size() == 0) {
                return ResponseEntity.ok(R.ok().put("data", ""));
            }
        }
//        gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
        boolean flag = checkList(gfshList);
        if (flag){
            pramsMap.put("sign","88");
            log.info("登陆账号无税号");
        }
//        if (gfshList.size() == 0) {
//            return ResponseEntity.ok(R.ok().put("data", ""));
//        }
        pramsMap.put("gfsh", gfshList);
        if (pramsMap.get("cjksyf") != null && !"".equals(pramsMap.get("cjksyf"))) {
            pramsMap.put("cjksyf", DateUtils.getMorning(DateUtils.strToDate(pramsMap.get("cjksyf").toString())));
        }
        if (pramsMap.get("cjjsyf") != null && !"".equals(pramsMap.get("cjjsyf"))) {
            pramsMap.put("cjjsyf", DateUtils.getNight(DateUtils.strToDate(pramsMap.get("cjjsyf").toString())));
        }
        if (pramsMap.get("kpksrq") != null && !"".equals(pramsMap.get("kpksrq"))) {
            pramsMap.put("kpksrq", DateUtils.getMorning(DateUtils.strToDate(pramsMap.get("kpksrq").toString())));
        }

        if (pramsMap.get("accountPeriod") != null && !"".equals(pramsMap.get("accountPeriod"))) {
            String accountPeriod = pramsMap.get("accountPeriod").toString().substring(0,7);
            pramsMap.put("accountPeriod", accountPeriod);
            log.info("accountPeriod:{}",accountPeriod);
        }

        if (pramsMap.get("kpjsrq") != null && !"".equals(pramsMap.get("kpjsrq"))) {
            pramsMap.put("kpjsrq", DateUtils.getNight(DateUtils.strToDate(pramsMap.get("kpjsrq").toString())));
        }
        if (pramsMap.get("skssq") != null && !"".equals(pramsMap.get("skssq")) && "1".equals(pramsMap.get("rzzt"))) {
            pramsMap.put("skssq", pramsMap.get("skssq").toString().replace("-", ""));
        } else {
            pramsMap.put("skssq", "");
        }
        if (pramsMap.get("qsyf") == null && "".equals(pramsMap.get("qsyf")) && !"1".equals(pramsMap.get("qszt"))) {
            pramsMap.put("qsyf", "");
        }
        if (pramsMap.get("inAccountMonth") == null && "".equals(pramsMap.get("inAccountMonth"))
            && !"1".equals(pramsMap.get("inAccountStatus"))) {
            pramsMap.put("inAccountMonth", "");
        }
        int curr = (int)pramsMap.get("curr");
        int size = (int)pramsMap.get("size");
        List<String> companyCodes = new ArrayList<>();
        String companyCode = (String) pramsMap.get("companyCode");
        if(StringUtils.isNotEmpty(companyCode) && !"99".equals(companyCode) && !"88".equals(companyCode)) {
            pramsMap.put("companyCode", companyCode);
            companyCodes.add(companyCode);
//            gfshList = extInvoicePoolService.getGfshList(gfshList,companyCodes);
            pramsMap.put("gfsh", gfshList);
        }else if(StringUtils.isNotEmpty(companyCode) && "99".equals(companyCode)){
            pramsMap.put("companyCode", companyCode);
            companyCodes = getUserInfo().getCompanyCodes();
            pramsMap.put("companyCodes", companyCodes);
//            gfshList = extInvoicePoolService.getGfshList(gfshList,companyCodes);
            pramsMap.put("gfsh", gfshList);
            log.info("组织机构====>{}", companyCodes);
        }else if(StringUtils.isNotEmpty(companyCode) && "88".equals(companyCode)){
            pramsMap.put("companyCode", companyCode);
            log.info("组织机构====>{}", companyCodes);
        }

        try {
            return ResponseEntity.ok(R.ok().put("data", extInvoicePoolService.listAddTax(pramsMap, curr, size)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 进项票池摊销记录
     *
     * @param pramsMap
     *            查询条件
     * @return 返回
     */
    @RequestMapping("/amortizeRecord")
    @SysLog("进项票池摊销记录")
    public ResponseEntity<R> amortizeRecord(@RequestBody Map<String, Object> pramsMap) {
        pramsMap.put("dbName", getUserInfo().getDbName());
        try {
            return ResponseEntity.ok(R.ok().put("data", extInvoicePoolService.amortizeRecord(pramsMap)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 其他票据采集
     *
     * @param pramsMap
     *            查询条件
     * @return 返回
     */
    @RequestMapping("/listOtherInvoice")
    @SysLog("其他发票采集")
    public ResponseEntity<R> listOtherInvoice(@RequestBody Map<String, Object> pramsMap) {
        pramsMap.put("dbName", getUserInfo().getDbName());

        log.info("其他发票采集接收参数 {}",pramsMap);
        List<String> gfshList = new ArrayList<>();
        List<String> invoiceTypeList = new ArrayList<>();
        if (!"99".equals(pramsMap.get("gfsh")) && pramsMap.get("gfsh") != null && !"".equals(pramsMap.get("gfsh"))) {
            gfshList.add(pramsMap.get("gfsh").toString());
        } else {
            gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
            if (gfshList.size() == 0) {
                return ResponseEntity.ok(R.ok().put("data", ""));
            }
        }
        pramsMap.put("gfsh", gfshList);
        if (pramsMap.get("cjksyf") != null && !"".equals(pramsMap.get("cjksyf"))) {
            pramsMap.put("cjksyf", DateUtils.getMorning(DateUtils.strToDate(pramsMap.get("cjksyf").toString())));
        }
        if (pramsMap.get("cjjsyf") != null && !"".equals(pramsMap.get("cjjsyf"))) {
            pramsMap.put("cjjsyf", DateUtils.getNight(DateUtils.strToDate(pramsMap.get("cjjsyf").toString())));
        }
        if (pramsMap.get("kpksrq") != null && !"".equals(pramsMap.get("kpksrq"))) {
            pramsMap.put("kpksrq", DateUtils.getMorning(DateUtils.strToDate(pramsMap.get("kpksrq").toString())));
        }
        if (pramsMap.get("kpjsrq") != null && !"".equals(pramsMap.get("kpjsrq"))) {
            pramsMap.put("kpjsrq", DateUtils.getNight(DateUtils.strToDate(pramsMap.get("kpjsrq").toString())));
        }
        if (pramsMap.get("qsyf") == null && "".equals(pramsMap.get("qsyf")) && !"1".equals(pramsMap.get("qszt"))) {
            pramsMap.put("qsyf", "");
        }
        if (pramsMap.get("accountPeriod") != null && !"".equals(pramsMap.get("accountPeriod"))) {
            String accountPeriod = pramsMap.get("accountPeriod").toString().substring(0,7);
            pramsMap.put("accountPeriod", accountPeriod);
            log.info("accountPeriod:{}",accountPeriod);
        }
        String companyCode = (String) pramsMap.get("companyCode");
        if (StringHelper.isNotBlank(companyCode) && "99".equals(companyCode)){
            pramsMap.put("companyCodes",getUserInfo().getCompanyCodes());
            log.info("组织编码===>{}", pramsMap.get("companyCodes"));
        }
        int curr = (int)pramsMap.get("curr");
        int size = (int)pramsMap.get("size");
        try {
            log.info("其他发票采集接收参数 {}" ,pramsMap);
            return ResponseEntity.ok(R.ok().put("data", extInvoicePoolService.listOther(pramsMap, curr, size)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 销项票池
     *
     * @param pramsMap
     *            查询条件
     * @return 返回
     */
    @RequestMapping("/listSaleInvoice")
    @SysLog("销项票池采集")
    public ResponseEntity<R> listSaleInvoice(@RequestBody Map<String, Object> pramsMap) {
        pramsMap.put("dbName", getUserInfo().getDbName());

        List<String> gfshList = new ArrayList<>();
        if (!"99".equals(pramsMap.get("gfsh")) && pramsMap.get("gfsh") != null && !"".equals(pramsMap.get("gfsh"))) {
            gfshList.add(pramsMap.get("gfsh").toString());
        } else {
            gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
            if (gfshList.size() == 0) {
                return ResponseEntity.ok(R.ok().put("data", ""));
            }
        }

//        gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
        boolean flag = checkList(gfshList);
        if (flag){
            pramsMap.put("sign","88");
            log.info("登陆账号无税号");
        }
//        if (gfshList.size() == 0) {
//                return ResponseEntity.ok(R.ok().put("data", ""));
//            }
        pramsMap.put("taxno", gfshList);
        if (pramsMap.get("cjksyf") != null && !"".equals(pramsMap.get("cjksyf"))) {
            pramsMap.put("cjksyf", DateUtils.getMorning(DateUtils.strToDate(pramsMap.get("cjksyf").toString())));
        }
        if (pramsMap.get("cjjsyf") != null && !"".equals(pramsMap.get("cjjsyf"))) {
            pramsMap.put("cjjsyf", DateUtils.getNight(DateUtils.strToDate(pramsMap.get("cjjsyf").toString())));
        }
        if (pramsMap.get("kpksrq") != null && !"".equals(pramsMap.get("kpksrq"))) {
            pramsMap.put("kpksrq", DateUtils.getMorning(DateUtils.strToDate(pramsMap.get("kpksrq").toString())));
        }
        if (pramsMap.get("kpjsrq") != null && !"".equals(pramsMap.get("kpjsrq"))) {
            pramsMap.put("kpjsrq", DateUtils.getNight(DateUtils.strToDate(pramsMap.get("kpjsrq").toString())));
        }

        if (pramsMap.get("qsyf") == null && "".equals(pramsMap.get("qsyf")) && !"1".equals(pramsMap.get("qszt"))) {
            pramsMap.put("qsyf", "");
        }
        if (pramsMap.get("inAccountMonth") == null && "".equals(pramsMap.get("inAccountMonth"))
            && !"1".equals(pramsMap.get("inAccountStatus"))) {
            pramsMap.put("inAccountMonth", "");
        }
        if (pramsMap.get("accountPeriod") != null && !"".equals(pramsMap.get("accountPeriod"))) {
            String accountPeriod = pramsMap.get("accountPeriod").toString().substring(0,7);
            pramsMap.put("accountPeriod", accountPeriod);
            log.info("accountPeriod:{}",accountPeriod);
        }
        int curr = (int)pramsMap.get("curr");
        int size = (int)pramsMap.get("size");
        String companyCode = (String) pramsMap.get("companyCode");
        if (StringHelper.isNotBlank(companyCode) && "99".equals(companyCode)){
            pramsMap.put("companyCodes",getUserInfo().getCompanyCodes());
        }
        try {
            return ResponseEntity.ok(Objects
                .requireNonNull(R.ok().put("data", extInvoicePoolService.listSaleInvoice(pramsMap, curr, size))));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 销项票池优惠政策
     *
     * @return 返回
     */
    @RequestMapping("/incentiveFlagList")
    @SysLog("销项票池优惠政策查询")
    public ResponseEntity<R> incentiveFlagList() {
        try {
            return ResponseEntity
                .ok(R.ok().put("data", extInvoicePoolService.incentiveFlagList(getUserInfo().getDbName())));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }
    /**
     * 拉取记录列表获取
     */

    @RequestMapping("getPullRecordList")
    public ResponseEntity<R> getPullRecordList(@RequestBody PullRecordReq pullRecordReq){
        try{
            if(pullRecordReq.getSm().equals("99")){
                pullRecordReq.setSm("");
            }
            if(pullRecordReq.getCompanyCode().equals("99")){
                List<TaxOrgCode> orgCodes = getUserInfo().getOrgCodes();
                List<String> collect = orgCodes.stream().map(TaxOrgCode::getOrgCode).collect(Collectors.toList());
                pullRecordReq.setOrgCode(collect);
                pullRecordReq.setCompanyCode("");
            }
            if(pullRecordReq.getAccountPeriod()!=null && pullRecordReq.getAccountPeriod()!=""){
                String accountPeriod = pullRecordReq.getAccountPeriod();
                if(accountPeriod != null && StringUtils.isNoneBlank(accountPeriod) && accountPeriod.contains("-")) {
                    String[] split = accountPeriod.split("-");
                    if (split[1].startsWith("0")) {
                        String replace = split[1].replace("0", "");
                        pullRecordReq.setAccountPeriod(split[0] + "-" + replace);
                    }
                }
            }
            return ResponseEntity.ok(R.ok().put("data",extInvoicePoolService.selectPullRecord(pullRecordReq)));
        }catch (Exception e){
            e.printStackTrace();
            log.error("",e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));

        }

    }


    public static void main(String[] args) {
        String str ="2022-04";
        String[] split = str.split("-");
        if(split[1].startsWith("0")){
            String replace = split[1].replace("0", "");
            System.out.println(replace);
        }
    }
    public boolean checkList(List<String> list) {
        boolean flag =false;
        if (list == null || list.isEmpty()){
            flag = true;
        }else {
            String s = list.toString().replace("[","").replace("]","");
            if (StringHelper.isBlank(s)){
                flag = true;
            }
            if (StringHelper.isNotBlank(s) && s.contains(",")){
                String replace = s.replace(",", "");
                if (StringHelper.isBlank(replace)){
                    flag = true;
                }
            }
        }
        return flag;
    }
}
