package com.sifang.modules.flowpath.web;

import com.jfinal.plugin.activerecord.Record;
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.entity.SupplySupplierApply;
import com.sifang.modules.flowpath.entity.SupplyWarehouseApply;
import com.sifang.modules.flowpath.service.CashOutApplyService;
import com.sifang.modules.flowpath.service.DistributionGoodsApplyService;
import com.sifang.modules.flowpath.service.ExamineInfoService;
import com.sifang.modules.flowpath.service.SupplyWarehouseApplyService;
import com.sifang.modules.flowpath.vo.CashOutVo;
import com.sifang.modules.flowpath.vo.UserApplyVo;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.AddressUtils;
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.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.dao.CrmSupplyWarehouseDao;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
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.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.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value = "${adminPath}/apply/warehouseApply")
public class SupplyWarehouseApplyController extends BaseExceptionController {

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

    @Autowired
    private SupplyWarehouseApplyService supplyWarehouseApplyService;


    @Autowired
    private ExamineInfoService examineInfoService;

    @Autowired
    TraderService traderService;

    @Autowired
    AddressService addressService;

    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    private CrmSupplyWarehouseDao warehouseDao;


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

    @ResponseBody
    @RequestMapping(value = "warehouseApplyList")
    public String warehouseApplyList(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        User user = UserUtils.getUser();
        String ascriptionId="";
        if (User.USER_TYPE_ADVISOR.equals(user.getUserType()) || User.USER_TYPE_KJ.equals(user.getUserType())) {
            ascriptionId = CrmUtils.getUserRelId(user);
        }
        map.put("ascriptionId",ascriptionId);
        supplyWarehouseApplyService.findApplyPage(page, map);
        return page.renderJson();
    }

    /**
     * 新增申请页面
     */
    @RequestMapping(value = "addWarehouseApply")
    public String addCashOutApplyPage(Model model,HttpServletRequest request){
        List<Record> province = addressService.getProvinces();//获取所有的省
        model.addAttribute("province", province);
        User user = UserUtils.getUser();
        String id = request.getParameter("id");
        model.addAttribute("model","add");
        model.addAttribute("userType",user.getUserType());
        if (StringUtil.isNotBlank(id)) {
           /* SupplyWarehouseApply warehouse = supplyWarehouseApplyService.get(id);*/
            CrmSupplyWarehouse warehouse=warehouseDao.get(id);
            model.addAttribute("warehouse", warehouse);
            if(StringUtil.isNotBlank(warehouse.getQualificationsImgs())){
                String[] arr=warehouse.getQualificationsImgs().split(",");
                model.addAttribute("quaimgs",warehouse.getQualificationsImgs().split(","));
                model.addAttribute("quaimgsCount", arr.length);
            }
            String pro = warehouse.getProvince();
            String city = warehouse.getCity();
            //根据省查询下面的
            List<Record> citys = AddressUtils.getCityByProName(pro);
            List<Record> areas = AddressUtils.getAreaByCityName(city);
            model.addAttribute("city", citys);
            model.addAttribute("area", areas);
            model.addAttribute("imgsCount", 1);
            model.addAttribute("model","edit");
        }

        return "modules/flowpath/addWarehouseApply";
    }


    //新建/修改申请

    /**
     *请款申请修改为从结算明细勾选数据提交，不走提交申请按钮输入金额，系统会自动扣减电站扣款的金额，并且需要校验体现总额不能超过总结算金额。
     * 能准确知道具体是哪个电站扣减结算。固定每月5/15/25号才可请款操作。
     */
    @ResponseBody
    @RequestMapping(value = "saveWarehouseApply")
    public Result saveWarehouseApply(@RequestBody SupplyWarehouseApply vo){
        supplyWarehouseApplyService.saveWarehouse(vo);
        return Result.ok();
    }

    /**
     * 代理商仓库编辑调用
     * @param vo 仓库信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "saveWarehouseApplyFromWareEdit")
    public Result saveWarehouseApplyFromWareEdit(@Valid CrmSupplyWarehouse vo){
        try{
            supplyWarehouseApplyService.saveWarehouseApplyFromWareEdit(vo);
            return Result.ok();
        }catch (RuntimeException r){
            r.printStackTrace();
            return Result.fail(r.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>saveWarehouseApply e:{}",e);
        }
        return Result.fail("保存失败");
    }


    // 详情/审核 页面
    @RequestMapping(value = "warehouseApplyDetail")
    public String warehouseApplyDetail(String id,String from,Model model){
        List<Record> province = addressService.getProvinces();//获取所有的省
        model.addAttribute("from",from);
        CrmSupplyWarehouse supplier=null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(id)) {
            supplier = warehouseDao.get(id);
            model.addAttribute("apply", supplier);
            List<Record> city = AddressUtils.getCityByProName(supplier.getProvince());
            List<Record> area = AddressUtils.getAreaByCityName(supplier.getCity());
            model.addAttribute("city", city);
            model.addAttribute("area", area);
        }
        model.addAttribute("province", province);
        /*List<ExamineInfo> infos=examineInfoService.getByApplyId(id,FormUtils.WAREHOUSE_APPLY);
        model.addAttribute("infos",infos);
        model.addAttribute("formId", FormUtils.WAREHOUSE_APPLY);*/
        User user = UserUtils.getUser();
        model.addAttribute("userType",user.getUserType());
        return "modules/flowpath/warehouseApplyDetailPage";
    }

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

    //审核通过
    @ResponseBody
    @RequestMapping(value = "examineWarehouseApplyApprove")
    public Result examineWarehouseApplyApprove(String id ,String taskId,String content){
        try{
            supplyWarehouseApplyService.examineWarehouseApply(id, taskId, content);
            return Result.ok();
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>examineCashOutApplyApprove e:{}",e);
            return Result.fail("审核失败！");
        }
    }

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