package cn.superdesk.uniorder.controller.accounting.supplier;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.accounting.unified.supplier.AccountingUnifiedSupplier;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dto.param.accounting.common.StatementOfAccountUpdateFieldRamarkForm;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.AccountingOrderUnifiedSuplierHeadVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.AccountingOrderUnifiedSupplierListItemVo;
import cn.superdesk.uniorder.dubbo.consumer.accounting.supplier.AccountingUnifiedSupplierDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysSupplierDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysUserDubboConsumerService;
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.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2020/11/3 下午5:41
 * @UpdateUser: linjinyu
 * @UpdateDate: 2020/11/3 下午5:41
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "[对账单]-供应商结算-对账单", tags = {"[对账单]-供应商结算-对账单"})
@Slf4j
@RestController
@RequestMapping("/accounting/unified/supplier/statement")
public class AccountingUnifiedSupplierController extends BaseController {


    @Autowired
    private UnifiedOrderDubboConsumerService              unifiedOrderDubboConsumerService;
    @Autowired
    private SysSupplierDubboConsumerService               unifiedSupplierDubboConsumerService;
    @Autowired
    private AccountingUnifiedSupplierDubboConsumerService accountingUnifiedSupplierDubboConsumerService;

    @Autowired
    private SysUserDubboConsumerService sysUserDubboConsumerService;

    /***
     * 供应商结算-对账单 弃用
     * {@link cn.superdesk.uniorder.controller.accounting.supplier.AccountingUnifiedSupplierVer2Controller#getStatementOfAccountList}
     *
     * @url: http://order.avic-s.com/#/vendorAccountStatement?id=72
     * @return
     */
    @Deprecated
    @ApiOperation(value = "供应商结算-对账单-列表-引用 1.后端;2.商户端;", notes = "已粉饰[BigDecimal]")
    @RequestMapping(value = "/getStatementOfAccountList", method = RequestMethod.POST)
    @ResponseBody
    public R<List<AccountingOrderUnifiedSupplierListItemVo>> getStatementOfAccountList() {

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

        try {
            Map<String, Object> params = new HashMap<>();

            // 组合的 下拉选择的
            params.put("accountingOrderSn", getString("accountingOrderSn"));

            params.put("orderSn", getString("orderSn"));

            // 供应商名称
            params.put("supplierId", getLong("supplierId"));
            params.put("supplierName", getString("supplierName"));

            // 对账单状态
            params.put("accountingStatus", getString("accountingStatus"));

            // 开票状态
            params.put("invoiceStatus", getString("invoiceStatus"));

            // 对账时间
            params.put("startTime", getString("startTime"));
            params.put("endTime", getString("endTime"));

            log.info("供应商结算-对账单 : \n{}", AnJsonUtils.toJson(params));

            // 前端 列表数据
            result = accountingUnifiedSupplierDubboConsumerService.getStatementOfAccountList(params, getPageNum(), getPageSize(), getToken());

            // 前端 头部 对账单数:1 订单数:3 成本金额:¥ 10312.92
            AccountingOrderUnifiedSuplierHeadVo accountingUnifiedSuplierHeadVo = accountingUnifiedSupplierDubboConsumerService
                    .getStatementOfAccountHeadSum(
                            params,
                            getToken()
                    );

            result.setHeadData(AnBeanUtils.beanToMap(accountingUnifiedSuplierHeadVo));

        } catch (Exception e) {

            result.setCode(String.valueOf(e.hashCode()));
            result.setSuccess(false);
            result.setMessage(e.getMessage());

            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();

        }

        return result;
    }


    /**
     * 供应商结算-对账单-opt编辑对帐
     *
     * @return
     */
    @ApiOperation(value = "供应商结算-对账单-opt编辑对帐(目前能适用以订单创建的对账单)", notes = "以商品维度创建的对账单 编辑对账不用做 mark at  20201102 10:30 确认人为: 张雪")
    @RequestMapping(value = "/opEditAccounting", method = RequestMethod.POST)
    @ResponseBody
    public R<Object> opEditAccounting() {

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

        try {
            // 对账单Id
            Long id = getLong("id");
            // 订单 orderSn
            String orderSn = getString("orderSn");
            // 是否新增 默认为 0
            String add = getString("add");

            AccountingUnifiedSupplier statementOfAccount = accountingUnifiedSupplierDubboConsumerService.findById(id);

            if (null == statementOfAccount) {
                result.setCode(400);
                result.setSuccess(false);
                result.setMessage("对账单 查找不到? 给错参数? 正确的参数为[id]");
                result.setData(statementOfAccount);
                return result;
            }

            // TODO 写死
            if (statementOfAccount.getInvoiceStatus() == 1) {
                result.setCode(400);
                result.setSuccess(false);
                result.setMessage("已开票 对账单 不可继续操作！");
                result.setData(statementOfAccount);
                return result;
            }

            UnifiedOrder unifiedOrder = unifiedOrderDubboConsumerService.findByOrderSn(orderSn);

            if (null == unifiedOrder) {
                result.setCode(400);
                result.setSuccess(false);
                result.setMessage("订单 查找不到? 给错参数? 正确的参数为[orderSn]");
                result.setData(unifiedOrder);
                return result;
            }

            if (null == statementOfAccount.getSaleId()) {
                result.setCode(400);
                result.setSuccess(false);
                result.setMessage("对账单 没有 设定供应商? 请联系管理员! 异常对账单Id:" + id);
                result.setData(unifiedOrder);
                return result;
            }

            if (null == unifiedOrder.getSaleId()) {
                result.setCode(400);
                result.setSuccess(false);
                result.setMessage("要添加的订单 没有 设定供应商? 请联系管理员! 异常订单,订单Sn:" + orderSn);
                result.setData(unifiedOrder);
                return result;
            }

            if (!statementOfAccount.getSaleId().equals(unifiedOrder.getSaleId())) {
                result.setCode(400);
                result.setSuccess(false);
                result.setMessage("订单 的供应商 与 对账单 的供应商 不一样!");
                result.setData(unifiedOrder);
                return result;
            }

            if (add.equals("1") && unifiedOrder.getAccountingStateSupplier().equals(CommonAccountingStateEnum.已对账.getKey())) {
                result.setCode(400);
                result.setSuccess(false);
                result.setMessage("该订单已对账,不可继续操作！");
                result.setData(unifiedOrder);
                return result;
            }

            accountingUnifiedSupplierDubboConsumerService.opEditAccountingDimOrder(getToken(), statementOfAccount, unifiedOrder, add);

            result.setSuccess(true);

        } catch (Exception e) {

            result.setCode(String.valueOf(e.hashCode()));
            result.setSuccess(false);
            result.setMessage(e.getMessage());

            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }

        return result;
    }


    /***
     * 供应商结算-对账单-opt更新状态 弃用
     * opt 提交对账 state 0
     * opt 确认对账 state 1
     *
     * /accounting/unified/supplier/statement/updatestate
     * @return
     */
    @Deprecated
    @ApiOperation(value = "(弃用)供应商结算-对账单-opt更新状态 | opt 提交对账 state 0 | opt 确认对账 state 1", notes = "-1-已取消;0-已提交(未确认);1-已确认;2-已拒绝;3-待提交(创建对账单 初始 状态)")
    @RequestMapping(value = "/updatestate", method = RequestMethod.POST)
    @ResponseBody
    public R<AccountingUnifiedSupplier> updateState() {

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

        try {

            Long id = getLong("id");

            // -1-已取消;0-已提交(未确认);1-已确认;2-已拒绝;3-待提交(创建对账单 初始 状态)
            Integer state = getInteger("state");

            AccountingUnifiedSupplier statementOfAccount4Check = accountingUnifiedSupplierDubboConsumerService.findById(id);

            // TODO 写死
            if (statementOfAccount4Check.getInvoiceStatus() == 1) {
                result.setCode(400);
                result.setSuccess(false);
                result.setMessage("已开票对账单不可继续操作!");
                return result;
            }

            AccountingUnifiedSupplier statementOfAccount4Update = new AccountingUnifiedSupplier();

            statementOfAccount4Update.setAccountingStatus(state);
            statementOfAccount4Update.setId(statementOfAccount4Check.getId());
            statementOfAccount4Update.setUpdateTime(DateUtil.date());
            accountingUnifiedSupplierDubboConsumerService.updateObj(getToken(), statementOfAccount4Update);

            result.setData(statementOfAccount4Update);

        } catch (Exception e) {

            result.setCode(String.valueOf(e.hashCode()));
            result.setSuccess(false);
            result.setMessage(e.getMessage());

            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }

        return result;
    }

    @ApiOperation(value = "设置备注-对账单-供应商结算-超级前台|侨城汇")
    @RequestMapping(value = "/setRemark", method = RequestMethod.POST)
    @ResponseBody
    public R setRemark(@RequestBody StatementOfAccountUpdateFieldRamarkForm form) {

        AccountingUnifiedSupplier statementOfAccount4Update = new AccountingUnifiedSupplier();
        statementOfAccount4Update.setId(form.getId());
        statementOfAccount4Update.setRemark(form.getRemark());

        accountingUnifiedSupplierDubboConsumerService.updateObj(getToken(), statementOfAccount4Update);

        return new R();
    }
}
