package com.sifang.modules.flowpath.web;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.form.SelectVo;
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.ExamineInfoService;
import com.sifang.modules.flowpath.service.SubpackageStandardPriceApplyService;
import com.sifang.modules.flowpath.vo.SubpackageVo;
import com.sifang.modules.flowpath.vo.UserApplyVo;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.sunshine.SystemSetting.service.ProjectInfoSettingService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseController;
import com.sifang.modules.sys.web.BaseExceptionController;
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.ArrayList;
import java.util.List;
import java.util.Map;

//分包保准价申请
@Controller
@RequestMapping(value = "${adminPath}/apply/standardPrice")
public class SubpackageStandardPriceController extends BaseExceptionController {

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

    @Autowired
    private SubpackageStandardPriceApplyService standardPriceApplyService;

    @Autowired
    private ExamineInfoService examineInfoService;

    @Autowired
    MemberService memberService;
    @Autowired
    ProjectInfoSettingService projectInfoSettingService;
    @Autowired
    private TraderService traderService;

    @Autowired
    private ProcessFlowableService processFlowableService;


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

    @ResponseBody
    @RequestMapping(value = "listData")
    public String listData(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        standardPriceApplyService.applyList(page,map);
        return page.renderJson();
    }

    //新增页面
    @RequestMapping(value = "addSubpackageStandardPage")
    public String addDistributionGoodsPage(Model model){
        List<Record> list=standardPriceApplyService.getProjectName();
        model.addAttribute("projects",list);
        model.addAttribute("itemCount",0);
        return "modules/flowpath/addSubpackageStandardPage";
    }

    @RequestMapping(value = "projectOrTraderPage")
    public String projectOrTraderPage(Model model,String type,String ids){
        // type =1  添加产品  type=2  添加代理商
        model.addAttribute("type",type);
        model.addAttribute("ids",ids);
        return "modules/flowpath/projectOrTraderPage";
    }

    @ResponseBody
    @RequestMapping(value = "projectOrTraderData")
    public String projectOrTraderData(HttpServletRequest request,String setType){
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        if("2".equals(setType)){
            map.put("type","1");

            traderService.listTrader(page,map);
        }else{
            projectInfoSettingService.listProjectSettings(page,map);
        }

        return page.renderJson();
    }

    //新增/修改
    @ResponseBody
    @RequestMapping(value = "saveStandardPriceApply")
    public Result saveStandardPriceApply(@RequestBody SubpackageVo vo){
        try{
            standardPriceApplyService.saveStandardPriceApply(vo);
            return Result.ok();
        }catch (RuntimeException r){
            r.printStackTrace();
            return Result.fail(r.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>saveStandardPriceApply e:{}",e);
        }
        return Result.fail("保存失败");
    }

    //编辑页面
    @RequestMapping(value = "editStandardPriceApply")
    public String editStandardPriceApply(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        Record apply=standardPriceApplyService.getDetailById(id);
        model.addAttribute("apply",apply);
        List<Record> items=standardPriceApplyService.getApplyItems(id);
        model.addAttribute("items",items);
        if(items.size()>0){
            Record rd = items.get(0);
            Map<String,String> map = Maps.newHashMap();
            if(StringUtil.isNotBlank(rd.getStr("trader_ids"))){
                map.put("traderIds",rd.getStr("trader_ids"));
                model.addAttribute("traders",traderService.findTraderRecordsList(map));
            }
            map.put("proIds",rd.getStr("project_ids"));

            model.addAttribute("projectsOld",projectInfoSettingService.findProjectSettingsList(map));
        }

        model.addAttribute("itemCount",items.size());
       // model.addAttribute("itemJson",new Gson().toJson(item));
        List<Record> list=standardPriceApplyService.getProjectNameByApply(id);
      /*  model.addAttribute("projects",list);*/
        return "modules/flowpath/addSubpackageStandardPage";
    }

    //查看详情/审批页面/系统设置--结算价设置-查看页面
    @RequestMapping(value = "standardPriceApplyDetailPage")
    public String standardPriceApplyDetailPage(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        Record apply=standardPriceApplyService.getDetailById(id);
        model.addAttribute("apply",apply);
        List<Record> items=standardPriceApplyService.getApplyItems(id);
        model.addAttribute("items",items);

        if(items.size()>0){
            Record rd = items.get(0);
            Map<String,String> map = Maps.newHashMap();
            if(StringUtil.isNotBlank(rd.getStr("trader_ids"))){
                map.put("traderIds",rd.getStr("trader_ids"));
                model.addAttribute("traders",traderService.findTraderRecordsList(map));
            }
            map.put("proIds",rd.getStr("project_ids"));

            model.addAttribute("projects",projectInfoSettingService.findProjectSettingsList(map));
        }

        String detailId=request.getParameter("detailId");  // 来自 系统设置--结算价设置-查看页面
        if(StringUtil.isNotBlank(detailId)){
            List<Record> rds=new ArrayList<>();
           for(Record r:items){
               if(r.getStr("id").equals(detailId)){
                   rds.add(r);
                   break;
               }
           }
           model.addAttribute("items",rds);
        }
        String from=request.getParameter("from"); //from = audit 那么就是审批操作  否则就是查看
        model.addAttribute("from",from);
        List<ExamineInfo> infos=examineInfoService.getByApplyId(id,FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION);
        model.addAttribute("infos",infos);
        User user = UserUtils.getUser();
        if(!"audit".equals(from)){
            processFlowableService.readApplication(apply.getStr("process_instance_id"),FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION,id,user);
        }
        return "modules/flowpath/applyStandardPriceApplyDetail";
    }

    //查看
    @RequestMapping(value = "lookItemPage")
    public String lookItemPage(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        Record apply=standardPriceApplyService.getDetailById(id);
        model.addAttribute("apply",apply);
        List<Record> items=standardPriceApplyService.getApplyItems(id);
        model.addAttribute("items",items);
        if(items.size()>0){
            Record rd = items.get(0);
            Map<String,String> map = Maps.newHashMap();
            if(StringUtil.isNotBlank(rd.getStr("trader_ids"))){
                map.put("traderIds",rd.getStr("trader_ids"));
                model.addAttribute("traders",traderService.listTraderRecords(null,map));
            }
            map.put("proIds",rd.getStr("project_ids"));

            model.addAttribute("projects",projectInfoSettingService.findProjectSettingsList(map));
        }
        return "modules/flowpath/lookItemPage";
    }

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

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

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



}
