package cn.superdesk.uniorder.controller._thirdpart.szhtxx.paperInvoice;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.superdesk.libs.common.json.JsonUtils;
import cn.superdesk.uniorder.common.enums.invoice.customer.InvoiceApplyCustomerBackAccountStatusEnum;
import cn.superdesk.uniorder.common.numerical.AnBigDecimalUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.common.security.JwtUtil;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.invoice.customer.InvoiceApply;
import cn.superdesk.uniorder.dao.entity.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxExtendInfo;
import cn.superdesk.uniorder.dao.entity.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfo;
import cn.superdesk.uniorder.dto.param.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxQueryCriteria;
import cn.superdesk.uniorder.dto.param.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoOpEditForm;
import cn.superdesk.uniorder.dto.param.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoOpSetRemark2Form;
import cn.superdesk.uniorder.dto.param.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoParam;
import cn.superdesk.uniorder.dto.param.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoQueryCriteria;
import cn.superdesk.uniorder.dto.vo.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxListItemVo;
import cn.superdesk.uniorder.dto.vo.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoListItemVo;
import cn.superdesk.uniorder.dubbo.consumer.invoice.customer.InvoiceApplyCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxExtendInfoDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoDubboConsumerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * @Description:
 * @Author: linjinyu
 * @Email linjinyu@avic-s.com
 * @CreateDate: 2022-05-25 18:50:54
 * @UpdateUser: linjinyu
 * @UpdateDate: 2022-05-25 18:50:54
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */

@Api(value = "第三方-深圳航信纸质票-红票信息库", tags = {"第三方-深圳航信纸质票-红票信息库"})
@Slf4j
@RestController
@RequestMapping("/thirdpart/szhtxx/paperInvoiceFptxx/RedTaxInfo")
public class SzhtxxPaperInvoiceRedTaxInfoController extends BaseController {

    @Autowired
    private SzhtxxPaperInvoiceRedTaxInfoDubboConsumerService szhtxxPaperInvoiceRedTaxInfoDubboConsumerService;

    @Autowired
    private SzhtxxElectronicInvoiceFptxxDubboConsumerService           szhtxxElectronicInvoiceFptxxDubboConsumerService;
    @Autowired
    private SzhtxxElectronicInvoiceFptxxExtendInfoDubboConsumerService szhtxxElectronicInvoiceFptxxExtendInfoDubboConsumerService;

    @Autowired
    private InvoiceApplyCustomerDubboConsumerService invoiceApplyCustomerDubboConsumerService;

//    @ApiOperation(value = "分页查询 - 默认不用")
//    @RequestMapping(value = "listByObscure", method = RequestMethod.POST)
//    @ResponseBody
//    public R<List<SzhtxxPaperInvoiceRedTaxInfo>> pageQuerySzhtxxPaperInvoiceRedTaxInfo(@RequestBody PageQueryParam param) {
//
//        log.info("pageQuerySzhtxxPaperInvoiceRedTaxInfo:\n{}", JsonUtils.toJson(param));
//
//        R<List<SzhtxxPaperInvoiceRedTaxInfo>> result = new R<>();
//
//        // TODO 参数合法性判定
//
//        result = szhtxxPaperInvoiceRedTaxInfoDubboConsumerService.pageQuery(param.getConditions(), param.getPageNo(), param.getPageSize());
//
//        return result;
//    }

//    @ApiOperation(value = "分页查询")
//    @RequestMapping(value = "list", method = RequestMethod.POST)
//    @ResponseBody
//    public R<List<SzhtxxPaperInvoiceRedTaxInfo>> pageQueryGenericParamSzhtxxPaperInvoiceRedTaxInfo(@RequestBody PageQueryGenericParam<SzhtxxPaperInvoiceRedTaxInfoQueryCriteria> param) {
//
//        log.info("pageQuerySzhtxxPaperInvoiceRedTaxInfo:\n{}", JsonUtils.toJson(param));
//
//        R<List<SzhtxxPaperInvoiceRedTaxInfo>> result = new R<>();
//
//        // TODO 参数合法性判定
//
//        result = szhtxxPaperInvoiceRedTaxInfoDubboConsumerService.pageQueryGenericParam(param.getConditions());
//
//        return result;
//    }

    @ApiOperation(value = "list-积分结算-红字专用发票信息表-分页查询")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ResponseBody
    public R<List<SzhtxxPaperInvoiceRedTaxInfoListItemVo>> pageQueryGenericParamSzhtxxPaperInvoiceRedTaxInfo(@RequestBody SzhtxxPaperInvoiceRedTaxInfoQueryCriteria queryCriteria) {

        log.info("pageQuerySzhtxxPaperInvoiceRedTaxInfo:\n{}", JsonUtils.toJson(queryCriteria));

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

        // TODO 参数合法性判定

        result = szhtxxPaperInvoiceRedTaxInfoDubboConsumerService.pageQueryGenericParam(queryCriteria);

        return result;
    }

    @ApiOperation(value = "按id查询")
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @ResponseBody
    public R<List<SzhtxxPaperInvoiceRedTaxInfo>> getById(@PathVariable("id") long id) {

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

        // TODO 参数合法性判定

        SzhtxxPaperInvoiceRedTaxInfo entity = szhtxxPaperInvoiceRedTaxInfoDubboConsumerService.findSzhtxxPaperInvoiceRedTaxInfoById(id);

        List<SzhtxxPaperInvoiceRedTaxInfo> data = new ArrayList<>();
        data.add(entity);

        result.setData(data);

        return result;
    }

    @ApiOperation(value = "新增")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public R<String> addSzhtxxPaperInvoiceRedTaxInfo(@RequestBody SzhtxxPaperInvoiceRedTaxInfoParam param) {

        log.info("addSzhtxxPaperInvoiceRedTaxInfo:\n{}", JsonUtils.toJson(param));


        // TODO 参数合法性判定

        szhtxxPaperInvoiceRedTaxInfoDubboConsumerService.addSzhtxxPaperInvoiceRedTaxInfo(param);

        return new R<>("200", "操作成功", true);
    }

    @ApiOperation(value = "op修改红字信息表编号")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public R<String> updateSzhtxxPaperInvoiceRedTaxInfo(@RequestBody SzhtxxPaperInvoiceRedTaxInfoOpEditForm form) {

        log.info("updateSzhtxxPaperInvoiceRedTaxInfo params(SzhtxxPaperInvoiceRedTaxInfoOpEditForm):\n{}", JsonUtils.toJson(form));

        /******************************************** 初始化 start ********************************************/

        InvoiceApply invoiceApplyCustomerEntity = invoiceApplyCustomerDubboConsumerService.findByInvoiceApplySn(form.getFpqqlsh(), getToken());

        if (ObjectUtil.isNull(invoiceApplyCustomerEntity)) {
            return ResponseResultOuterUtils.createErrorResult("500", "未查找到相关的信息");
        }


        // 该发票的回款状态非“发票红冲/发票作废”，若为“发票红冲/发票作废”，不允许修改，1.5s提示“该发票已红冲/作废，无需修改”；
        Integer[] invoiceApplyCustomerBackAccountStatusContains001 = {
                InvoiceApplyCustomerBackAccountStatusEnum.发票红冲.getKey(),
                InvoiceApplyCustomerBackAccountStatusEnum.发票作废.getKey()
        };

        if (ArrayUtil.contains(
                invoiceApplyCustomerBackAccountStatusContains001,
                invoiceApplyCustomerEntity.getBackAccountStatus())
        ) {
            return ResponseResultOuterUtils.createErrorResult("500", "该发票已红冲/作废，无需修改");
        }


        // 该发票的回款状态为“未回款”，若非“未回款”，1.5s提示“只允许未回款的发票申请红字信息表编号，请返回检查”；
        Integer[] invoiceApplyCustomerBackAccountStatusContains002 = {
                InvoiceApplyCustomerBackAccountStatusEnum.未回款.getKey()
        };
        if (!ArrayUtil.contains(
                invoiceApplyCustomerBackAccountStatusContains002,
                invoiceApplyCustomerEntity.getBackAccountStatus())
        ) {
            return ResponseResultOuterUtils.createErrorResult("500", "只允许未回款的发票申请红字信息表编号，请返回检查");
        }

        List<SzhtxxElectronicInvoiceFptxxListItemVo> resultList = szhtxxElectronicInvoiceFptxxDubboConsumerService.queryGenericParam(
                SzhtxxElectronicInvoiceFptxxQueryCriteria.builder()
                        .szhtxxElectronicInvoiceFptxxId(form.getSzhtxxElectronicInvoiceFptxxId())
                        .build(),
                getToken()
        );

        if (CollUtil.isEmpty(resultList)) {
            return ResponseResultOuterUtils.createErrorResult("500", "未查找到相关的信息");
        }

        SzhtxxElectronicInvoiceFptxxListItemVo fptxxListItemVo = resultList.get(0);

        /******************************************** 初始化   end ********************************************/

        SzhtxxPaperInvoiceRedTaxInfoParam param = SzhtxxPaperInvoiceRedTaxInfoParam
                .builder()
//                .id()
                .batchId(DateUtil.now())

//                .redTaxInfoLsh()
                .redTaxInfoSn(form.getRedTaxInfoSn())
//                .redTaxInfoStatus()
//                .redTaxInfoDesc()

//                .used()

                .fpdm(fptxxListItemVo.getFpdm())
                .fphm(fptxxListItemVo.getFphm())

                .ghfNsrsbh(fptxxListItemVo.getGhfNsrsbh())
                .ghfmc(fptxxListItemVo.getGhfmc())

                .xhfNsrsbh(fptxxListItemVo.getXhfNsrsbh())
                .xhfmc(fptxxListItemVo.getXhfmc())

                .ssyf(fptxxListItemVo.getSsyf())

                .kphjje(fptxxListItemVo.getKphjje().multiply(new BigDecimal(-1L)))
                .hjbhsje(fptxxListItemVo.getHjbhsje().multiply(new BigDecimal(-1L)))
                .sl(AnBigDecimalUtils.getBigDecimal(invoiceApplyCustomerEntity.getTaxRate()))
                .hjse(fptxxListItemVo.getHjse().multiply(new BigDecimal(-1L)))

//                .reqfCode()
//                .reqfName()
//                .reqExplain()
//                .goldenTaxPlateNo()
//                .reqNsrsbh()

//                .backendMemo()

                .build();

        int ret = szhtxxPaperInvoiceRedTaxInfoDubboConsumerService.saveOrUpdateSzhtxxPaperInvoiceRedTaxInfo(param, getToken());

        SzhtxxElectronicInvoiceFptxxExtendInfo szhtxxElectronicInvoiceFptxxExtendInfo = szhtxxElectronicInvoiceFptxxExtendInfoDubboConsumerService.findByFpqqlsh(form.getFpqqlsh());

        if (ObjectUtil.isNull(szhtxxElectronicInvoiceFptxxExtendInfo)) {
            return ResponseResultOuterUtils.createErrorResult("500", "未查找到相关的信息");
        }

        LoginSysUser loginSysUser = JwtUtil.getLoginSysUser(getToken());

        szhtxxElectronicInvoiceFptxxExtendInfoDubboConsumerService.updateByPrimaryKeySelective(
                SzhtxxElectronicInvoiceFptxxExtendInfo
                        .builder()

                        .id(szhtxxElectronicInvoiceFptxxExtendInfo.getId())
                        .redTaxInfoSn(form.getRedTaxInfoSn())

                        .updateTime(DateUtil.date())
                        .updateUserId(loginSysUser.getSysUserId())
                        .updateUserName(loginSysUser.getFullName())

                        .build()
        );

        return new R<>("200", "操作成功", true);
    }

    @ApiOperation(value = "op后台备注")
    @RequestMapping(value = "/opSetBackendMemo", method = RequestMethod.POST)
    @ResponseBody
    public R<String> opSetRemark2(@RequestBody SzhtxxPaperInvoiceRedTaxInfoOpSetRemark2Form form) {

        LoginSysUser loginSysUser = JwtUtil.getLoginSysUser(getToken());

        SzhtxxPaperInvoiceRedTaxInfo forUpdate = new SzhtxxPaperInvoiceRedTaxInfo();

        forUpdate.setId(form.getSzhtxxPaperInvoiceRedTaxInfoId());
        forUpdate.setBackendMemo(form.getBackendMemo());

        forUpdate.setUpdateTime(DateUtil.date());
        forUpdate.setUpdateUserId(loginSysUser.getSysUserId());
        forUpdate.setUpdateUserName(loginSysUser.getFullName());

        int ret = szhtxxPaperInvoiceRedTaxInfoDubboConsumerService.updateByPrimaryKeySelective(forUpdate);

        if (ret == 0) {
            return ResponseResultOuterUtils.createSuccesResult("后台备注失败");
        } else {
            return ResponseResultOuterUtils.createSuccesResult("后台备注成功");
        }
    }

    @ApiOperation(value = "删除")
    @RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public R<String> deleteSzhtxxPaperInvoiceRedTaxInfo(@PathVariable("id") long id) {

        // TODO 参数合法性判定

        szhtxxPaperInvoiceRedTaxInfoDubboConsumerService.deleteSzhtxxPaperInvoiceRedTaxInfo(id);

        return new R<>("200", "操作成功", true);
    }

    @ApiOperation(value = "批量删除")
    @RequestMapping(value = "delete_ids", method = RequestMethod.POST)
    @ResponseBody
    public R<String> deleteIdsSzhtxxPaperInvoiceRedTaxInfo(@RequestParam(value = "ids") long[] ids) {

        log.info(JsonUtils.toJson(ids));

        for (long id : ids) {
            szhtxxPaperInvoiceRedTaxInfoDubboConsumerService.deleteSzhtxxPaperInvoiceRedTaxInfo(id);
        }

        return new R<>("200", "操作成功", true);

    }


}
