package com.pj.project.tb_business;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.pj.api.bo.OtherBusinessBO;
import com.pj.constants.UserTypeEnum;
import com.pj.project.tb_business_car.TbBusinessCar;
import com.pj.project.tb_business_car.TbBusinessCarService;
import com.pj.project.tb_business_item.TbBusinessItem;
import com.pj.project.tb_business_item.TbBusinessItemService;
import com.pj.project.tb_declare.TbDeclare;
import com.pj.project.tb_declare.TbDeclareService;
import com.pj.project.tb_item.TbItem;
import com.pj.project.tb_notices.TbNoticesService;
import com.pj.project.tb_pass_record.TbPassRecord;
import com.pj.project.tb_pass_record.TbPassRecordService;
import com.pj.utils.so.SoMap;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.pj.utils.sg.*;
import com.pj.project4sp.SP;

import com.pj.current.satoken.StpUserUtil;
import cn.dev33.satoken.annotation.SaCheckPermission;

import javax.annotation.Resource;


/**
 * Controller: tb_business -- 入境登记
 *
 * @author qzy
 */
@RestController
@RequestMapping("/TbBusiness/")
public class TbBusinessController {

    /**
     * 底层 Service 对象
     */
    @Autowired
    TbBusinessService tbBusinessService;
    @Resource
    private TbBusinessItemService tbBusinessItemService;
    @Resource
    private TbNoticesService tbNoticesService;
    @Resource
    private TbBusinessCarService tbBusinessCarService;
    @Resource
    private TbDeclareService tbDeclareService;


    @RequestMapping(value = "getMsg")
    public AjaxJson getMsg() {
        return AjaxJson.getSuccessData(BusinessMessageManager.get(StpUserUtil.getCustomerId()));
    }

    /**
     * 增
     */
    @RequestMapping("add")
    @SaCheckPermission(TbBusiness.PERMISSION_CODE)
    @Transactional(rollbackFor = Exception.class)
    public AjaxJson add(TbBusiness t) {
        return tbBusinessService.addOrUpdate(t);
    }

    /**
     * 删
     */
    @RequestMapping("delete")
    @SaCheckPermission(TbBusiness.PERMISSION_INPUT)
    @Transactional(rollbackFor = Exception.class)
    public AjaxJson delete(String id) {
        TbBusiness db = tbBusinessService.getById(id);
        if (db != null) {
            tbBusinessService.storeMsg(db.getCustomerId(), "业务订单【" + db.getNo() + "】已删除。" + DateUtil.now() + "。");
        }
        tbBusinessService.removeById(id);
        tbBusinessItemService.removeByBusinessId(id);

        tbBusinessCarService.removeByBusinessId(id);
        tbDeclareService.removeBusinessId(id);

        return AjaxJson.getSuccess();
    }

    /**
     * 改
     */
    @RequestMapping("update")
    @SaCheckPermission(TbBusiness.PERMISSION_CODE)
    public AjaxJson update(TbBusiness t) {
        tbBusinessService.addOrUpdate(t);
        return AjaxJson.getSuccess();
    }

    /**
     * 确认业务
     */
    @RequestMapping("confirm")
    @Transactional(rollbackFor = Exception.class)
    public AjaxJson confirm() {
        if (!StpUtil.hasPermissionAnd(TbBusiness.PERMISSION_CONFIRM) && !
                StrUtil.equals(StpUserUtil.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            return AjaxJson.getError("无确认业务权限");
        }
        SoMap so = SoMap.getRequestSoMap();
        List<String> ids = so.getListByComma("ids", String.class);
        tbBusinessService.confirm(ids);
        return AjaxJson.getSuccess();
    }

    /**
     * 确认业务
     */
    @RequestMapping("adminConfirmPay")
    @Transactional(rollbackFor = Exception.class)
    public AjaxJson adminConfirmPay() {
        if (!StrUtil.equals(StpUserUtil.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            return AjaxJson.getError("无确认支付权限");
        }
        SoMap so = SoMap.getRequestSoMap();
        List<String> ids = so.getListByComma("ids", String.class);
        String ticket = so.getString("payTicket");
        tbBusinessService.adminConfirmPay(ids, ticket);
        return AjaxJson.getSuccess();
    }

    /**
     * 手动入场确认 see adminSetIn
     */
    @RequestMapping("adminConfirmIn")
    @Transactional(rollbackFor = Exception.class)
    @Deprecated
    public AjaxJson adminConfirmIn() {
        if (!StrUtil.equals(StpUserUtil.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            return AjaxJson.getError("无确认入场权限");
        }
        SoMap so = SoMap.getRequestSoMap();
        String id = so.getString("id");
        String inChannel = so.getString("inChannel");
        tbBusinessService.adminConfirmIn(id, inChannel);
        return AjaxJson.getSuccess();
    }


    /**
     * 查 - 根据id
     */
    @RequestMapping("getById")
    public AjaxJson getById(String id) {
        TbBusiness t = tbBusinessService.getById(id);
        List<TbBusinessItem> items = tbBusinessItemService.findByBusinessId(id);
        items.forEach(tbBusinessItem -> tbBusinessItem.setGoodsName(t.getGoodsName()).setCardNo(t.getCardNo()).setChinaCarNo(t.getChinaCarNo()));
        t.setItems(items);
        if (TbBusiness.BusinessType.CAR_DISINCLE.getCode().equals(t.getBusinessType())) {
            t.setCars(Collections.singletonList(tbBusinessCarService.getById(t.getBusinessCarId())));
        } else {
            List<TbBusinessCar> cars = tbBusinessCarService.findByBusinessId(id);
            t.setCars(cars);
        }
        return AjaxJson.getSuccessData(t);
    }


    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    @RequestMapping("getList")
    public AjaxJson getList() {
        SoMap so = SoMap.getRequestSoMap();
        String currentCustomerId = StpUserUtil.getCustomerId();
        if (!currentCustomerId.equals(UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            so.put("customerId", currentCustomerId);
        }
        List<TbBusiness> list = tbBusinessService.getList(so.startPage());
        return AjaxJson.getPageData(so.getDataCount(), list);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    @RequestMapping("getCarDisincleList")
    public AjaxJson getCarDisincleList() {
        SoMap so = SoMap.getRequestSoMap();
        String currentCustomerId = StpUserUtil.getCustomerId();
        if (!currentCustomerId.equals(UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            so.put("customerId", currentCustomerId);
        }
        List<CarDisincle> list = tbBusinessService.getCarDisincleList(so.startPage());
        return AjaxJson.getPageData(so.getDataCount(), list);
    }

    /**
     * 改
     */
    @RequestMapping("pay")
    public AjaxJson pay() {
        if (!StpUtil.hasPermissionAnd("tb-business-pay") && !
                StrUtil.equals(StpUserUtil.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            return AjaxJson.getError("无支付权限");
        }
        SoMap so = SoMap.getRequestSoMap();
        String id = so.getString("id");
        String payTicket = so.getString("payTicket");
        tbBusinessService.pay(id, payTicket);
        return AjaxJson.getSuccess();
    }

    @RequestMapping("adminSetIn")
    public AjaxJson adminSetIn() {
        if (!StrUtil.equals(StpUserUtil.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            return AjaxJson.getError("无入场权限");
        }
        SoMap so = SoMap.getRequestSoMap();
        String id = so.getString("id");
        Date inTime = so.getDateTime("realInTime");
        Date chinaCarInTime = so.getDateTime("chinaCarInTime");
        TbBusiness tbBusiness = tbBusinessService.getById(id);
        tbBusiness.setChinaCarInTime(chinaCarInTime).setRealInTime(inTime).setAdminConfirmIn(1);
        tbBusinessService.updateById(tbBusiness);

        //更新境外车入场记录

        //更新中国车入场记录

        //发送消息
        String text = "您的车辆已入场，业务单号[" + tbBusiness.getNo() + "]";
        tbNoticesService.sendNotice(tbBusiness.getId(), tbBusiness.getNo(), tbBusiness.getCustomerId(), text);

        return AjaxJson.getSuccess();
    }

    @RequestMapping("adminOut")
    public AjaxJson adminOut() {
        if (!StrUtil.equals(StpUserUtil.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            return AjaxJson.getError("无离场权限");
        }
        SoMap so = SoMap.getRequestSoMap();
        String id = so.getString("id");
        TbBusiness business = tbBusinessService.getById(id);
        Date outTime = so.getDateTime("outDayTime");
        if (business.getRealInTime().getTime() > outTime.getTime()) {
            return AjaxJson.getError("离场时间须大于出场时间");
        }
        business.setOutDayTime(outTime);
        tbBusinessService.calculationPartMoney("越南车", business);
        tbBusinessService.updateById(business);
        Date chinaCarOutTime = so.getDateTime("chinaCarOutTime");
        if (chinaCarOutTime.getTime() < business.getChinaCarInTime().getTime()) {
            return AjaxJson.getError("离场时间须大于出场时间");
        }
        business.setChinaCarOutTime(chinaCarOutTime);
        tbBusinessService.calculationPartMoney("中国车", business);
        business.setAdminConfirmOut(1);
        tbBusinessService.updateById(business);
        //更新境外车出场记录

        //更新中国车出场记录

        tbBusinessService.storeMsg(business.getCustomerId(), "业务订单【" + business.getNo() + "】已完成作业离场" + DateUtil.now() + "。");
        //发送消息
        String text = "您的车辆已离场，业务单号[" + business.getNo() + "]";
        tbNoticesService.sendNotice(business.getId(), business.getNo(), business.getCustomerId(), text);
        return AjaxJson.getSuccess();
    }

    @RequestMapping("calJwPartMoney")
    public AjaxJson calJwPartMoney(TbBusiness business) {
        if (!StrUtil.equals(StpUserUtil.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            return AjaxJson.getError("无生成账单权限");
        }
        tbBusinessService.calculationPartMoney("越南车", business);
        return AjaxJson.getSuccessData(business);
    }

    @RequestMapping("calChinaPartMoney")
    public AjaxJson calChinaPartMoney(TbBusiness business) {
        if (!StrUtil.equals(StpUserUtil.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            return AjaxJson.getError("无生成账单权限");
        }
        tbBusinessService.calculationPartMoney("中国车", business);
        return AjaxJson.getSuccessData(business);
    }

    @RequestMapping("complete")
    public AjaxJson complete(TbBusiness business) {
        if (!StrUtil.equals(StpUserUtil.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            return AjaxJson.getError("无生成账单权限");
        }
        business.setComplete(1);
        tbBusinessService.updateById(business);
        tbBusinessService.storeMsg(business.getCustomerId(), "业务订单【" + business.getNo() + "】账单已生成！" + DateUtil.now() + "。");
        //发送消息
        String text = "您的账单已生成，业务单号[" + business.getNo() + "]";
        tbNoticesService.sendNotice(business.getId(), business.getNo(), business.getCustomerId(), text);
        return AjaxJson.getSuccessData(business);
    }

    @RequestMapping("uploadReport")
    public AjaxJson uploadReport(@RequestBody TbBusiness tbBusiness) {
        tbBusinessService.uploadReport(tbBusiness);
        return AjaxJson.getSuccess();
    }

    @RequestMapping("getOtherBusinessById")
    public AjaxJson getOtherBusinessById(String id) {
        return AjaxJson.getSuccessData(tbBusinessService.getOtherBusinessById(id));
    }

    @RequestMapping("deleteOtherBusiness")
    public AjaxJson deleteOtherBusiness(String id, String businessCarId) {
        tbBusinessService.deleteOtherBusiness(id);
        return AjaxJson.getSuccess();
    }

    @RequestMapping("manualConfirm")
    @SaCheckPermission(TbBusiness.PERMISSION_MANUAL_PAY)
    public AjaxJson manualConfirm() {
        SoMap so = SoMap.getRequestSoMap();
        String id = so.getString("id");
        String remark = so.getString("remark");
        String inChannel = so.getString("inChannel");
        String outChannel = so.getString("outChannel");
        Date realInTime = so.getDateTime("realInTime");
        Date realOutTime = so.getDateTime("realOutTime");
        tbBusinessService.manualConfirmPay(id, inChannel, realInTime, outChannel, realOutTime, remark);
        return AjaxJson.getSuccess();
    }


    @RequestMapping(value = "unBindCar")
    public AjaxJson unBindCar(String id, String businessCarId) {
        tbBusinessService.unBindCar(id,businessCarId);
        return AjaxJson.getSuccess();
    }
    @RequestMapping(value = "bindCar")
    public AjaxJson bindCar(String id, String businessCarId) {
        tbBusinessService.bindCar(id,businessCarId);
        return AjaxJson.getSuccess();
    }


    // ------------------------- 前端接口 -------------------------


}
