package com.goafanti.expenseAccount.controller;

import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.model.ExpenseAccount;
import com.goafanti.common.utils.ParamUtils;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.expenseAccount.bo.*;
import com.goafanti.expenseAccount.service.ExpenseAccountService;
import com.goafanti.organization.bo.OrganizationListOut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/admin/expenseAccount")
public class ExpenseAccountController extends CertifyApiController {

    @Resource
    private ExpenseAccountService expenseAccountService;


    @Value(value = "${upload.path}")
    private final String	uploadPath			= null;

    /**
     * 新增私有报销帐号
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Result add(@Validated InputExpenseAccount in , BindingResult bindingResult){
        Result res =new Result();
        if (bindingResult.hasErrors()) {
            String param=bindingResult.getFieldError().getField();
            res.getError().add(buildError(ParamUtils.getParamMsg(in,param),ParamUtils.getParamName(in,param)));
            return res;
        }
        in.setAid(TokenManager.getAdminId());

        res.setData(expenseAccountService.add(in));
        return res;
    }

    /**
     * 删除报销
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Result delete(String id){
        Result res =new Result();
        res.setData(expenseAccountService.delete(id));
        return res;
    }


    /**
     * 新增私有报销帐号
     * @param in  updateType=1时，作为修改类型。会删除所有子项
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Result update( InputExpenseAccount in ){
        Result res =new Result();
        in.setAid(TokenManager.getAdminId());
        //只修改状态
        if (in.getUpdateType()==1){
            res.setData(expenseAccountService.updateType(in));
        }else {
            //抵扣单借支单必须指定
            if (in.getType()==5){
                if (in.getDebitId()==null){
                    res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"抵扣单借支单"));
                    return res;
                }
            }

            res.setData(expenseAccountService.update(in));
        }
        return res;
    }

    /**
     * 删除报销抵扣
     */
    @RequestMapping(value = "/updateDebitId",method = RequestMethod.POST)
    public Result updateDebitId( InputExpenseAccount in ){
        Result res =new Result();
        res.setData(expenseAccountService.updateDebitId(in));
        return res;
    }

    /**
     * 主报销列表
     */
    @RequestMapping(value = "/mainList",method = RequestMethod.GET)
    public Result mainList(ExpenseMainListInput in){
        Result res =new Result();
        return res.data(expenseAccountService.mainList(in));
    }

    /**
     * 报销列表,子报销列表
     */
    @RequestMapping(value = "/pageList",method = RequestMethod.GET)
    public Result pageList(InputPageListBo in ){
        Result res =new Result();
        res.setData(expenseAccountService.pageList(in));
        return res;
    }

    /**
     * 费用单列表导出
     */
    @RequestMapping(value = "/pageListExport",method = RequestMethod.GET)
    public Result pageListExport(InputPageListBo in ){
        Result res =new Result();
        in.setPageSize(999999);
        res.setData(expenseAccountService.pageListExport(in));
        return res;
    }
    /**
     * 报销详情列表
     */
    @RequestMapping(value = "/detailsList",method = RequestMethod.GET)
    public Result detailsList(InputDetailsListBo in ){
        Result res =new Result();
        res.setData(expenseAccountService.detailsList(in));
        return res;
    }

    /**
     * 费用详情列表导出
     */
    @RequestMapping(value = "/detailsListExport",method = RequestMethod.GET)
    public Result detailsListExport(InputDetailsListBo in ){
        Result res =new Result();
        in.setPageSize(999999);
        res.setData(expenseAccountService.detailsListExport(in));
        return res;
    }




    /**
     * 判断当前是否存在草稿
     */
    @RequestMapping(value = "/selectByPrid",method = RequestMethod.GET)
    public Result selectByPrid(InputExpenseAccount in ){
        Result res =new Result();
        res.setData(expenseAccountService.selectByPrid(in));
        return res;
    }

    /**
     * 报销详情
     */
    @RequestMapping(value = "/selectById",method = RequestMethod.GET)
    public Result selectById(Integer id ){
        Result res =new Result();
        res.setData(expenseAccountService.selectById(id));
        return res;
    }

    /**
     * 报销查询编号
     * @param checkNo 查询编号
     */
    @RequestMapping(value = "/selectByCheckNo",method = RequestMethod.GET)
    public Result selectByCheckNo(String checkNo ){
        Result res =new Result();
        res.setData(expenseAccountService.selectByCheckNo(checkNo));
        return res;
    }




    /**
     * 新增报销详情
     */
    @RequestMapping(value = "/details/add",method = RequestMethod.POST)
    public Result addDetails(@Validated InputExpenseAccountDetails in , BindingResult bindingResult){
        Result res =new Result();
        if (bindingResult.hasErrors()) {
            String param=bindingResult.getFieldError().getField();
            System.out.println(param);
            res.getError().add(buildError(ParamUtils.getParamMsg(in,param),ParamUtils.getParamName(in,param)));
            return res;
        }
        res.setData(expenseAccountService.addDetails(in));
        return res;
    }

    /**
     * 删除报销详情
     */
    @RequestMapping(value = "/details/delete",method = RequestMethod.GET)
    public Result deleteDetails(Integer id){
        Result res =new Result();
        res.setData(expenseAccountService.deleteDetails(id));
        return res;
    }

    /**
     * 报销详情
     */
    @RequestMapping(value = "/details/list",method = RequestMethod.GET)
    public Result detailsList(Integer eaid){
        Result res =new Result();
        res.setData(expenseAccountService.detailsList(eaid));
        return res;
    }

    @RequestMapping(value = "/log/list",method = RequestMethod.GET)
    public Result logList(Integer eaid){
        Result res =new Result();
        if (eaid==null){
            res.getError().add(buildErrorMessageParams(ErrorConstants.PARAM_EMPTY_ERROR,"报销编号"));
            return res;
        }
        res.setData(expenseAccountService.logList(eaid));
        return res;
    }


    /**
     * 报销审核
     */
    @RequestMapping(value = "/examine",method = RequestMethod.POST)
    public Result examine(InputExpenseAccount in,BindingResult bindingResult){
        Result res =new Result();
        if (bindingResult.hasErrors()) {
            String param=bindingResult.getFieldError().getField();
            res.getError().add(buildError(ParamUtils.getParamMsg(in,param),ParamUtils.getParamName(in,param)));
            return res;
        }
        res.setData(expenseAccountService.updateExamine(in));
        return res;
    }

    /**
     * 获取借支列表
     */
    @RequestMapping(value = "/selectDebitOrder",method = RequestMethod.GET)
    public Result selectDebitOrder(String depId,Integer id){
        Result res=new Result();
        if (depId==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"抵扣部门"));
            return  res;
        }
        res.setData(expenseAccountService.selectDebitOrder(depId,id));
        return res;
    }

    /**
     * 获取后台统计数据
     */
    @RequestMapping(value = "/statistics",method = RequestMethod.GET)
    public Result statistics(String name,String depId,String startTime,String endTime) {
        Result res = new Result();
        String lander = null;
        if (TokenManager.hasRole(AFTConstants.FINANCE)) {
            lander = TokenManager.getAdminId();
        }
        res.setData(expenseAccountService.statistics(name, depId, startTime, endTime, lander));
        return res;
    }

    @RequestMapping(value = "/statistics/evict",method = RequestMethod.GET)
    public Result statisticsEvict(String name,String depId,String startTime,String endTime){
        Result res=new Result();
        expenseAccountService.statisticsEvict(  name, depId, startTime, endTime);
        return res.data(1);
    }


    /**
     * 获取后台统计数据
     */
    @RequestMapping(value = "/statistics/export",method = RequestMethod.GET)
    public Result statisticsExport(String name,String depId,String startTime,String endTime) {
        String lander = null;
        if (TokenManager.hasRole(AFTConstants.FINANCE)) {
            lander = TokenManager.getAdminId();
        }
        List<OutExpenseAccountStatistics> list = expenseAccountService.statistics(name, depId, startTime, endTime, lander);
        NewExcelUtil<OutExpenseAccountStatistics> newExcelUtil = new NewExcelUtil<>(OutExpenseAccountStatistics.class);
        return newExcelUtil.exportExcel(list, "报销统计", uploadPath);
    }

    /**
     * 合并报销
     */
    @RequestMapping(value = "/merge",method = RequestMethod.GET)
    public Result merge(String ids){
        Result res =new Result();
        if (ids==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"合并编号"));
            return  res;
        }
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        List<ExpenseAccount> expenseAccounts = expenseAccountService.selectByIds(list);
        for (ExpenseAccount e : expenseAccounts) {
            if (e.getStatus()!=0){
                res.getError().add(buildError(String.format("[%s]编号已经发起，不能重复发起。",e.getId())));
                return res;
            }else if (e.getTotalAmount().compareTo(new BigDecimal(0))==0){
                res.getError().add(buildError(String.format("[%s]编号金额为0，请完善修改后发起。",e.getId())));
                return res;
            }
        }
        //预借支不允许和其他类型发起报销
        int i = expenseAccountService.selectCountByIdsAndType(list, 5);
        if (i>0){
            if (i!=expenseAccounts.size()+1){
                res.getError().add(buildError("不允许抵扣与其他类型报销合并发起。"));
                return res;
            }
        }
        return res.data(expenseAccountService.pushMerge(expenseAccounts));
    }




    /**
     * 主报销详情
     */
    @RequestMapping(value = "/mainExpense",method = RequestMethod.GET)
    public Result mainExpense(Integer id){
        Result res =new Result();
        if (id==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"合并编号"));
            return  res;
        }
        return res.data(expenseAccountService.mainExpense(id));
    }



    /**
     * 主报销详情导出PDF，未完待续
     */
    @RequestMapping(value = "/mainExpenseExport",method = RequestMethod.GET)
    public Result mainExpenseExport(Integer id, HttpServletResponse response){
        Result res =new Result();
        if (id==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"合并编号"));
            return  res;
        }
        return res.data(expenseAccountService.mainExpenseExport(id,response));
    }




    /**
     * 修改主报销
     */
    @RequestMapping(value = "/updateMain",method = RequestMethod.POST)
    public Result updateMain( MainExpenseAccount in){
        Result res =new Result();
        if (in.getId()==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"编号"));
            return  res;
        }
        if (in.getStatus()==1&&in.getEaaid()==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"报销账号"));
            return  res;
        }
        return res.data(expenseAccountService.updateMain(in));
    }

    /**
     * 修改实报金额
     * @param type 类型 1报销与费用  2费用详细  去掉修改上级，只能修改费用
     * @param id 编号
     * @param amount 金额
     */
    @RequestMapping(value = "/updateRealAmount",method = RequestMethod.POST)
    public Result updateRealAmount(Integer type ,Integer id,BigDecimal amount){
        Result res =new Result();
        if (id==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"编号"));
            return  res;
        }
        if (amount==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"金额"));
            return  res;
        }
        return res.data(expenseAccountService.updateRealAmount( type , id, amount));
    }

    /**
     *  修改报销类型说明
     */
    @RequestMapping(value = "/updateTypeOther",method = RequestMethod.POST)
    public Result updateTypeOther(Integer id ,String typeOther,String remarks,String orderNo){
        Result res =new Result();
        if (id==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"编号"));
            return  res;
        }
        return res.data(expenseAccountService.updateTypeOther(id, typeOther,remarks,orderNo));
    }

    /**
     *  修改报销详情类型说明
     */
    @RequestMapping(value = "/updateDetailsTypeOther",method = RequestMethod.POST)
    public Result updateDetailsTypeOther(Integer id , String typeOther){
        Result res =new Result();
        if (id==null){
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"编号"));
            return  res;
        }
        return res.data(expenseAccountService.updateDetailsTypeOther(id, typeOther));
    }

    /**
     * 主类分类说明
     */
    @RequestMapping(value = "/pushAll",method = RequestMethod.GET)
    public Result pushAll(){
        expenseAccountService.pushAll();
        return null;
    }

    /**
     * 订单报销情&公出详情计算触发接口
     */
    @RequestMapping(value = "/pushExpenseTotalAmount",method = RequestMethod.GET)
    public Result pushExpenseTotalAmount(){
        expenseAccountService.pushExpenseTotalAmount();
        return res().data(true);
    }

    /**
     *  获取报销部门设置
     */
    @RequestMapping(value = "/getDepDetails",method = RequestMethod.GET)
    public Result<OrganizationListOut> getDepDetails(Integer id){
        Result res= new Result();
        return res.data(expenseAccountService.getDepDetails(id));
    }

}
