package com.sifang.modules.flowpath.web;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.entity.CrmTraderAccount;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.flowable.service.ProcessFlowableService;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.entity.ExamineInfo;
import com.sifang.modules.flowpath.service.DistributionGoodsApplyService;
import com.sifang.modules.flowpath.service.ExamineInfoService;
import com.sifang.modules.flowpath.service.SettlementAmountAdjustmentApplyService;
import com.sifang.modules.flowpath.vo.DistributionGoodsVo;
import com.sifang.modules.flowpath.vo.UserApplyVo;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseController;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

// 结算额调整申请
@Controller
@RequestMapping(value = "${adminPath}/apply/settlementAmount")
public class SettlementAmountAdjustmentApplyController extends BaseExceptionController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ExamineInfoService examineInfoService;

    @Autowired
    private SettlementAmountAdjustmentApplyService settlementApplyService;

    @Autowired
    private DistributionGoodsApplyService distributionGoodsApplyService;

    @Autowired
    private TraderService traderService;

    @Autowired
    private ProcessFlowableService flowableService;


    //页面
    @RequestMapping(value = "settlementAmountListPage")
    public String applyListPage(Model model) {
        User user = UserUtils.getUser();
        model.addAttribute("userId",user.getId());
        model.addAttribute("formId", FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION);
        return "modules/flowpath/settlementAmountListPage";
    }

    @ResponseBody
    @RequestMapping(value = "listData")
    public String listData(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        String traderId = "";
        if (User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())) {  //代理商
            traderId = CrmUtils.getUserRelId(user);
        } if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            //平台人员
            EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
        }
        map.put("traderId", traderId);
        LayuiPage page = new LayuiPage(request);
        settlementApplyService.applyList(page, map);
        return page.renderJson();
    }

    //新增页面
    @RequestMapping(value = "addSettlementAmountPage")
    public String addDistributionGoodsPage(Model model){
        List<Record> list= distributionGoodsApplyService.getTrader();
        model.addAttribute("traders",list);
        model.addAttribute("imgsCount", 0);
        return "modules/flowpath/addSettlementAmountPage";
    }

    //新建/修改申请
    @ResponseBody
    @RequestMapping(value = "saveSettlementAmountApply")
    public Result saveDistributionGoods(@RequestBody DistributionGoodsVo vo){
        try{
            settlementApplyService.saveSettlementAmountApply(vo);
            return Result.ok();
        }catch (RuntimeException r){
            r.printStackTrace();
            return Result.fail(r.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>saveSettlementAmountApply e:{}",e);
        }
        return Result.fail("保存失败");
    }

    //编辑页面
    @RequestMapping(value = "editSettlementAmountApplyPage")
    public String editSettlementAmountApplyPage(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        Record apply=settlementApplyService.getDetailById(id);
        model.addAttribute("apply",apply);
        List<Record> list=distributionGoodsApplyService.getTrader();
        model.addAttribute("traders",list);
        List<ExamineInfo> infos=examineInfoService.getByApplyId(id,FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION);
        model.addAttribute("infos",infos);
        int imgsCount = 0;
        if (StringUtils.isNotBlank(apply.getStr("voucher"))) {
            String[] imgArr = apply.getStr("voucher").split(",");
            imgsCount = imgArr.length;
            List<String> imglist = Arrays.asList(imgArr);
            model.addAttribute("imglist", imglist);
        }
        model.addAttribute("imgsCount", imgsCount);

        if("2".equals(apply.getStr("adjust_type"))){  //扣减
            List<Record> entryList= settlementApplyService.getEntryList(apply.getStr("trader_id"));
            model.addAttribute("entryList",entryList);
        }
        return "modules/flowpath/addSettlementAmountPage";
    }

    //查看详情
    @RequestMapping(value = "settlementAmountApplyDetail")
    public String settlementAmountApplyDetail(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        String from=request.getParameter("from"); //from = audit 那么就是审批操作  否则就是查看
        model.addAttribute("from",from);
        Record apply=settlementApplyService.getDetailById(id);
        model.addAttribute("apply",apply);
        List<ExamineInfo> infos=examineInfoService.getByApplyId(id, FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION);
        model.addAttribute("infos",infos);
        if (StringUtils.isNotBlank(apply.getStr("voucher"))) {
            String[] imgArr = apply.getStr("voucher").split(",");
            List<String> imglist = Arrays.asList(imgArr);
            model.addAttribute("imglist", imglist);
        }
        User user = UserUtils.getUser();
        model.addAttribute("userType",user.getUserType());
        if(!"audit".equals(from)){
            flowableService.readApplication(apply.getStr("process_instance_id"),FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION,id,user);
        }
        return "modules/flowpath/settlementAmountApplyDetail";
    }

    //删除申请
    @ResponseBody
    @RequestMapping(value = "deleteSettlementAmountApply")
    public Result deleteDistributionGoodsApply(HttpServletRequest request){
        String id=request.getParameter("id");
        try{
            settlementApplyService.deleteSettlementAmountApply(id);
            return Result.ok();
        }catch (RuntimeException r){
            r.printStackTrace();
            return Result.fail(r.getMessage());
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>deleteSettlementAmountApply e:{}",e);
            e.printStackTrace();
            return Result.fail("删除失败！");
        }
    }

    //审核通过
    @ResponseBody
    @RequestMapping(value = "examineSettlementAmountApprove")
    public Result examineSettlementAmountApprove(UserApplyVo userApplyVo){
        try{
            settlementApplyService.examineSettlementAmountApplyApprove(userApplyVo.getId(),userApplyVo.getTaskId(),userApplyVo.getContent());
            return Result.ok();
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>examineSettlementAmountApprove e:{}",e);
            return Result.fail("审核失败！");
        }
    }

    //审核驳回
    @ResponseBody
    @RequestMapping(value = "rejectSettlementAmountTask")
    public Result rejectTask(@Valid UserApplyVo userApplyVo){
        try{
            settlementApplyService.rejectSettlementAmountTask(userApplyVo.getId(),userApplyVo.getTaskId(),userApplyVo.getContent());
            return Result.ok();
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>rejectSettlementAmountTask e:{}",e);
            return Result.fail("审核失败！");
        }
    }

    //获取关联的电站
    @ResponseBody
    @RequestMapping(value = "getEntryList")
    public Result getEntryList(String traderId){
        List<Record> list= settlementApplyService.getEntryList(traderId);
        return Result.success(list);
    }
}
