package com.iamberry.wechat.handles.admin;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.agentInfo.AgentConfig;
import com.iamberry.wechat.core.entity.agentInfo.AgentOrder;
import com.iamberry.wechat.core.entity.agentInfo.AgentTooth;
import com.iamberry.wechat.core.entity.drp.PlaceRoleInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.face.agentInfo.AgentInfoService;
import com.iamberry.wechat.face.agentInfo.AgentPurchaseOrderService;
import com.iamberry.wechat.face.drp.DrpRoleInfoService;
import com.iamberry.wechat.face.efast.EfastRentService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.face.porduct.ProductColorService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.utils.SendMessageUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.iamberry.wechat.service.ImberryConfig.INFORM_SHIPPING;

/**
 * 代理商逻辑处理类
 * Created by liuzhiwei on 2017/10/11.
 */
@Controller
@RequestMapping("/admin/agentTooth")
public class AdminAgentToothHandler {

    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private ProductColorService productColorService;
    @Autowired
    private AgentPurchaseOrderService agentPurchaseOrderService;
    @Autowired
    private EfastRentService efastRentService;
    @Autowired
    private SendMessageUtil sendMessageUtil;
    @Autowired
    private RatFWLogger logger;
    @Autowired
    private CodeService codeService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private DrpRoleInfoService drpRoleInfoService;

    /**
     * 分页查询代理商优惠价配置信息
     * @param request
     * @param pageSize
     * @param pageNO
     * @return
     * @throws Exception
     */
    @RequestMapping("/select_agent_config_list")
    public ModelAndView selectAgentConfigList(HttpServletRequest request,
                                              @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                              @RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO) throws Exception {
        AgentConfig config = new AgentConfig();
        ModelAndView mv = new ModelAndView("admin/agentInfo/agentConfigList");
        StringBuilder url = new StringBuilder("/admin/agentTooth/select_agent_config_list?pageSize=");
        url.append(pageSize);
        String agentName = request.getParameter("agentName");
        String agentTel = request.getParameter("agentTel");
        String productName = request.getParameter("productName");
        String colorName = request.getParameter("colorName");
        if (StringUtils.isNotEmpty(agentName)) {
            config.setAgentName(agentName);
            url.append("&agentName=");
            url.append(agentName);
            mv.addObject("agentName",agentName);
        }
        if (StringUtils.isNotEmpty(agentTel)) {
            config.setAgentTel(agentTel);
            url.append("&agentTel=");
            url.append(agentTel);
            mv.addObject("agentTel",agentTel);
        }
        if (StringUtils.isNotEmpty(productName)) {
            config.setProductName(productName);
            url.append("&productName=");
            url.append(productName);
            mv.addObject("productName",productName);
        }
        if (StringUtils.isNotEmpty(colorName)) {
            config.setColorName(colorName);
            url.append("&colorName=");
            url.append(colorName);
            mv.addObject("colorName",colorName);
        }

        PageBean page = new PageBean();
        page.setPageSize(pageSize);
        page.setPageNumber(pageNO);
        page.initRecordBegin();
        config.setPage(page);
        url.append("&pageNO=");
        //查询代理商配置金额集合
        List<AgentConfig> configList = agentInfoService.listAgentConfig(config);
        mv.addObject("configList", configList);
        mv.addObject("pageNO", pageNO);
        mv.addObject("pageSize", agentInfoService.listAgentConfigCount(config));
        mv.addObject("url",url.toString());
        return mv;
    }

    /**
     * 进入添加代理商优惠价配置页面
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/_add_agent_config")
    public ModelAndView addAgentConfigUI(HttpServletRequest request) throws Exception {
        ModelAndView mv = new ModelAndView("admin/agentInfo/addAgentConfig");
        return mv;
    }

    /**
     * 查询商品列表
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_agent_and_product")
    public ResultMsg selectAgentAndProduct(HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        Map<String,Object> map = new HashMap<String,Object>();
        ProductColor productColor = new ProductColor();
        productColor.setPage(null);
        //查询产品颜色集合
        List<ProductColor> colorList = productColorService.selectProductColorList(productColor);
        AgentTooth agent = new AgentTooth();
        agent.setAgentStatus(1);
        //查询代理商集合
        List<AgentTooth> agentList = agentInfoService.listAgentTooth(agent);
        map.put("colorList",colorList);
        map.put("agentList",agentList);
        msg.setData(map);
        msg.setStatus(true);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        return msg;
    }

    /**
     * 添加代理商优惠价配置信息
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/add_agent_config")
    public ResultMsg addAgentConfig(HttpServletRequest request) throws  Exception {
        ResultMsg msg = new ResultMsg();
        String productColor = request.getParameter("productColor");
        String agentId = request.getParameter("sel_agent");
        if (!StringUtils.isNotEmpty(productColor)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("您没有输入优惠价请重新输入!");
        }
        if (!StringUtils.isNotEmpty(agentId)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("您没有选择代理商,请选择!");
        }

        //拆分产品id和金额
        String[] productPrice = productColor.split(",");

        //根据代理商id查询所有优惠价配置信息
        AgentConfig agentConfig = new AgentConfig();
        agentConfig.setAgentId(Integer.parseInt(agentId));
        agentConfig.setConfigStatus(1);
        List<AgentConfig> configList = agentInfoService.listAgentConfig(agentConfig);

        //校验是否已经存在该代理商的优惠价
        for (int i = 0;i < productPrice.length;i++) {
            String[] color = productPrice[i].split(":");
            int color1 = Integer.parseInt(color[0]);
            for(AgentConfig agentConfig2 : configList) {
                if (color1 == agentConfig2.getColorId()) {
                    StringBuilder message = new StringBuilder("产品为");
                    message.append(agentConfig2.getProductName());
                    message.append("颜色为");
                    message.append(agentConfig2.getColorName());
                    message.append("的产品已经配置了优惠价,无法重复配置!");
                    msg.setResultCode(ResultInfo.ERRORCODE);
                    msg.setStatus(false);
                    msg.setMessage(message.toString());
                    return msg;
                }
            }
        }

        List<AgentConfig> list = new ArrayList<AgentConfig>();
        for (int i = 0;i < productPrice.length;i++) {
            String[] color = productPrice[i].split(":");
            AgentConfig config = new AgentConfig();
            config.setAgentId(Integer.parseInt(agentId));
            config.setColorId(Integer.parseInt(color[0]));
            config.setConfigAmount(Integer.parseInt(color[1]));
            config.setConfigStatus(1);
            list.add(config);
        }
        int num = agentInfoService.addAgentConfigList(list);
        if (num > 0) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
            return msg;
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setMessage("添加代理商优惠价失败!");
            msg.setStatus(false);
            return msg;
        }
    }

    /**
     * 进入修改代理商优惠价页面
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/_update_agent_config")
    public ModelAndView updateAgentConfig(HttpServletRequest request) throws Exception {
        String configId = request.getParameter("configId");
        ModelAndView mv = new ModelAndView("admin/agentInfo/updateAgentConfig");
        mv.addObject("configId",configId);
        return mv;
    }

    /**
     * 获取代理商优惠价和产品信息
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/get_agent_config_By_Id")
    public ResultMsg getAgentConfigById(HttpServletRequest request) throws Exception{
        ResultMsg msg = new ResultMsg();
        Map<String,Object> map = new HashMap<String,Object>();
        String configId = request.getParameter("configId");
        if (!StringUtils.isNotEmpty(configId)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该配置信息不存在!");
        }
        AgentConfig config = new AgentConfig();
        config.setConfigId(Integer.parseInt(configId));
        config.setPage(null);
        //查询代理商配置金额集合
        List<AgentConfig> configList = agentInfoService.listAgentConfig(config);

        ProductColor productColor = new ProductColor();
        productColor.setPage(null);
        //查询产品颜色集合
        List<ProductColor> colorList = productColorService.selectProductColorList(productColor);
        AgentTooth agent = new AgentTooth();
        agent.setAgentStatus(1);
        //查询代理商集合
        List<AgentTooth> agentList = agentInfoService.listAgentTooth(agent);
        map.put("colorList",colorList);
        map.put("agentList",agentList);
        map.put("config",configList.get(0));
        msg.setData(map);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setStatus(true);
        return msg;
    }

    /**
     * 修改代理商优惠价信息
     * @param request
     * @param config
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/update_agent_config")
    public ResultMsg updateAgentConfig(HttpServletRequest request,AgentConfig config) throws Exception{
        ResultMsg msg = new ResultMsg();
        if (!StringUtils.isNotEmpty(config.getConfigId().toString())) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("修改代理商优惠价配置失败!");
            return msg;
        }
        AgentConfig config2 = new AgentConfig();
        config2.setConfigStatus(1);
        config2.setAgentId(config.getAgentId());
        config2.setColorId(config.getColorId());
        config2.setPage(null);
        //根据代理商id和产品颜色id查询配置信息
        List<AgentConfig> configList = agentInfoService.listAgentConfig(config2);
        if (configList != null && configList.size() > 0) {
            for (AgentConfig agent : configList) {
                if (agent != null && agent.getConfigId().intValue() != config.getConfigId()) {
                    msg.setResultCode(ResultInfo.ERRORCODE);
                    msg.setStatus(false);
                    msg.setMessage("该代理商已配置过该产品的优惠价,不能重复配置!");
                    return msg;
                }
            }
        }
        //修改代理商优惠价配置信息
        int num = agentInfoService.updateAgentConfig(config);
        if (num > 0) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
        }
        return msg;
    }

    /**
     * 修改代理商优惠价配置的状态
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/update_agent_config_status")
    public ResultMsg updateAgentConfigStatus(HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        String configId = request.getParameter("configId");
        String configStatus = request.getParameter("configStatus");
        AgentConfig config = new AgentConfig();
        if (!StringUtils.isNotEmpty(configId)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }
        if (!StringUtils.isNotEmpty(configStatus)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }

        config.setConfigId(Integer.parseInt(configId));
        //根据id查询配置信息
        AgentConfig agentConfig = agentInfoService.getAgentConfig(config);

        AgentConfig config2 = new AgentConfig();
        config2.setConfigStatus(1);
        config2.setAgentId(agentConfig.getAgentId());
        config2.setColorId(agentConfig.getColorId());
        //根据代理商id和产品颜色id查询配置信息
        config2 = agentInfoService.getAgentConfig(config);
        if (config2 != null && config2.getConfigId().intValue() != config.getConfigId()) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该代理商已配置过该产品的优惠价,不能重复配置!");
            return msg;
        }
        config.setConfigStatus(Integer.parseInt(configStatus));
        //修改代理商优惠价配置信息
        int num = agentInfoService.updateAgentConfig(config);
        if (num > 0) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
        }
        return msg;
    }

    /**
     * 分页查询代理商采购订单信息
     * @param request
     * @param pageSize
     * @param pageNO
     * @return
     * @throws Exception
     */
    @RequestMapping("/select_agent_order_list")
    public ModelAndView selectAgentOrderList(HttpServletRequest request,
                                             @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                             @RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO) throws Exception {
        ModelAndView mv = new ModelAndView("admin/agentInfo/agentOrderList");
        AgentOrder agentOrder = new AgentOrder();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        StringBuilder url = new StringBuilder("/admin/agentTooth/select_agent_order_list?pageSize=");
        url.append(pageSize);
        String agentStatus = request.getParameter("agentStatus");
        String agentName = request.getParameter("agentName");
        String agentTel = request.getParameter("agentTel");
        String agentAddressName = request.getParameter("agentAddressName");
        String agentAddressTel = request.getParameter("agentAddressTel");
        String beginDate = request.getParameter("beginDate");
        String endDate = request.getParameter("endDate");
        if (StringUtils.isNotEmpty(agentStatus)) {
            agentOrder.setAgentStatus(Integer.parseInt(agentStatus));
            url.append("&agentStatus=");
            url.append(Integer.parseInt(agentStatus));
            mv.addObject("agentStatus",Integer.parseInt(agentStatus));
        }
        if (StringUtils.isNotEmpty(agentName)) {
            agentOrder.setAgentName(agentName);
            url.append("&agentName=");
            url.append(agentName);
            mv.addObject("agentName",agentName);
        }
        if (StringUtils.isNotEmpty(agentTel)) {
            agentOrder.setAgentTel(agentTel);
            url.append("&agentTel=");
            url.append(agentTel);
            mv.addObject("agentTel",agentTel);
        }
        if (StringUtils.isNotEmpty(agentAddressName)) {
            agentOrder.setAgentAddressName(agentAddressName);
            url.append("&agentAddressName=");
            url.append(agentAddressName);
            mv.addObject("agentAddressName",agentAddressName);
        }
        if (StringUtils.isNotEmpty(agentAddressTel)) {
            agentOrder.setAgentAddressTel(agentAddressTel);
            url.append("&agentAddressTel=");
            url.append(agentAddressTel);
            mv.addObject("agentAddressTel",agentAddressTel);
        }
        if (StringUtils.isNotEmpty(beginDate)) {
            url.append("&beginDate=");
            url.append(beginDate);
            mv.addObject("beginDate",beginDate);
            agentOrder.setBeginDate(format.parse(beginDate));
        }
        if (StringUtils.isNotEmpty(endDate)) {
            url.append("&endDate=");
            url.append(endDate);
            mv.addObject("endDate",endDate);
            agentOrder.setEndDate(format.parse(endDate));
        }

        PageBean page = new PageBean();
        page.setPageNumber(pageNO);
        page.setPageSize(pageSize);
        page.initRecordBegin();
        agentOrder.setPage(page);
        List agentOrderList = agentPurchaseOrderService.listAgentOrder(agentOrder);
        url.append("&pageNO=");
        mv.addObject("agentOrderList",agentOrderList);
        mv.addObject("pageNO", pageNO);
        mv.addObject("pageSize", agentPurchaseOrderService.listAgentOrderCount(agentOrder));
        mv.addObject("url",url.toString());
        return mv;
    }

    /**
     * 同步订单状态
     * @param request
     * @param orderId
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/sync_efast_order/{orderId}")
    public ResultMsg syncEfastOrder(HttpServletRequest request,
                                      @PathVariable("orderId") String orderId) throws Exception {
        //efast的订单编号
        String efastOrderId = request.getParameter("efastOrderId");
        ResultMsg msg = new ResultMsg();

        if (!StringUtils.isNotEmpty(orderId)) {
            msg.setMessage("订单号为空!");
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }

        String id = efastOrderId;
        String EsastType = "1"; //0：百胜外部交易号；  1：百胜订单号
        //查询efast系统该订单的状态
        Map<String, Object> map = efastRentService.getEfastSendOrderInfo(id,EsastType);
        if (!(boolean) map.get("status")) {
            msg.setMessage(map.get("result").toString());
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }

        //获取订单信息
        AgentOrder agentOrder = new AgentOrder();
        agentOrder.setAgentOrderid(orderId);
        //查询代理商订单列表
        List<AgentOrder> orderList =  agentPurchaseOrderService.listSelectAgentOrder(agentOrder);
        if (orderList == null || orderList.size() == 0) {
            msg.setMessage("该订单不存在!");
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }
        agentOrder = orderList.get(0);

        AgentOrder order = new AgentOrder();
        order.setAgentOrderid(orderId);
        order.setAgentStatus(5);
        order.setAgentPostFirm((String) map.get("postFirm"));
        order.setAgentPostNum((String) map.get("postNum"));
        //修改代理商订单信息
        int flag = agentPurchaseOrderService.updateAgentPurchaseOrder(order);
        if (flag < 1){
            msg.setMessage("修改订单状态失败");
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }

        Member member = memberService.getMemberByUserOpenId(agentOrder.getAgentOpenId());
        if (member == null || 1 == member.getUserStatus() || 0 == member.getUserStatus()){   //未关注或者取消关注的，将发送手机短信
            logger.info("短信通知："+ agentOrder.getAgentOrderid() +" 用户的订单已发货");
            String phone = agentOrder.getAgentTel();
            codeService.informShipping(phone,INFORM_SHIPPING);
        }else if(2 == member.getUserStatus()){      //已关注的用户推送信息到公众号
            logger.info("公众号推送物流信息： "+ agentOrder.getAgentOpenId() +" 用户的订单已发货");
            //消息内容
            String data = ResultInfo.ORDERPACKAGETEMP;
            data = data.replaceFirst("firstValueOrder", ResultInfo.SHIPMENTMESSAGE)
                    .replaceFirst("orderIdValueOrder", orderId)
                    .replaceFirst("orderValuePackageId", SendMessageUtil.hashmap.get(map.get("postFirm")) + ":" + map.get("postNum"))
                    .replaceFirst("orderRemarkValue", ResultInfo.INTOSHOP);
            sendMessageUtil.sendTemplateMessageToOpenid(data, agentOrder.getAgentOpenId(), "", 2);
        }

        msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setStatus(true);
        return msg;
    }


    /**
     * 分页查询代理商
     * @param request
     * @param pageSize
     * @param pageNO
     * @return
     * @throws Exception
     */
    @RequestMapping("/select_agentInfo_list")
    public ModelAndView selectAgentInfoList(HttpServletRequest request,
                                              @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                              @RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO) throws Exception {
        AgentTooth agentTooth = new AgentTooth();
        ModelAndView mv = new ModelAndView("admin/agentInfo/agentInfoList");
        StringBuilder url = new StringBuilder("/admin/agentTooth/select_agentInfo_list?pageSize=");
        url.append(pageSize);
        String agentName = request.getParameter("agentName");
        String agentTel = request.getParameter("agentTel");
        String agentStatus = request.getParameter("agentStatus");
        if (StringUtils.isNotEmpty(agentName)) {
            agentTooth.setAgentName(agentName);
            url.append("&agentName=");
            url.append(agentName);
            mv.addObject("agentName",agentName);
        }
        if (StringUtils.isNotEmpty(agentTel)) {
            agentTooth.setAgentTel(agentTel);
            url.append("&agentTel=");
            url.append(agentTel);
            mv.addObject("agentTel",agentTel);
        }
        if (StringUtils.isNotEmpty(agentStatus)) {
            agentTooth.setAgentStatus(Integer.valueOf(agentStatus));
            url.append("&agentStatus=");
            url.append(agentStatus);
            mv.addObject("agentStatus",agentStatus);
        }

        PageBean page = new PageBean();
        page.setPageSize(pageSize);
        page.setPageNumber(pageNO);
        page.initRecordBegin();
        agentTooth.setPage(page);
        url.append("&pageNO=");
        //查询代理商配置金额集合
        List<AgentTooth> agentToothList = agentInfoService.selectAllAgentinfo(agentTooth);
        mv.addObject("agentToothList", agentToothList);
        mv.addObject("pageNO", pageNO);
        mv.addObject("pageSize", agentInfoService.selectAllAgentinfoCount(agentTooth));
        mv.addObject("url",url.toString());
        return mv;
    }

    /**
     * 修改代理商
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/update_agentInfo")
    public ResultMsg updateAgentInfo(HttpServletRequest request,AgentTooth agentTooth) throws Exception{
        ResultMsg msg = new ResultMsg();
        if (!StringUtils.isNotEmpty(agentTooth.getAgentId().toString())) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("修改代理商配置失败!");
        }
        AgentTooth agent = new AgentTooth();
        agent.setAgentTel(agentTooth.getAgentTel());
        agent.setAgentStatus(1);
        //根据条件查询代理商
        List<AgentTooth> agentList = agentInfoService.selectAllAgentinfo(agent);
        if (agentList != null && agentList.size() > 0) {
            //只可能存在一条数据
            agent = agentList.get(0);
            if (agentTooth.getAgentId().intValue() != agent.getAgentId()) {
                msg.setResultCode(ResultInfo.ERRORCODE);
                msg.setStatus(false);
                msg.setMessage("该电话号码已被注册，不能重复注册!");
                return msg;
            }
        }
        //修改代理商信息
        int num = agentInfoService.updateAgentTooth(agentTooth);
        if (num > 0) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
        }
        return msg;
    }

    /**
     * 进入修改代理商页面
     * @param request
     * @return
     */
    @RequestMapping("/_update_agentInfo")
    public ModelAndView _updateAgentInfo(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("admin/agentInfo/updateAgentInfo");
        String agentId = request.getParameter("agentId");
        if(agentId == null || agentId.equals("")){
            return null;
        }
        List<PlaceRoleInfo> roleInfoList = drpRoleInfoService.getDrpRoleList2();
        mv.addObject("roleInfoList",roleInfoList);

        AgentTooth agentTooth = new AgentTooth();
        agentTooth.setAgentId(Integer.valueOf(agentId));
        agentTooth = agentInfoService.getAgentTooth(agentTooth);
        mv.addObject("agentTooth",agentTooth);

        return mv;
    }

    /**
     * 进入新增代理商页面
     * @param request
     * @return
     */
    @RequestMapping("/_add_agentInfo")
    public ModelAndView _addAgentInfo(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("admin/agentInfo/addAgentInfo");
        List<PlaceRoleInfo> roleInfoList = drpRoleInfoService.getDrpRoleList2();
        mv.addObject("roleInfoList",roleInfoList);
        return mv;
    }

    /**
     * 新增代理商
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/add_agentInfo")
    public ResultMsg addAgentInfo(HttpServletRequest request,AgentTooth agentTooth) throws Exception{
        ResultMsg msg = new ResultMsg();
        if (!StringUtils.isNotEmpty(agentTooth.getAgentName())
                || !StringUtils.isNotEmpty(agentTooth.getAgentAddr())
                || !StringUtils.isNotEmpty(agentTooth.getAgentTel())
                || !StringUtils.isNotEmpty(String.valueOf(agentTooth.getAgentRoleId()))
                || !StringUtils.isNotEmpty(String.valueOf(agentTooth.getAgentStatus()))) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("修改代理商配置失败!");
            return msg;
        }

        AgentTooth agent = new AgentTooth();
        agent.setAgentTel(agentTooth.getAgentTel());
        agent.setAgentStatus(1);
        //根据条件查询代理商
        List<AgentTooth> agentList = agentInfoService.selectAllAgentinfo(agent);
        if (agentList != null && agentList.size() > 0) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该电话号码已被注册，不能重复注册!");
            return msg;
        }
        //add代理商信息
        int num = agentInfoService.addAgentinfo(agentTooth);
        if (num > 0) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
        }
        return msg;
    }
}
