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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.superdesk.uniorder.common.constants.ResponseMsgConstants;
import cn.superdesk.uniorder.common.enums.invoice.customer.InvoiceApplyCustomerBackAccountStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderTypeDimEnum;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.numerical.AnStringUtils;
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.dao.entity.invoice.customer.InvoiceApply;
import cn.superdesk.uniorder.dto.param.invoice.customer.status.OpBackAccountStatusBindingAttachmentForm;
import cn.superdesk.uniorder.dto.param.invoice.customer.status.OpBackAccountStatusForm;
import cn.superdesk.uniorder.dto.param.invoice.customer.status.OpChangeStatusBaseItem;
import cn.superdesk.uniorder.dubbo.consumer.invoice.customer.InvoiceApplyCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.invoice.customer.state.InvoiceApplyFieldBackAccountStatusDubboConsumerService;
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.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 回款登记部分 - 简易状态机 星型结构
 * @Author: linjinyu
 * @CreateDate: 10/12/20 4:28 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 10/12/20 4:28 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "积分结算-发票单-回款登记部分-InvoiceApply-BackAccountStatus", tags = {"积分结算-发票单-回款登记部分-InvoiceApply-BackAccountStatus"})
@Slf4j
@RestController
@RequestMapping("/invoice/apply/customer/score/state/backAccountStatus")
public class InvoiceApplyCustomerScoreFieldBackAccountStatusController extends BaseController {

    @Autowired
    private InvoiceApplyCustomerDubboConsumerService               invoiceApplyCustomerDubboConsumerService;
    @Autowired
    private InvoiceApplyFieldBackAccountStatusDubboConsumerService invoiceApplyFieldBackAccountStatusDubboConsumerService;

    @ApiOperation(value = "InvoiceApply-BackAccountStatus-op 未回款 0")
    @RequestMapping(value = "/opInit/{id}", method = RequestMethod.POST)
    @ResponseBody
    public R<?> opInit(@PathVariable("id") Long id) {

        R<?> result = new R<>();

        try {
            InvoiceApply entity = invoiceApplyCustomerDubboConsumerService.findById(id);
            invoiceApplyFieldBackAccountStatusDubboConsumerService.opInit(entity, getToken());
            result.setSuccess(true);

        } catch (Exception e) {

            result.setSuccess(false);
            result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation(value = "InvoiceApply-BackAccountStatus-op 部分回款 1")
    @RequestMapping(value = "/opPart/{id}", method = RequestMethod.POST)
    @ResponseBody
    public R<?> opPart(@PathVariable("id") Long id) {

        R<?> result = new R<>();

        try {
            InvoiceApply entity = invoiceApplyCustomerDubboConsumerService.findById(id);
            invoiceApplyFieldBackAccountStatusDubboConsumerService.opPart(entity, getToken());
            result.setSuccess(true);

        } catch (Exception e) {

            result.setSuccess(false);
            result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation(value = "InvoiceApply-BackAccountStatus-op 已回款 2 - 单个开票申请")
    @RequestMapping(value = "/opComplete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public R<?> opComplete(@PathVariable("id") Long id) {

        R<?> result = new R<>();

        try {
            InvoiceApply entity = invoiceApplyCustomerDubboConsumerService.findById(id);
            invoiceApplyFieldBackAccountStatusDubboConsumerService.opComplete(entity, getToken());
            result.setSuccess(true);

        } catch (Exception e) {

            result.setSuccess(false);
            result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }
        return result;
    }


    @ApiOperation(value = "InvoiceApply-BackAccountStatus-op 已回款 2 - 对账单维度", notes = "以对账单维度自动补全 - 20220111")
    @RequestMapping(value = "/opComplete/dim/accountingOrder", method = RequestMethod.POST)
    @ResponseBody
    public R<?> opCompleteDimAccountingOrder(@RequestBody OpBackAccountStatusForm form) { // 以对账单维度自动补全 - 20220111

        R<?> result = new R<>();

        // TODO 简单验证

        if (CollUtil.isEmpty(form.getSubmitList())) {
            return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
        }

        try {

            /****************************************** 对账单编号 start ******************************************/

            List<String> accountingOrderSns = form.getSubmitList()
                    .stream()
                    .filter(AnLamdaUtils.distinctByKey(o -> o.getAccountingOrderSn()))
                    .map(OpChangeStatusBaseItem::getAccountingOrderSn)
                    .collect(Collectors.toList());

            if (CollUtil.isEmpty(accountingOrderSns)) {
                return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
            }

            if (accountingOrderSns.size() > 1) {
                return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
            }

            /****************************************** 开票申请 - 数据库 start ******************************************/

            List<InvoiceApply> entitysExistDb = invoiceApplyCustomerDubboConsumerService.findByAccountingOrderSn(accountingOrderSns.get(0), AccountingOrderTypeDimEnum.积分订单);

            if (CollUtil.isEmpty(entitysExistDb)) {
                return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
            }


            /****************************************** 开票申请 - 前端提交 start ******************************************/

            List<Long>         invoiceApplyIds = form.getSubmitList().stream().map(OpChangeStatusBaseItem::getInvoiceApplyId).collect(Collectors.toList());
            List<InvoiceApply> entitys         = invoiceApplyCustomerDubboConsumerService.findByIds(invoiceApplyIds);

            if (CollUtil.isEmpty(invoiceApplyIds)) {
                return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
            }
            if (CollUtil.isEmpty(entitys)) {
                return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
            }
            if (invoiceApplyIds.size() != entitys.size()) {
                return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
            }

            List<Integer> backAccountStatus = entitysExistDb.stream().filter(AnLamdaUtils.distinctByKey(o -> o.getBackAccountStatus())).map(InvoiceApply::getBackAccountStatus).collect(Collectors.toList());

            if (CollUtil.isEmpty(backAccountStatus)) {
                return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
            }
            if (backAccountStatus.size() > 1) {
                return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
            }

            InvoiceApplyCustomerBackAccountStatusEnum invoiceApplyCustomerBackAccountStatusEnum = InvoiceApplyCustomerBackAccountStatusEnum.get(backAccountStatus.get(0));

            if (invoiceApplyCustomerBackAccountStatusEnum != InvoiceApplyCustomerBackAccountStatusEnum.未回款) {
                return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常,要求状态为[未回款]");
            }

            invoiceApplyFieldBackAccountStatusDubboConsumerService.opComplete(entitysExistDb, form, getToken());
            result.setSuccess(true);

        } catch (Exception e) {

            result.setSuccess(false);
            result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }
        return result;
    }

//	attachmentUploadfilesUids
//	attachment_upload_files_uids

    @ApiOperation(value = "InvoiceApply-BackAccountStatus-op binding attachment 绑定附件 - 单个开票申请")
    @RequestMapping(value = "/opBindingAttachment", method = RequestMethod.POST)
    @ResponseBody
    public R<?> opBindingAttachmentToInvoiceApplyCustomer(@RequestBody OpBackAccountStatusBindingAttachmentForm form) {

        R<?> result = new R<>();

        try {

            InvoiceApply entity = invoiceApplyCustomerDubboConsumerService.findById(form.getInvoiceApplyId());

            if (ObjectUtil.isEmpty(entity)) {
                return ResponseResultOuterUtils.createErrorResult("500", "资源不存在");
            }

            InvoiceApply forUpdate = new InvoiceApply();
            forUpdate.setId(entity.getId());

            if (CollUtil.isEmpty(form.getUids())) {
                forUpdate.setAttachmentUploadFilesUids("");
            } else {
                forUpdate.setAttachmentUploadFilesUids(AnStringUtils.stringListConvertToString(form.getUids()));
            }

            int ret = invoiceApplyCustomerDubboConsumerService.updateInvoiceApplyByPrimaryKeySelective(forUpdate);

            result.setSuccess(true);

        } catch (Exception e) {

            result.setSuccess(false);
            result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }

        return result;
    }

}
