package com.njyunzhi.pet_identity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njyunzhi.pet_identity.common.BaseController;
import com.njyunzhi.pet_identity.common.Constants;
import com.njyunzhi.pet_identity.common.ResponseBean;
import com.njyunzhi.pet_identity.common.StringUtils;
import com.njyunzhi.pet_identity.entity.*;
import com.njyunzhi.pet_identity.service.ITaCardNoService;
import com.njyunzhi.pet_identity.service.ITaOrderService;
import com.njyunzhi.pet_identity.service.ITaPetIdentityService;
import com.njyunzhi.pet_identity.vo.AuditParam;
import com.njyunzhi.pet_identity.vo.MakeCardParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.njyunzhi.pet_identity.service.ITaApplicationService;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * <p>
    * 我的申请 前端控制器
    * </p>
 *
 * @author yansen
 * @since 2022-05-24
 */

@Api(tags = "我的申请")
@RestController
@RequestMapping("/")
public class TaApplicationController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaApplicationController.class);

    @Autowired
    public ITaApplicationService iTaApplicationService;

    @Autowired
    public ITaPetIdentityService iTaPetIdentityService;

    @Autowired
    public ITaOrderService iTaOrderService;

    @Autowired
    public ITaCardNoService iTaCardNoService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/application",method= RequestMethod.GET)
    @ApiOperation(value="列表", notes = "列表", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean taApplicationList(@ApiParam("页码") @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                          @ApiParam("单页数据量") @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                          @ApiParam("表单进度") @RequestParam(value ="process", defaultValue = "0") Integer process,
                                          @ApiParam(value = "申请开始时间", example = "2022-06-01") @RequestParam(value ="applyStart", required = false) String applyStart,
                                          @ApiParam(value = "申请结束时间", example = "2022-06-30") @RequestParam(value ="applyEnd", required = false) String applyEnd,
                                          @ApiParam(value = "审核开始时间", example = "2022-06-01") @RequestParam(value ="auditStart", required = false) String auditStart,
                                          @ApiParam(value = "审核结束时间", example = "2022-06-30") @RequestParam(value ="auditEnd", required = false) String auditEnd,
                                          @ApiParam(value = "发证开始时间", example = "2022-06-01") @RequestParam(value ="makeStart", required = false) String makeStart,
                                          @ApiParam(value = "发证结束时间", example = "2022-06-30") @RequestParam(value ="makeEnd", required = false) String makeEnd,
                                          @ApiParam("申请类型") @RequestParam(value ="applyType", required = false) String applyType,
                                          @ApiParam("申领方式") @RequestParam(value ="applyMethod", required = false) Integer applyMethod,
                                          @ApiParam("付款状态") @RequestParam(value ="payStatus", required = false) Integer payStatus,
                                          @ApiParam("审核状态") @RequestParam(value ="verifyStatus", required = false) Integer verifyStatus,
                                          @ApiParam("犬主") @RequestParam(value ="personName", required = false) String personName,
                                          @ApiParam("手机号") @RequestParam(value ="phone", required = false) String phone,
                                          @ApiParam("犬名") @RequestParam(value ="petName", required = false) String petName,
                                          @ApiParam("卡号") @RequestParam(value ="originCardNo", required = false) String originCardNo,
                                          @ApiParam("是否企业") @RequestParam(value ="isOrg", required = false) Boolean isOrg,
                                          @ApiParam("企业名称") @RequestParam(value ="orgName", required = false) String orgName) throws Exception{

        SysUser sysUser = currentUser();

        IPage<TaApplication> pg = new Page<>(pageNum, pageSize);
        QueryWrapper<TaApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("status", Constants.STATUS_DELETE);
        queryWrapper.eq(!StringUtils.isEmpty(applyType), "apply_type", applyType);
        queryWrapper.eq(null != applyMethod, "apply_method", applyMethod);
        queryWrapper.eq(null != payStatus, "pay_status", payStatus);
        queryWrapper.eq(null != verifyStatus, "verify_status", verifyStatus);
        queryWrapper.eq(null != isOrg, "is_org", isOrg);
        queryWrapper.like(!StringUtils.isEmpty(orgName), "org_name", "%" + orgName + "%");
        queryWrapper.like(!StringUtils.isEmpty(personName), "person_name", "%" + personName + "%");
        queryWrapper.like(!StringUtils.isEmpty(phone), "phone", "%" + phone + "%");
        queryWrapper.like(!StringUtils.isEmpty(petName), "pet_name", "%" + petName + "%");
        queryWrapper.like(!StringUtils.isEmpty(originCardNo), "origin_card_no", "%" + originCardNo + "%");
        queryWrapper.ge(!StringUtils.isEmpty(applyStart), "create_date", applyStart);
        queryWrapper.le(!StringUtils.isEmpty(applyEnd), "create_date", applyEnd);
        queryWrapper.ge(!StringUtils.isEmpty(auditStart), "verify_date", auditStart);
        queryWrapper.le(!StringUtils.isEmpty(auditEnd), "verify_date", auditEnd);
        queryWrapper.ge(!StringUtils.isEmpty(makeStart), "make_date", makeStart);
        queryWrapper.le(!StringUtils.isEmpty(makeEnd), "make_date", makeEnd);

        if (Constants.WORKFLOW_PROCESS_AUDIT == process) {
            // 过滤待审批列表
            queryWrapper.in("status", new Integer[] { Constants.WORKFLOW_STATUS_PROCESSING, Constants.WORKFLOW_STATUS_AUDIT });
        } else if (Constants.WORKFLOW_PROCESS_MADE == process) {
            // 过滤待制卡列表
            // 必须是审核通过的, 且是初次提审或者挂失补办的
            queryWrapper.in("status", new Integer[] { Constants.WORKFLOW_STATUS_AUDIT, Constants.WORKFLOW_STATUS_MADE });
            queryWrapper.eq("verify_Status", Constants.AUDIT_STATUS_PASSED);
            queryWrapper.in("apply_type", new String[] { Constants.APPLY_TYPE_FIRST,  Constants.APPLY_TYPE_REISSUE});
        }

//        // 审核人角色
//        if (Constants.USER_AUDITOR.equals(sysUser.getRoleName())) {
//            queryWrapper.ge("status", Constants.WORKFLOW_STATUS_PROCESSING);
//            queryWrapper.le("status", Constants.WORKFLOW_STATUS_AUDIT);
//        }
//
//        // 发证(制卡)人角色
//        if (Constants.USER_MAKER.equals(sysUser.getRoleName())) {
//            queryWrapper.ge("status", Constants.WORKFLOW_STATUS_AUDIT);
//            queryWrapper.le("status", Constants.WORKFLOW_STATUS_MADE);
//        }

        queryWrapper.orderByAsc("status");
        queryWrapper.orderByDesc("create_date");

        IPage<TaApplication> result = iTaApplicationService.page(pg, queryWrapper);
        return ResponseBean.success(result);
    }


    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/wx/{client}/application",method= RequestMethod.GET)
    @ApiOperation(value="微信列表", notes = "微信列表", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean wxList(@ApiParam("页码") @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                               @ApiParam("单页数据量") @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize) throws Exception{

        TaPerson taPerson = currentPerson();

        IPage<TaApplication> pg = new Page<>(pageNum, pageSize);
        QueryWrapper<TaApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("status", Constants.STATUS_DELETE);
        queryWrapper.eq("person_id", taPerson.getPersonId());

        queryWrapper.orderByDesc("create_date");

        IPage<TaApplication> result = iTaApplicationService.page(pg, queryWrapper);
        return ResponseBean.success(result);
    }

    /**
     * 保存对象
     * @param taApplication 实体对象
     * @return
     */
    @RequestMapping(value="/wx/{clientId}/application",method= RequestMethod.POST)
    @ApiOperation(value="微信申请", notes = "微信申请", httpMethod = "POST", response = ResponseBean.class)
    public ResponseBean taApplicationAdd(@ApiParam("保存内容") @RequestBody TaApplication taApplication) throws Exception{

        TaPerson taPerson = currentPerson();
        if (StringUtils.isEmpty(taPerson.getPhone())) {
            return ResponseBean.error("请先完善个人信息");
        }

        taApplication.setPersonId(taPerson.getPersonId());
        taApplication.setPersonName(taPerson.getNickName());
        taApplication.setPhone(taPerson.getPhone());
        taApplication.setPayStatus(Constants.PAY_STATUS_READY);
        taApplication.setStatus(Constants.WORKFLOW_STATUS_READY);
        taApplication.setCreateDate(LocalDateTime.now());
        taApplication.setVerifyStatus(Constants.AUDIT_STATUS_READY);
        taApplication.setMakeStatus(Constants.MAKE_STATUS_READY);

        if (Constants.APPLY_TYPE_RENEWAL.equals(taApplication.getApplyType())) {
            // 如果是续期申请
            if (StringUtils.isEmpty(taApplication.getOriginCardNo())) {
                return ResponseBean.error("未找到原始证件信息");
            }
            TaPetIdentity taPetIdentity = iTaPetIdentityService.getExistBy("card_no", taApplication.getOriginCardNo(), false, true);
            if (null == taPetIdentity) {
                return ResponseBean.error("未找到原始证件信息");
            }

            // 续期不需要缴费, 直接状态位待审核
            taApplication.setStatus(Constants.WORKFLOW_STATUS_PROCESSING);
        } else if (Constants.APPLY_TYPE_REISSUE.equals(taApplication.getApplyType())) {
            // 如果是挂失补办
            if (StringUtils.isEmpty(taApplication.getOriginCardNo())) {
                return ResponseBean.error("未找到原始证件信息");
            }
            TaPetIdentity taPetIdentity = iTaPetIdentityService.getExistBy("card_no", taApplication.getOriginCardNo(), false, true);
            if (null == taPetIdentity) {
                return ResponseBean.error("未找到原始证件信息");
            }

            // 直接将原卡置为挂失
            taPetIdentity.setStatus(Constants.CARD_STATUS_LOSS);
            if (!iTaPetIdentityService.updateById(taPetIdentity)) {
                return ResponseBean.error("挂失证件失败, 请重试");
            }

            Integer totalCharge = iTaApplicationService.getTotalCharge(taApplication);
            if (totalCharge < 1) {
                // 不需要缴费
                taApplication.setStatus(Constants.WORKFLOW_STATUS_PROCESSING);
            }

        } else {
            // 当前狗狗是否存在证件
            TaPetIdentity origin = iTaPetIdentityService.getByPet(taApplication.getPetId(), taApplication.getPersonId());
            if (null != origin) {
                return ResponseBean.error("请先挂失原始证件");
            }

            Integer totalCharge = iTaApplicationService.getTotalCharge(taApplication);
            if (totalCharge < 1) {
                // 不需要缴费
                taApplication.setStatus(Constants.WORKFLOW_STATUS_PROCESSING);
            }

        }

        if (iTaApplicationService.save(taApplication)){
            return ResponseBean.success(taApplication);
        } else {
            return ResponseBean.error("保存失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @RequestMapping(value="/wx/{clientId}/application/{id}", method= RequestMethod.DELETE)
    @ApiOperation(value="微信删除", notes = "微信删除", httpMethod = "DELETE", response = ResponseBean.class)
    public ResponseBean taApplicationDelete(@ApiParam("对象ID") @PathVariable Integer id) throws Exception{
        TaPerson taPerson = currentPerson();

        TaApplication taApplication = iTaApplicationService.getById(id);
        if (null == taApplication || taApplication.getStatus() == Constants.STATUS_DELETE) {
            return ResponseBean.error("未找到数据");
        }

        if (!taPerson.getPersonId().equals(taApplication.getPersonId())) {
            return ResponseBean.error("无权操作");
        }

        if (taApplication.getStatus() >= Constants.WORKFLOW_STATUS_PROCESSING) {
            return ResponseBean.error("流程已提审, 不能删除");
        }

        if(iTaApplicationService.removeLogicById(id)){
            return ResponseBean.success("success");
        }else {
            return ResponseBean.error("删除失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param auditParam 实体对象
     * @return
     */
    @RequestMapping(value="/admin/application/{id}/audit",method= RequestMethod.PUT)
    @ApiOperation(value="审批", notes = "审批", httpMethod = "PUT", response = ResponseBean.class)
    public ResponseBean audit(@ApiParam("对象ID") @PathVariable Integer id,
                                        @ApiParam("更新内容") @RequestBody AuditParam auditParam) throws Exception{

        // 目前业务有 3 种, 初次申请, 挂失, 续期
        // 其中 续期 不需要缴费
        // 如果审核驳回，那么已缴费用, 需要原路返回

        SysUser sysUser = currentUser();
        if (!checkRole(sysUser.getRoleName(), Constants.USER_AUDITOR)) {
            return ResponseBean.error("暂无权限");
        }

        TaApplication taApplication = iTaApplicationService.getById(id);
        if (null == taApplication || taApplication.getStatus() == Constants.STATUS_DELETE) {
            return ResponseBean.error("未找到数据");
        }

        if (taApplication.getStatus() >= Constants.WORKFLOW_STATUS_AUDIT) {
            return ResponseBean.error("当前记录已审批");
        }

        if (auditParam.getVerifyStatus() == Constants.AUDIT_STATUS_REJECT) {
            if (StringUtils.isEmpty(auditParam.getRejectReason())) {
                return ResponseBean.error("请填写驳回理由");
            }

            // 如果已经缴费, 则原路退回费用
            if (Constants.PAY_STATUS_PAID == taApplication.getPayStatus()) {
                iTaOrderService.refundByApplication(taApplication);
            }
        }

        taApplication.setVerifyStatus(auditParam.getVerifyStatus());
        taApplication.setRejectReason(auditParam.getRejectReason());
        taApplication.setVerifyDate(LocalDateTime.now());
        taApplication.setVerifyUser(sysUser.getUserId());
        taApplication.setVerifyUserName(sysUser.getUserName());
        taApplication.setStatus(Constants.WORKFLOW_STATUS_AUDIT);

        if (Constants.APPLY_TYPE_FIRST.equals(taApplication.getApplyType())) {
            // 办证申请
//            if (taApplication.getPayStatus() != Constants.PAY_STATUS_PAID) {
//                return ResponseBean.error("用户未支付");
//            }
        } else if (Constants.APPLY_TYPE_RENEWAL.equals(taApplication.getApplyType())) {
            // 续期 - 续期不需要费用
            if (StringUtils.isEmpty(taApplication.getOriginCardNo())) {
                return ResponseBean.error("未找到原始证件信息");
            }

            TaPetIdentity taPetIdentity = iTaPetIdentityService.getExistBy("card_no", taApplication.getOriginCardNo(), false, true);
            if (null == taPetIdentity) {
                return ResponseBean.error("未找到原始证件信息");
            }

            // 审核同意之后, 直接续期原证件
            if (Constants.AUDIT_STATUS_PASSED == auditParam.getVerifyStatus()) {
                if (!iTaPetIdentityService.extendDate(taPetIdentity)) {
                    return ResponseBean.error("续期证件失败, 请重试");
                }

                // 续期不需要制卡, 直接变为已制卡
                taApplication.setStatus(Constants.WORKFLOW_STATUS_MADE);
                taApplication.setMakeStatus(Constants.MAKE_STATUS_MADE);
            }
        } else if (Constants.APPLY_TYPE_REISSUE.equals(taApplication.getApplyType())) {
            // 补办
//            if (taApplication.getPayStatus() != Constants.PAY_STATUS_PAID) {
//                return ResponseBean.error("用户未支付");
//            }

            if (StringUtils.isEmpty(taApplication.getOriginCardNo())) {
                return ResponseBean.error("未找到原始证件信息");
            }

            TaPetIdentity taPetIdentity = iTaPetIdentityService.getExistBy("card_no", taApplication.getOriginCardNo(), false, true);
            if (null == taPetIdentity) {
                return ResponseBean.error("未找到原始证件信息");
            }
        } else {
            return ResponseBean.error("申办业务类型不支持");
        }

        if (iTaApplicationService.updateById(taApplication)){
            return ResponseBean.success(taApplication);
        }else {
            return ResponseBean.error("修改失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 发证
     * @param id  实体ID
     * @param makeCardParam 实体对象
     * @return
     */
    @RequestMapping(value="/admin/application/{id}/make",method= RequestMethod.PUT)
    @ApiOperation(value="发证", notes = "发证", httpMethod = "PUT", response = ResponseBean.class)
    public ResponseBean makeCard(@ApiParam("对象ID") @PathVariable Integer id,
                              @ApiParam("更新内容") @RequestBody MakeCardParam makeCardParam) throws Exception{
        SysUser sysUser = currentUser();
        if (!checkRole(sysUser.getRoleName(), Constants.USER_MAKER)) {
            return ResponseBean.error("暂无权限");
        }

        TaApplication taApplication = iTaApplicationService.getById(id);
        if (null == taApplication || taApplication.getStatus() == Constants.STATUS_DELETE) {
            return ResponseBean.error("未找到数据");
        }

//        if (!taApplication.getApplyType().equals(Constants.APPLY_TYPE_RENEWAL)
//                && taApplication.getPayStatus() != Constants.PAY_STATUS_PAID) {
//            return ResponseBean.error("当前申请工本费未支付");
//        }

//        if (taApplication.getStatus() != Constants.WORKFLOW_STATUS_AUDIT
//                && taApplication.getVerifyStatus() == Constants.AUDIT_STATUS_PASSED) {
//            return ResponseBean.error("申请未通过或状态不对");
//        }

        if (!Constants.APPLY_TYPE_FIRST.equals(taApplication.getApplyType())
                && !Constants.APPLY_TYPE_REISSUE.equals(taApplication.getApplyType())) {
            return ResponseBean.error("非制证申请");
        }

        if (taApplication.getApplyMethod() == Constants.APPLY_METHOD_EXPRESS) {
            if (StringUtils.isEmpty(makeCardParam.getTrackingType()) || StringUtils.isEmpty(makeCardParam.getTrackingNo())) {
                return ResponseBean.error("请填写快递信息");
            } else {
                taApplication.setTrackingNo(makeCardParam.getTrackingNo());
                taApplication.setTrackingType(makeCardParam.getTrackingType());
            }
        }

        if (StringUtils.isEmpty(makeCardParam.getCardNo())) {
            return ResponseBean.error("卡号不能为空");
        } else {
            TaCardNo taCardNo = iTaCardNoService.getUnuseCard(makeCardParam.getCardNo());
            if (taCardNo == null) {
                return ResponseBean.error("卡号无效或者已使用");
            }

            // 将卡号置为已使用
            taCardNo.setStatus(Constants.STATUS_NORMAL);
            iTaCardNoService.updateById(taCardNo);

            TaPetIdentity taPetIdentity = iTaPetIdentityService.getExistBy("card_no", makeCardParam.getCardNo(), false, true);
            if (null != taPetIdentity) {
                return ResponseBean.error("卡号已被占用");
            }
        }

        // 关联证件
        taApplication.setOriginCardNo(makeCardParam.getCardNo());
        taApplication.setMakeStatus(Constants.MAKE_STATUS_MADE);
        taApplication.setMakeDate(LocalDateTime.now());
        taApplication.setMakeUser(sysUser.getUserId());
        taApplication.setMakeUserName(sysUser.getUserName());
        taApplication.setTrackingType(makeCardParam.getTrackingType());
        taApplication.setTrackingNo(makeCardParam.getTrackingNo());
        taApplication.setStatus(Constants.WORKFLOW_STATUS_MADE);

        if (iTaApplicationService.updateById(taApplication)){
            TaPetIdentity newCard = iTaPetIdentityService.createNewCard(taApplication, makeCardParam);

            return ResponseBean.success(newCard);
        } else {
            return ResponseBean.error("修改失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/admin/application/{id}",method= RequestMethod.GET)
    @ApiOperation(value="详情", notes = "详情", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean taApplicationGet(@ApiParam("对象ID") @PathVariable Integer id) throws Exception{

        TaApplication taApplication = iTaApplicationService.getById(id);
        if (taApplication == null || taApplication.getStatus() == Constants.STATUS_DELETE) {
            return ResponseBean.error("未找到数据");
        }

        return ResponseBean.success(taApplication);
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/wx/{clientId}/application/{id}",method= RequestMethod.GET)
    @ApiOperation(value="微信详情", notes = "微信详情", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean wxGet(@ApiParam("对象ID") @PathVariable Integer id) throws Exception{

        TaApplication taApplication = iTaApplicationService.getById(id);
        if (taApplication == null || taApplication.getStatus() == Constants.STATUS_DELETE) {
            return ResponseBean.error("未找到数据");
        }

        TaPerson taPerson = currentPerson();
        if (!taPerson.getPersonId().equals(taApplication.getPersonId())) {
            return ResponseBean.error("未找到数据");
        }

        return ResponseBean.success(taApplication);
    }

}
