package com.sifang.modules.setting.web;

import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.setting.dao.CrmPlatformEmployeeRoleDao;
import com.sifang.modules.setting.entity.CrmPlatformEmployeeRole;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmPlatformEmpDao;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectSettingDao;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderEmployeDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlatformEmployee;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTraderEmploye;
import com.sifang.modules.sunshine.SystemSetting.service.DepartmentSettingService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderEmployeService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderPcdService;
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.entity.ZtreeNode;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.Objects;

@Controller
@RequestMapping(value = "${adminPath}/member")
public class MemberController extends BaseController {

    @Autowired
    MemberService memberService;
    @Autowired
    private CrmPlatformEmployeeRoleDao crmPlatformEmployeeRoleDao;

    @Autowired
    private TraderService traderService;

    @Autowired
    AddressService addressService;

    @Autowired
    DepartmentSettingService departmentSettingService;

    @Autowired
    private TraderEmployeDao traderEmployeDao;

    @Autowired
    private TraderEmployeService traderEmployeeService;

    @Autowired
    private TraderPcdService traderPcdService;

    @Autowired
    private CrmPlatformEmpDao crmPlatformEmpDao;

    @Autowired
    private ProjectSettingDao projectSettingDao;

    @RequestMapping(value = "test")
    @ResponseBody
    public String test(HttpServletRequest request, Model model) {
        memberService.test();
        return "modules/base/login";
    }

    //平台人员管理首页
    @RequestMapping(value = "index")
    public String index(HttpServletRequest request, Model model){
        List<Record> roles = memberService.getMemberRoles();
        model.addAttribute("roles", roles);
        return "modules/setting/member/index";
    }

    //权限管理首页
    @RequestMapping(value = "roleIndex")
    public String roleIndex(HttpServletRequest request, Model model){
        User user = UserUtils.getUser();
        model.addAttribute("user",user);
        return "modules/setting/member/roleIndex";
    }

   //平台角色管理首页
    @RequestMapping(value="setRole")
    public String setRole(HttpServletRequest request,Model model){
        User user = UserUtils.getUser();
        model.addAttribute("user",user);
        return "modules/setting/member/setRoleIndex";
    }

    /**
     * 设置数据权限
    */
    @RequestMapping(value="rightsForm")
    public String rightsForm(HttpServletRequest reques,Model model){
        String id = reques.getParameter("id");
        model.addAttribute("id",id);
        String type=reques.getParameter("type");  //type=1,那么是代理商员工 ，否则是平台员工
        model.addAttribute("type",type);
        if("1".equals(type)){
            CrmTraderEmploye emp = traderEmployeeService.getById(id);
            model.addAttribute("dataAuthority","2".equals(emp.getDataAuthority())?"2":"1");
        }else {
            Record rd = memberService.getPlatFormEmployeById(id);
            model.addAttribute("rds",rd);
            if(StringUtil.isNotEmpty(rd.getStr("provices"))){
                List<Record> list = AddressUtils.getCityListByProName(rd.getStr("provices"));
                model.addAttribute("citys",list);
            }

            List<Record> province = addressService.getProvinces();//获取所有的省
            model.addAttribute("province",province);
            CrmPlatformEmployee crmPlatformEmployee = crmPlatformEmpDao.get(id);
            //获取区域下的项目
            model.addAttribute("project",memberService.getProjectLists());
            model.addAttribute("projectList", projectSettingDao.getProjectInfoByArea(crmPlatformEmployee.getProvices()));
            //获取区域下的所有代理商
            List<Record> listtrader =  traderService.findTraderListByProvince(crmPlatformEmployee.getProvices());
            model.addAttribute("listtrader",listtrader);
        }
        return "modules/setting/member/rightsForm";
    }

    /**
     * 保存角色数据权限
    */
    @ResponseBody
    @RequestMapping("saveRights")
    public Result saveRights(HttpServletRequest request){
        Result result = new Result();
        String id = request.getParameter("id");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String project = request.getParameter("project");
        String traderIds = request.getParameter("traderIds");

        String code = memberService.saveEditRoleRights(id,province,city,project,traderIds);
        result.setCode(code);
        return result;
    }



    //获取平台角色管理的列表信息
    @ResponseBody
    @RequestMapping(value="getRoleList")
    public String getRoleData(HttpServletRequest request){
        Map<String, String> params = getParams(request);
        LayuiPage page = new LayuiPage(request);
        List<Record> list=memberService.getRoleList(page);
        page.setData(list);
        page.setCount(memberService.getCount());
        return page.renderJson();
    }
    //平台添加角色
     @ResponseBody
     @RequestMapping(value="addPlatformRole")
     public String addPlatformRole(HttpServletRequest request){
         String jsonData = request.getParameter("jsonData");
         try{
           return  memberService.addPlateformRole(jsonData);
         }catch (Exception e){
             e.printStackTrace();
             return "202";
         }
     }

    //平台删除角色
    @ResponseBody
    @RequestMapping(value="deleteRole")
    public String  deleteRole(HttpServletRequest request){
        String roleId = request.getParameter("id");
        String traderId = request.getParameter("traderId");
        Boolean flag;
        if (Objects.equals("1", traderId)) {
            flag = crmPlatformEmployeeRoleDao.checkIfHasRole(roleId);
        } else {
            flag = traderEmployeDao.checkIfHasRole(roleId, traderId);
        }
        try {
            if (flag) {
                crmPlatformEmployeeRoleDao.deleteById(roleId);
                return "200";
            } else {
                return "202"; // 该角色下有员工
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "405";
        }
    }
//到平台修改角色页面
  @RequestMapping(value="editPlatemRole")
  public String editPlatemRole(HttpServletRequest request,Model model){
      String roleId=request.getParameter("id");
      CrmPlatformEmployeeRole crmPlatformEmployeeRole=crmPlatformEmployeeRoleDao.get(roleId);
       model.addAttribute("role",crmPlatformEmployeeRole);
        return "modules/setting/member/editRole";
  }
//保存修改的角色信息
    @ResponseBody
    @RequestMapping(value="saveEditPlatformRole")
    public String saveEditPlatformRole(HttpServletRequest request){
        String roleId=request.getParameter("roleId");
        String name=request.getParameter("name");
        String sort=request.getParameter("sort");
      return memberService.saveEditPlatformRole(roleId,name,sort);
    }

 //到添加角色页面
    @RequestMapping(value="addPlatemRole")
    public String addPlatemRole(HttpServletRequest request){
        return "modules/setting/member/addRole";
    }


    //添加员工
    @RequestMapping(value = "memberForm")
    public String memberForm(HttpServletRequest request, Model model){
      /*  String id = request.getParameter("id");
        Record memberRd = memberService.getMemberById(id);
        model.addAttribute("member", memberRd);*/
        List<Record> roles = memberService.getMemberRoles();
        model.addAttribute("roles", roles);
        //获取所有省份
       /* List<Record> pros = AddressUtils.getProvinces();
        model.addAttribute("provinces", pros);*/
        List<Record> deplist = departmentSettingService.getAllTopDept();
        model.addAttribute("deplist", deplist);
        return "modules/setting/member/form";
    }

    //修改员工信息
    @RequestMapping(value = "memberFormNew")
    public String memberFormNew(HttpServletRequest request, Model model){
        String id = request.getParameter("id");
        Record memberRd = memberService.getMemberById(id);
        model.addAttribute("member", memberRd);
        List<Record> roles = memberService.getMemberRoles();
        model.addAttribute("roles", roles);
        return "modules/setting/member/formNew";
    }
   //平台人员管理页面数据
    @RequestMapping(value = "getMemberData")
    @ResponseBody
    public String getMemberData(HttpServletRequest request){
        Map<String, String> params = getParams(request);
        LayuiPage page = new LayuiPage(request);
        memberService.getMembers(params,page);
        return page.renderJson();
    }

    //获取角色信息
    @RequestMapping(value = "getRoles")
    @ResponseBody
    public String getRoles(HttpServletRequest request, Model model) {
        //HashMap
        List<Record> roles = memberService.getMemberRoles();
        return new Gson().toJson(roles);
    }

    //获取角色对应的菜单
    @RequestMapping(value = "getMenus")
    @ResponseBody
    public String getMenus(HttpServletRequest request, Model model) {
        String roleId = request.getParameter("roleId");
        List<ZtreeNode> nodes = memberService.getMenus(roleId);
        return new Gson().toJson(nodes);
    }

    @RequestMapping(value = "getMenusYw")
    @ResponseBody
    public String getMenusYw(HttpServletRequest request, Model model) {
        String roleId = request.getParameter("roleId");
        List<ZtreeNode> nodes = memberService.getMenusYw(roleId);
        return new Gson().toJson(nodes);
    }


    @RequestMapping(value = "addMemberRole")
    @ResponseBody
    public String addMemberRole(HttpServletRequest request, Model model) {
        String name = request.getParameter("name");
        String ret = memberService.addMemberRole(name);
        return ret;
    }

    @RequestMapping(value = "saveMemberRoleMenus")
    @ResponseBody
    public String saveMemberRoleMenus(HttpServletRequest request, Model model) {
        String roleId = request.getParameter("roleId");
        String roleName = request.getParameter("roleName");
        String permission = request.getParameter("permission");
        String permissionsyw = request.getParameter("permissionsyw");
        String ret = memberService.saveMemberRoleMenus(roleId, roleName, permission,permissionsyw);
        return ret;
    }

    @RequestMapping(value = "saveMember")
    @ResponseBody
    public String addMember(HttpServletRequest request){
        Map<String, String> params = getParams(request);
        String ret = memberService.saveMember(params);
        return ret;
    }

    @RequestMapping(value = "delMember")
    @ResponseBody
    public String delMember(HttpServletRequest request){
        Map<String, String> params = getParams(request);
        String ret = memberService.delMember(params);
        return ret;
    }

    @RequestMapping(value = "delRole")
    @ResponseBody
    public String delRole(HttpServletRequest request){
        String id = request.getParameter("id");
        String ret = memberService.delRole(id);
        return ret;
    }

    //点击form页面的保存按钮，提交前验证
    @RequestMapping(value = "beforeSave")
    @ResponseBody
    public String beforeSave(HttpServletRequest request){
        Map<String, String> params = getParams(request);
        String ret = memberService.beforeSave(params);
        return ret;
    }

    @RequestMapping(value = "findProjectList")
    @ResponseBody
    public Object findProjectList(){
        return memberService.getProjectLists();
    }

}
