package com.sifang.modules.changes.controller;


import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.service.CustomerInformationChangeService;
import com.sifang.modules.changes.vo.CustomerInformationChangeVo;
import com.sifang.modules.customer.Service.CustomerEntrySurveyRecordService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.entity.CustomerEntrySurveyRecord;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.insurance.entity.CrmCustomerEntryInsuranceInsured;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTraderEmploye;
import com.sifang.modules.sunshine.SystemSetting.service.FormSetService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderEmployeService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
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.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//客户信息变更
@Controller
@RequestMapping(value = "${adminPath}/entryChanges/customerInformationChange")
public class CustomerInformationChangeController extends BaseExceptionController {

    @Autowired
    private CustomerInformationChangeService informationChangeService;

    @Autowired
    private PartnerService partnerService;

    @Autowired
    TraderEmployeService traderEmployeService;

    @Autowired
    private CustomerEntryDao customerEntryDao;

    @Autowired
    private FormSetService formSetService;

    //待审核页面
    @RequestMapping(value = "changeWaitAuditList")
    public String changeWaitAuditList(HttpServletRequest request, Model model){
        User user=UserUtils.getUser();
        model.addAttribute("user",user);
        return "modules/yangguang/changes/customerInformationChange/changeWaitAuditList";
    }

    @ResponseBody
    @RequestMapping(value = "getListData")
    public Object getListData(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        User user = UserUtils.getUser();

        if(!StringUtil.equalsAny(user.getUserType(),User.USER_TYPE_YYS,User.USER_TYPE_WXG)){
            if(params.get("status").contains("2")){
                 params.put("status","1,2");
            }
        }
        if(User.USER_TYPE_WXG.equals(user.getUserType())){  //平台员工
            EmployeRoleUtils.getUserDataAuthority(user.getId(),params);
        }
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user), user.getUserType());
        informationChangeService.getListData(page, params, operator);
        return page.renderJson();
    }

    //变更记录页面
    @RequestMapping(value = "changeList")
    public String changeList(HttpServletRequest request,Model model){
        return "modules/yangguang/changes/customerInformationChange/changeList";
    }

    //新增、修改页面
    @RequestMapping(value = "savaEntryChangePage")
    public String savaEntryChangePage(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        String firstApply="";
        String tssBankNum="";
        String tssBankNumName="";
        if(StringUtil.isNotBlank(id)){  //修改
          Record changeRecord= informationChangeService.getByChangeId(id);
          List<Record> details= informationChangeService.getDetails(id);
          Map<String,Record> mapDetails=details.stream().collect(Collectors.toMap(e -> e.getStr("item_code"), e -> e, (a, b) -> a));
          model.addAttribute("changeRecord",changeRecord);
          model.addAttribute("mapDetails",mapDetails);
          model.addAttribute("details",details);
          firstApply=changeRecord.getStr("first_apply_status");
          if(StringUtil.isNotBlank(mapDetails.get("tssBankNumName").getStr("after_change"))){
              tssBankNum=mapDetails.get("tssBankNum").getStr("after_change");
              tssBankNumName=mapDetails.get("tssBankNumName").getStr("after_change");
          }
        }
        model.addAttribute("firstApply",firstApply);
        model.addAttribute("tssBankNum",tssBankNum);
        model.addAttribute("tssBankNumName",tssBankNumName);
        return "modules/yangguang/changes/customerInformationChange/savaEntryChangePage";
    }

    //新增变更记录
    @ResponseBody
    @RequestMapping(value = "savaEntryChange")
    public Result savaEntryChange(@RequestBody @Validated CustomerInformationChangeVo changeVo){
        String code= informationChangeService.savaEntryChange(changeVo);
        if(!"200".equals(code)){
            String msg = "";
            if ("208".equals(code)){
                msg = "修改的内容涉及重新再次进件，是否确认提交变更？";
            }else if ("209".equals(code)){
                msg = "修改的内容涉及合同重签，是否确认提交变更？";
            }
            return Result.fail("208",msg);
        }
        return Result.ok();
    }

    //审核页面
    @RequestMapping(value = "toChangeAudit")
    public String toChangeAudit(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        String form=request.getParameter("form");
        Record changeRecord= informationChangeService.getByChangeId(id);
        List<Record> details= informationChangeService.getDetails(id);
        Map<String,Record> mapDetails=details.stream().collect(Collectors.toMap(e -> e.getStr("item_code"), e -> e, (a, b) -> a));
        model.addAttribute("changeRecord",changeRecord);
        model.addAttribute("mapDetails",mapDetails);
        model.addAttribute("details",details);
        model.addAttribute("form",form); //form=look  那么是查看
        String entryId = changeRecord.getStr("entry_id");
        CustomerEntry customerEntry = customerEntryDao.get(entryId);
        model.addAttribute("customerEntry",customerEntry);
        model.addAttribute("formSet", formSetService.getListByCondition("06", customerEntry.getPartnerId()));
        return "modules/yangguang/changes/customerInformationChange/changeAuditPage";
    }

    //审核驳回
    @ResponseBody
    @RequestMapping(value = "changeRecordBack")
    public Result changeRecordBack(HttpServletRequest request){
        String id=request.getParameter("id");
        String auditRemarks=request.getParameter("auditRemarks");
        informationChangeService.changeRecordBack(id,auditRemarks);
        return Result.ok();
    }

    //申请撤回
    @ResponseBody
    @RequestMapping(value = "revokeChangeRecord")
    public Result revokeChangeRecord(HttpServletRequest request){
        String id=request.getParameter("id");
        informationChangeService.revokeChangeRecord(id);
        return Result.ok();
    }

    //审核通过
    @ResponseBody
    @RequestMapping(value = "changeRecordApprove")
    public Result changeRecordApprove(HttpServletRequest request){
        String id=request.getParameter("id");
        String auditRemarks=request.getParameter("auditRemarks");
        String confirmTrue=request.getParameter("confirmTrue");
        informationChangeService.changeRecordApprove(id,auditRemarks,confirmTrue);
        return Result.ok();
    }

    //暂存
    @ResponseBody
    @RequestMapping(value = "changeRecordTemp")
    public Result changeRecordTemp(HttpServletRequest request){
        String id=request.getParameter("id");
        String auditRemarks=request.getParameter("auditRemarks");
        informationChangeService.changeRecordTemp(id,auditRemarks);
        return Result.ok();
    }


    /**
     * 根据电站编号获取电站信息(客户信息变更)
     * @param stationCode
     * @return
     */
    @ResponseBody
    @RequestMapping("selectNumber/{stationCode}")
    public Result selectNumber(@PathVariable("stationCode") String stationCode) {
       Map<String,Object> map= informationChangeService.getCanChangeEntry(stationCode);
       return Result.success(map);
    }

    /**
     * 去选择电站页面
     */
    @RequestMapping("/toSelectEntry")
    public String toSelectEntry(Model model,HttpServletRequest request) {
        User user = UserUtils.getUser();
        //地址信息
        List<Record> pros = AddressUtils.findProvinceListByTraderId(CrmUtils.getCurrentTraderId(user.getId()), null);
        model.addAttribute("province", pros);
        String status=request.getParameter("status");
        if(StringUtil.isBlank(status)){
            status="khxxbgStatus";
        }
        model.addAttribute("status",status);
        return "modules/yangguang/changes/customerInformationChange/selectEntry";
    }

}
