package com.dgtly.wxportal.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import com.dgtly.common.annotation.ApiPassToken;
import com.dgtly.common.annotation.Log;
import com.dgtly.common.core.controller.ApiBaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.domain.ParameterObject;
import com.dgtly.common.core.domain.Ztree;
import com.dgtly.common.enums.BusinessType;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.system.domain.*;
import com.dgtly.system.service.*;
import com.dgtly.wxportal.domain.HelpCenter;
import com.dgtly.wxportal.domain.WxBanner;
import com.dgtly.wxportal.domain.WxMagnet;
import com.dgtly.wxportal.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;




@Slf4j
@Api(tags = "微信门户相关接口")
@RestController
@RequestMapping("/wxportal")
@ApiPassToken
public class WxPortalController extends ApiBaseController {

    @Autowired
    private IWxMagnetService wxMagnetService;

    @Autowired
    private IWxBannerService wxBannerService;
    @Autowired
    private ESignService eSignService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysUserExtService userExtService;
    @Autowired
    private ICustomersExtService customersExtService;
    @Autowired
    private IEsignPersonRealnVerifyService personRealnVerifyService;
    @Autowired
    private IEsignOrganRealVerifyService organRealVerifyService;
    @Autowired
    private IHelpCenterService helpCenterService;
    @Autowired
    private IAssRelcustomerinfoService assRelcustomerinfoService;
    @Autowired
    private ISysMagnetLogService sysMagnetLogService;
    @Autowired
    private ISysRidingLanternService sysRidingLanternService;
    @Autowired
    private ISysUserOrderAuthorService sysUserOrderAuthorService;
    @Autowired
    private ISysUserCustomerAuthorizationService authorizationService;
    @Autowired
    private ISysUserExtService sysUserExtService;

    @Autowired
    private ISysUserShopExtService sysUserShopExtService;


    @Autowired
    JdbcTemplate jdbcTemplate;
    @ApiOperation(value = "微信门户首页",notes = "参数：{userId:1}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/portalData")
    public Object getMagent(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("userId,agent,userType");
        String loginType="";
        List<Map<String, Object>> loginTypeList = jdbcTemplate.queryForList("select dict_label shopType,dict_value shopTypeValue  from sys_dict_data where  dict_type='system_login_type'  and dict_label=?  ",obj.getString("agent"));
        if(loginTypeList.size()!=0){
            loginType= loginTypeList.get(0).get("shopTypeValue").toString();
        }

        WxBanner wxBanner = new WxBanner();
        List<WxMagnet> wxMagnetList =  wxMagnetService.selectMagnetByUserId(obj.getString("userId"), obj.getString("cw"), obj.getString("salesLevel"),loginType);
        //筛选掉没有权限的磁贴
        String userType = obj.getString("userType");
        wxMagnetList = wxMagnetList.stream()
                .filter(magnet -> userType.equals(magnet.getUserType()))
                .collect(Collectors.toList());
        List<WxBanner> wxBannerList = wxBannerService.selectWxBannerList(wxBanner);
        return AjaxResult.success().putKV("magnets",wxMagnetList).putKV("banners",wxBannerList);
    }

    @ApiOperation(value = "磁贴下标记权限磁贴",notes = "参数：{userId,magnetName}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/wxMagnetRoleByUserId")
    public Object getWxMagnetRoleByUserId(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("userId,magnetName");
        String magnetName = obj.getString("magnetName");
        Long userId = obj.getLong("userId");
        List<WxMagnet> wxMagnetList =  wxMagnetService.selectWxMagnetRoleByUserId(userId,magnetName);
        if(wxMagnetList !=null && wxMagnetList.size()>0){
            return AjaxResult.success().putKV("magnets",wxMagnetList);
        }else{
            return AjaxResult.noData();
        }
    }

    @ApiOperation(value = "通知公告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/ridingLantern")
    public Object getRidingLantern(){
        ParameterObject obj = getParameterObject();
        Long userId = Long.valueOf(obj.getString("userId"));
        List<String> userTypeList = new ArrayList<>();
        Set<String> userTypeSet = new HashSet<>();
        SysUserExt sysUserExt = sysUserExtService.selectSysUserExtById(userId);
        if (sysUserExt != null){
            String salesLevel = sysUserExt.getSalesLevel();
            if(("customer_level").equals(salesLevel)||("reseller_level").equals(salesLevel) ){
                userTypeList.add("1");
            }else{
                userTypeList.add("0");
            }
        }
        List<SysUserShopExt>  sysUserShopExt = sysUserShopExtService.selectSysUserShopExtById(obj.getString("userId"));
        if (sysUserShopExt != null && sysUserShopExt.size() > 0){
            for (SysUserShopExt shopExt : sysUserShopExt){
                userTypeSet.add(shopExt.getIsShopType());
            }
            for (String userType : userTypeSet){
                if ("0".equals(userType)){
                    userTypeList.add("2");
                }else {
                    userTypeList.add("3");
                }
            }
        }
        log.info("该用户的userType为:{}",userTypeList);
        List<SysRidingLantern> lanternList = sysRidingLanternService.selectLanternList();
        List<SysRidingLantern> lanternListhow=new ArrayList<>();
        if (lanternList != null && lanternList.size() > 0) {
            lanternList.forEach(lantern->{
                //如果userType为空,则添加通知,
                if (StringUtils.isEmpty(lantern.getUserType())){
                    lantern.setUserType("");
                    lanternListhow.add(lantern);
                }else {
                    String[] split = lantern.getUserType().split(",");
                    for (String userTypeStr : userTypeList){
                        boolean exists = Arrays.stream(split)
                                .anyMatch(str -> str.equals(userTypeStr));
                        if (exists){
                            if (!lanternListhow.contains(lantern)){
                                lanternListhow.add(lantern);
                            }
                        }
                    }
                }
            });
            return AjaxResult.success().putKV("lanterns", lanternListhow);
        } else {
            return AjaxResult.error("暂无通知");
        }
    }

    /**
     * 新增保存磁铁日志
     */
    @ApiOperation(value = "新增磁铁访问日志",notes = "参数：{userId,userName,orgCode,orgName,level,magnetName,whatEnd}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/magnetLogAdd")
    @ResponseBody
    public AjaxResult magnetLogAdd()
    {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId,userName,level,magnetName,whatEnd");
        SysMagnetLog sysMagnetLog = new SysMagnetLog();
        sysMagnetLog.setUserId(obj.getLong("userId"));
        sysMagnetLog.setUserName(obj.getString("userName"));
        sysMagnetLog.setOrgCode(obj.getString("orgCode"));
        sysMagnetLog.setOrgName(obj.getString("orgName"));
        sysMagnetLog.setLevel(obj.getString("level"));
        sysMagnetLog.setMagnetName(obj.getString("magnetName"));
        sysMagnetLog.setWhatEnd(obj.getLong("whatEnd"));
        sysMagnetLog.setSalesCompanyName(obj.getString("salesCompanyName") == null ? "" : obj.getString("salesCompanyName"));
        sysMagnetLog.setSalesOfficeName(obj.getString("salesOfficeName") == null ? "" : obj.getString("salesOfficeName"));
        sysMagnetLog.setSubOfficeName(obj.getString("subOfficeName") == null ? "" : obj.getString("subOfficeName"));
        sysMagnetLog.setShopCode(obj.getString("shopCode") == null ? "" : obj.getString("shopCode"));
        return toAjax(sysMagnetLogService.insertSysMagnetLog(sysMagnetLog));
    }

    @ApiOperation(value = "查询经销商人员列表", notes = "参数：{'userId':'XXXXXXX'}" +
            "\n（userId：用户id）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("getDistributorList")
    public Object getDistributorList() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId");
        String userId = obj.getString("userId");
        SysUserExt userExt = userExtService.selectSysUserCustomerExtById(Long.parseLong(userId));
        if (userExt!=null){
            List<SysUser> userList = userService.selectUserByOrgCode(userExt.getOrgCode());
            return AjaxResult.success().putKV("userList",userList);
        }else{
            return AjaxResult.error("用户不存在");
        }
    }

    @ApiOperation(value = "查询多经销商列表", notes = "参数：{'userId':'XXXXXXX'}" +
            "\n（userId：用户id）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("getSysUserExtList")
    public Object getSysUserExtList() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId");
        String userId = obj.getString("userId");
        String customerCode = obj.getString("customerCode");
        Map map = new HashMap(5);
        SysUser sysUser = userService.selectUserById(Long.parseLong(userId));
        /*根据org_code查询多个经销商列表*/
        List<SysUserExt> sysUserExtList = new ArrayList<>();
        List<AssRelcustomerinfo>  assRelcustomerinfoList= assRelcustomerinfoService.selectRelcustomerinfoListByorgCode(customerCode,sysUser.getUserId().toString());
        if (assRelcustomerinfoList.size()>0){
            for (AssRelcustomerinfo ar:assRelcustomerinfoList) {
                SysUserExt sysUserExt = new SysUserExt();
                sysUserExt.setUserId(sysUser.getSysUserExt().getUserId());
                sysUserExt.setOrgCode(ar.getMainkunnr());
                sysUserExt.setOrgName(ar.getMainname1());
                sysUserExt.setSalesLevel(sysUser.getSysUserExt().getSalesLevel());
                sysUserExt.setBossEmployeeId(sysUser.getSysUserExt().getBossEmployeeId());
                sysUserExt.setBossName(sysUser.getSysUserExt().getBossName());
                sysUserExt.setSapEmployeeId(sysUser.getSysUserExt().getSapEmployeeId());
                sysUserExt.setCustomerCode(sysUser.getSysUserExt().getCustomerCode());
                sysUserExt.setIsCustomerManager(sysUser.getSysUserExt().getIsCustomerManager());
                sysUserExt.setPostCode(sysUser.getSysUserExt().getPostCode());
                sysUserExt.setPostName(sysUser.getSysUserExt().getPostName());
                sysUserExtList.add(sysUserExt);
            }

            for (AssRelcustomerinfo ar:assRelcustomerinfoList) {
                SysUserExt sysUserExt = new SysUserExt();
                sysUserExt.setUserId(sysUser.getSysUserExt().getUserId());
                sysUserExt.setOrgCode(ar.getKunnr());
                sysUserExt.setOrgName(ar.getName1());
                sysUserExt.setSalesLevel(sysUser.getSysUserExt().getSalesLevel());
                sysUserExt.setBossEmployeeId(sysUser.getSysUserExt().getBossEmployeeId());
                sysUserExt.setBossName(sysUser.getSysUserExt().getBossName());
                sysUserExt.setSapEmployeeId(sysUser.getSysUserExt().getSapEmployeeId());
                sysUserExt.setCustomerCode(sysUser.getSysUserExt().getCustomerCode());
                sysUserExt.setIsCustomerManager(sysUser.getSysUserExt().getIsCustomerManager());
                sysUserExt.setPostCode(sysUser.getSysUserExt().getPostCode());
                sysUserExt.setPostName(sysUser.getSysUserExt().getPostName());
                sysUserExtList.add(sysUserExt);
            }

            /*
            SysUserExt sysUserExt = new SysUserExt();
            sysUserExt.setUserId(sysUser.getSysUserExt().getUserId());
            sysUserExt.setOrgCode(assRelcustomerinfoList.get(0).getMainkunnr());
            sysUserExt.setOrgName(assRelcustomerinfoList.get(0).getMainname1());
            sysUserExt.setSalesLevel(sysUser.getSysUserExt().getSalesLevel());
            sysUserExt.setBossEmployeeId(sysUser.getSysUserExt().getBossEmployeeId());
            sysUserExt.setBossName(sysUser.getSysUserExt().getBossName());
            sysUserExt.setSapEmployeeId(sysUser.getSysUserExt().getSapEmployeeId());
            sysUserExt.setCustomerCode(sysUser.getSysUserExt().getCustomerCode());
            sysUserExt.setIsCustomerManager(sysUser.getSysUserExt().getIsCustomerManager());
            sysUserExt.setPostCode(sysUser.getSysUserExt().getPostCode());
            sysUserExt.setPostName(sysUser.getSysUserExt().getPostName());
            sysUserExtList.add(sysUserExt);*/
        }
        ArrayList<SysUserExt> resultList = sysUserExtList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SysUserExt::getOrgCode))), ArrayList::new));

        sysUser.setSysUserExtLsit(resultList);
        if (sysUser!=null){
//            map.put("user",sysUser);
            map.put("sysUserExtList",resultList);
            return AjaxResult.success(map);
        }else{
            return AjaxResult.error("用户不存在");
        }
    }

    @ApiOperation(value = "切换经销商", notes = "参数：{'userId':'XXXXXXX','orgCode':'XXXXXXX','orgName':'XXXXXXX'}" +
            "\n（userId：用户id）" +
            "\n（orgCode：经销商code）" +
            "\n（orgName：经销商名称）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("switchCustomer")
    public Object switchCustomer() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId,orgCode,orgName");
        String userId = obj.getString("userId");
        String orgCode = obj.getString("orgCode");
        String orgName = obj.getString("orgName");

        //check
        SysUser sysUser = userService.selectUserById(Long.parseLong(userId));
        if (sysUser != null && "customer_level".equals(sysUser.getSysUserExt().getSalesLevel())) {
            int row = userExtService.switchCustomer(userId, orgCode, orgName);
            if (row > 0) {
                //通过userId查询用户信息
                SysUser user = userService.selectUserById(Long.valueOf(userId));
                List<Ztree>  author = sysUserOrderAuthorService.userAuthorTreeDataFmt(user.getUserId());
                if (author.size() > 0 && author.get(0).getChildren().size() > 1) {
                    user.setAuthorType("TUC");
                } else if (author.size() > 0 && author.get(0).getChildren().size() == 1) {//设置BUSINESS_UNIT
                    user.setAuthorType(author.get(0).getChildren().get(0).getCode());
                }else{
                    user.setAuthorType("DIY");//默认diy
                }
                user.setAuthor(author);
                return AjaxResult.success().putKV("sysUser", user);
            } else {
                return AjaxResult.error("经销商切换失败");
            }
        } else {
            return AjaxResult.error(301,"非经销商级别无需切换");
        }
    }

    @ApiOperation(value = "设置/取消是否为收货人", notes = "参数：{'userId':'XXXXXXX','IsConsignee':'1'}" +
            "\n（userId：用户id" +
            "\n IsConsignee:是否收货人（0否1是））")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("updateOrgUser")
    public Object updateOrgUser() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId,IsConsignee");
        String userId = obj.getString("userId");
        String IsConsignee = obj.getString("IsConsignee");
        String customerCode = obj.getString("customerCode");
        int i=0;
        SysUserCustomerAuthorization authorization = authorizationService.selectAuthorizationByUserIdAndCustomerCode(customerCode,userId);
        if(authorization !=null){
            authorization.setIsConsignee(IsConsignee);
            i= authorizationService.updateAuthorizationByCustomerCodeAndUserId(authorization);
        }else{
            SysUserCustomerAuthorization author = new SysUserCustomerAuthorization();
            author.setUserId(Long.valueOf(userId));
            author.setCustomerCode(customerCode);
            author.setIsConsignee(IsConsignee);
            i =authorizationService.insertSysUserCustomerAuthorization(author);
        }
        if (i>0){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @ApiOperation(value = "设置/取消自主下单授权", notes = "参数：{'userId':'XXXXXXX','isIndependently':'1'}" +
            "\n（userId：用户id" +
            "\n isIndependently:是否自主下单授权（0否1是））")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("updateUserByIsIndependently")
    public Object updateUserByIsIndependently() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId,isIndependently,customerCode");
        String userId = obj.getString("userId");
        String IsIndependently = obj.getString("isIndependently");
        String customerCode = obj.getString("customerCode");
        int i=0;
        SysUserCustomerAuthorization authorization = authorizationService.selectAuthorizationByUserIdAndCustomerCode(customerCode,userId);
        if(authorization !=null){
            authorization.setIsIndependently(IsIndependently);
             i= authorizationService.updateAuthorizationByCustomerCodeAndUserId(authorization);
        }else{
            SysUserCustomerAuthorization author = new SysUserCustomerAuthorization();
            author.setUserId(Long.valueOf(userId));
            author.setCustomerCode(customerCode);
            author.setIsIndependently(IsIndependently);
             i =authorizationService.insertSysUserCustomerAuthorization(author);
        }
        if (i>0){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }


    @ApiOperation(value = "设置/取消自提授权", notes = "参数：{'userId':'XXXXXXX','isSelfDelivery':'1'}" +
            "\n（userId：用户id" +
            "\n isSelfDelivery:是否自提授权（0否1是））")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("updateUserByIsSelfDelivery")
    public Object updateUserByIsSelfDelivery() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId,isSelfDelivery");
        String userId = obj.getString("userId");
        String IsSelfDelivery = obj.getString("isSelfDelivery");
        String customerCode = obj.getString("customerCode");
        int i=0;
        SysUserCustomerAuthorization authorization = authorizationService.selectAuthorizationByUserIdAndCustomerCode(customerCode,userId);
        if(authorization !=null){
            authorization.setIsSelfDelivery(IsSelfDelivery);
            i= authorizationService.updateAuthorizationByCustomerCodeAndUserId(authorization);
        }else{
            SysUserCustomerAuthorization author = new SysUserCustomerAuthorization();
            author.setUserId(Long.valueOf(userId));
            author.setCustomerCode(customerCode);
            author.setIsSelfDelivery(IsSelfDelivery);
            i =authorizationService.insertSysUserCustomerAuthorization(author);
        }

        if (i>0){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @ApiOperation(value = "帮助中心",notes = "参数：{userId:1}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/helpCenter")
    public Object getHelpCenter() {
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("userId");
        HelpCenter helpCenter = new HelpCenter();
        List<HelpCenter> list = helpCenterService.selectHelpCenterList(helpCenter);
        return AjaxResult.success().putKV("helpList",list);
    }


    @PostMapping("/getHomeIconInfo")
    public AjaxResult getHoemIconCongif() throws IOException {
        Map<String,Object> iconInfo= wxMagnetService.selectHomeIconInfoById();
        return  AjaxResult.success(iconInfo);
    }
}
