package org.jeecg.modules.adweb.userCountry.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.adweb.enquiry.constant.EnquiryDistributeTypeConstant;
import org.jeecg.modules.adweb.enquiry.entity.AdwebEnquiry;
import org.jeecg.modules.adweb.enquiry.service.IAdwebEnquiryService;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.jeecg.modules.adweb.system.service.SysAdwebApi;
import org.jeecg.modules.adweb.userCountry.dto.DistributeCountryParam;
import org.jeecg.modules.adweb.userCountry.dto.SubUser;
import org.jeecg.modules.adweb.userCountry.dto.TreeOption;
import org.jeecg.modules.adweb.userCountry.entity.AdwebCountry;
import org.jeecg.modules.adweb.userCountry.entity.AdwebUserCountry;
import org.jeecg.modules.adweb.userCountry.mapper.AdwebUserCountryMapper;
import org.jeecg.modules.adweb.userCountry.service.IAdwebCountryService;
import org.jeecg.modules.adweb.userCountry.service.IAdwebUserCountryService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @Description: adweb_user_country
 * @Author: jeecg-boot
 * @Date: 2022-08-19
 * @Version: V1.0
 */
@Tag(name = "adweb_user_country")
@RestController
@RequestMapping("/usercountry")
@Slf4j
public class AdwebUserCountryController
        extends JeecgController<AdwebUserCountry, IAdwebUserCountryService> {

    @Resource private IAdwebUserCountryService adwebUserCountryService;

    @Resource private IAdwebSiteService adwebSiteService;

    @Resource private AdwebUserCountryMapper adwebUserCountryMapper;

    @Resource private IAdwebCountryService admpCountryService;

    @Resource private IAdwebEnquiryService adwebEnquiryService;

    @Resource private SysAdwebApi sysAdwebApi;

    @Resource private ISysUserService sysUserService;

    /**
     * 分页列表查询
     *
     * @param adwebUserCountry
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "adweb_user_country-分页列表查询")
    @Operation(summary = "adweb_user_country-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(
            AdwebUserCountry adwebUserCountry,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        QueryWrapper<AdwebUserCountry> queryWrapper =
                QueryGenerator.initQueryWrapper(adwebUserCountry, req.getParameterMap());
        Page<AdwebUserCountry> page = new Page<AdwebUserCountry>(pageNo, pageSize);
        IPage<AdwebUserCountry> pageList = adwebUserCountryService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /** 查询未分配地区 */
    @GetMapping(value = "/undistribute")
    public Result<?> undistribute() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<AdwebUserCountry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdwebUserCountry::getMasterUid, loginUser.getId());
        queryWrapper.eq(AdwebUserCountry::getStatus, 1);
        List<AdwebUserCountry> userCountries = adwebUserCountryService.list(queryWrapper);
        List<AdwebCountry> countries = null;
        if (CollectionUtils.isEmpty(userCountries)) {}

        return Result.OK();
    }

    /** 获取子账户列表 */
    @AutoLog(value = "询盘管理-询盘分配-子账户列表")
    @GetMapping(value = "/subAccounts")
    public Result<?> subAccounts(
            @RequestParam(name = "siteId") Integer siteId,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "15") Integer pageSize) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<Integer> siteIds = adwebSiteService.getAllSiteIdByParentId(siteId);
        Page<SubUser> page = new Page<>(pageNo, pageSize);
        IPage<SubUser> pageList =
                adwebUserCountryMapper.getSubUserList(page, loginUser.getId(), siteIds);
        LambdaQueryWrapper<AdwebEnquiry> enquiryQueryWrapper = new LambdaQueryWrapper<>();
        enquiryQueryWrapper.eq(AdwebEnquiry::getStatus, 1);
        enquiryQueryWrapper.in(AdwebEnquiry::getSiteId, siteIds);
        enquiryQueryWrapper.eq(AdwebEnquiry::getPrincipalType, 1);
        int count = (int) adwebEnquiryService.count(enquiryQueryWrapper);
        List<SubUser> list = pageList.getRecords();
        SubUser subUser = new SubUser();
        subUser.setId("-1");
        subUser.setUsername("已手动分配跟进人的询盘");
        subUser.setRealname("已手动分配跟进人的询盘");
        subUser.setCountryNum(-1);
        subUser.setEnquiryNum(count);
        list.add(subUser);
        return Result.OK(pageList);
    }

    /** 获取子账户列表 */
    @GetMapping(value = "/subAccounts/options")
    public Result<?> subAccounts2(Integer siteId, String siteCode) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取主账户uid
        String uid;
        if (sysAdwebApi.isAdmin() || sysAdwebApi.isChannelAdmin()) {
            AdwebSite site;
            if (siteId != null) {
                site = adwebSiteService.getById(siteId);
            } else {
                site =
                        adwebSiteService.getOne(
                                new LambdaQueryWrapper<AdwebSite>()
                                        .eq(AdwebSite::getCode, siteCode));
            }
            if (site == null) {
                return Result.OK(new ArrayList<SubUser>());
            }
            uid = site.getUid();
        } else if (sysAdwebApi.isAdwebVip()) {
            uid = loginUser.getId();
        } else {
            return Result.OK(new ArrayList<SubUser>());
        }

        // 获取子账户列表
        List<SubUser> list = adwebUserCountryMapper.getSubUserOptions(uid);

        // 如果子账户不为空，将主账户也加进去作为选项
        if (CollectionUtils.isNotEmpty(list)) {
            SysUser masterAccount = sysUserService.getById(uid);
            SubUser user = new SubUser();
            user.setId(masterAccount.getId());
            user.setUsername(masterAccount.getRealname());
            list.add(0, user);
        }

        return Result.OK(list);
    }

    /** 获取子账户负责的国家 */
    @GetMapping(value = "/country/charge")
    public Result<?> chargeCountry(@RequestParam String id, @RequestParam Integer siteId) {
        LambdaQueryWrapper<AdwebUserCountry> userCountryQueryWrapper = new LambdaQueryWrapper<>();
        userCountryQueryWrapper.eq(AdwebUserCountry::getUid, id);
        userCountryQueryWrapper.eq(AdwebUserCountry::getSiteId, siteId);
        userCountryQueryWrapper.eq(AdwebUserCountry::getStatus, 1);
        List<AdwebUserCountry> userCountries =
                adwebUserCountryService.list(userCountryQueryWrapper);
        if (CollectionUtils.isEmpty(userCountries)) {
            return Result.OK();
        }

        List<Integer> countryIds = new ArrayList<>();
        for (AdwebUserCountry userCountry : userCountries) {
            countryIds.add(userCountry.getCountryId());
        }

        LambdaQueryWrapper<AdwebCountry> countryQueryWrapper = new LambdaQueryWrapper<>();
        countryQueryWrapper.in(AdwebCountry::getGeonameId, countryIds);
        List<AdwebCountry> countries = admpCountryService.list(countryQueryWrapper);
        if (CollectionUtils.isEmpty(countries)) {
            return Result.OK();
        }

        // 将国家按大洲分组，然后组装成树结构
        Map<String, List<AdwebCountry>> map = new HashMap<>();
        for (AdwebCountry country : countries) {
            String continentCode = country.getContinentCode();
            List<AdwebCountry> countryList =
                    map.computeIfAbsent(continentCode, k -> new ArrayList<>());
            countryList.add(country);
        }

        List<TreeOption> options = new ArrayList<>();
        for (List<AdwebCountry> countryList : map.values()) {
            TreeOption parentOption = new TreeOption();
            parentOption.setKey(countryList.get(0).getContinentCode());
            parentOption.setValue(countryList.get(0).getContinentCode());
            parentOption.setTitle(countryList.get(0).getContinentName());
            List<TreeOption> children = new ArrayList<>();
            for (AdwebCountry country : countryList) {
                TreeOption option = new TreeOption();
                option.setKey(country.getGeonameId());
                option.setValue(country.getGeonameId());
                option.setTitle(country.getCountryName());
                children.add(option);
            }
            parentOption.setChildren(children);
            options.add(parentOption);
        }

        return Result.OK(options);
    }

    /** 获取未分配的国家 */
    @GetMapping(value = "/country/uncontribute")
    public Result<?> uncontributeCountry(Integer siteId) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<AdwebUserCountry> userCountryQueryWrapper = new LambdaQueryWrapper<>();
        userCountryQueryWrapper.eq(AdwebUserCountry::getMasterUid, loginUser.getId());
        userCountryQueryWrapper.eq(AdwebUserCountry::getStatus, 1);
        userCountryQueryWrapper.eq(AdwebUserCountry::getSiteId, siteId);
        List<AdwebUserCountry> userCountries =
                adwebUserCountryService.list(userCountryQueryWrapper);

        List<AdwebCountry> countries;
        if (CollectionUtils.isEmpty(userCountries)) {
            countries = admpCountryService.list();
        } else {
            List<Integer> countryIds = new ArrayList<>();
            for (AdwebUserCountry userCountry : userCountries) {
                countryIds.add(userCountry.getCountryId());
            }

            LambdaQueryWrapper<AdwebCountry> countryQueryWrapper = new LambdaQueryWrapper<>();
            countryQueryWrapper.notIn(AdwebCountry::getGeonameId, countryIds);
            countries = admpCountryService.list(countryQueryWrapper);
        }
        if (CollectionUtils.isEmpty(countries)) {
            return Result.OK();
        }

        // 将国家按大洲分组，然后组装成树结构
        Map<String, List<AdwebCountry>> map = new HashMap<>();
        for (AdwebCountry country : countries) {
            String continentCode = country.getContinentCode();
            List<AdwebCountry> countryList =
                    map.computeIfAbsent(continentCode, k -> new ArrayList<>());
            countryList.add(country);
        }

        List<TreeOption> options = new ArrayList<>();
        for (List<AdwebCountry> countryList : map.values()) {
            TreeOption parentOption = new TreeOption();
            parentOption.setKey(countryList.get(0).getContinentCode());
            parentOption.setValue(countryList.get(0).getContinentCode());
            parentOption.setTitle(countryList.get(0).getContinentName());
            List<TreeOption> children = new ArrayList<>();
            for (AdwebCountry country : countryList) {
                TreeOption option = new TreeOption();
                option.setKey(country.getGeonameId());
                option.setValue(country.getGeonameId());
                option.setTitle(country.getCountryName());
                children.add(option);
            }
            parentOption.setChildren(children);
            options.add(parentOption);
        }

        return Result.OK(options);
    }

    /** 分配国家 */
    @PostMapping(value = "/contribute/add")
    public Result<?> contributeCountry(@RequestBody DistributeCountryParam param) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //        if(sysUser.isPerform()){
        //            return Result.FORBIDDEN("\"演示版\"没有操作权限，如果需要操作，请切换到\"正式版\"再操作！");
        //        }
        String uid = param.getUid();
        String countryIds = param.getCountryIds();
        String[] countryIdArr = countryIds.split(",");
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<AdwebUserCountry> userCountries = new ArrayList<>();
        for (String countryId : countryIdArr) {
            if (StringUtils.isEmpty(countryId) || this.notNum(countryId)) {
                continue;
            }
            AdwebUserCountry country = new AdwebUserCountry();
            country.setUid(uid);
            country.setMasterUid(loginUser.getId());
            country.setSiteId(param.getSiteId());
            country.setCountryId(Integer.parseInt(countryId));
            country.setStatus(1);
            country.setCreateTime(new Date());
            userCountries.add(country);
        }
        adwebUserCountryService.saveBatch(userCountries);

        // 更改相关询盘的负责人
        LambdaQueryWrapper<AdwebCountry> countryQueryWrapper = new LambdaQueryWrapper<>();
        countryQueryWrapper.in(AdwebCountry::getGeonameId, countryIdArr);
        List<AdwebCountry> countries = admpCountryService.list(countryQueryWrapper);
        List<String> countryCodes =
                countries.stream()
                        .map(AdwebCountry::getCountryIsoCode)
                        .collect(Collectors.toList());

        List<Integer> siteIds = adwebSiteService.getAllSiteIdByParentId(param.getSiteId());
        LambdaUpdateWrapper<AdwebEnquiry> enquiryUpdateWrapper = new LambdaUpdateWrapper<>();
        enquiryUpdateWrapper.in(AdwebEnquiry::getCountryCode, countryCodes);
        enquiryUpdateWrapper.in(AdwebEnquiry::getSiteId, siteIds);
        enquiryUpdateWrapper.ne(AdwebEnquiry::getPrincipalType, 1);
        enquiryUpdateWrapper.set(AdwebEnquiry::getPrincipalUid, param.getUid());
        adwebEnquiryService.update(enquiryUpdateWrapper);

        return Result.OK();
    }

    private boolean notNum(String countryId) {
        if (countryId.charAt(0) < '1' || countryId.charAt(0) > '9') {
            return true;
        }
        return false;
    }

    /** 分配国家 */
    @PostMapping(value = "/contribute/delete")
    public Result<?> delete(@RequestBody DistributeCountryParam param) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //        if(sysUser.isPerform()){
        //            return Result.FORBIDDEN("\"演示版\"没有操作权限，如果需要操作，请切换到\"正式版\"再操作！");
        //        }
        String uid = param.getUid();
        String countryIds = param.getCountryIds();
        List<String> countryIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(countryIds)) {
            Collections.addAll(countryIdList, countryIds.split(","));
        }
        countryIdList.removeIf(this::notNum);
        LambdaUpdateWrapper<AdwebUserCountry> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AdwebUserCountry::getUid, uid);
        updateWrapper.eq(AdwebUserCountry::getSiteId, param.getSiteId());
        if (CollectionUtils.isNotEmpty(countryIdList)) {
            updateWrapper.notIn(AdwebUserCountry::getCountryId, countryIdList);
        }
        updateWrapper.set(AdwebUserCountry::getStatus, 0);
        adwebUserCountryService.update(updateWrapper);

        // 更改相关询盘的负责人
        List<Integer> siteIds = adwebSiteService.getAllSiteIdByParentId(param.getSiteId());
        LambdaUpdateWrapper<AdwebEnquiry> enquiryUpdateWrapper = new LambdaUpdateWrapper<>();
        if (CollectionUtils.isNotEmpty(countryIdList)) {
            LambdaQueryWrapper<AdwebCountry> countryQueryWrapper = new LambdaQueryWrapper<>();
            countryQueryWrapper.in(AdwebCountry::getGeonameId, countryIdList);
            List<AdwebCountry> countries = admpCountryService.list(countryQueryWrapper);
            List<String> countryCodes =
                    countries.stream()
                            .map(AdwebCountry::getCountryIsoCode)
                            .collect(Collectors.toList());
            enquiryUpdateWrapper.notIn(AdwebEnquiry::getCountryCode, countryCodes);
        }
        enquiryUpdateWrapper.in(AdwebEnquiry::getSiteId, siteIds);
        enquiryUpdateWrapper.eq(AdwebEnquiry::getPrincipalUid, param.getUid());
        enquiryUpdateWrapper.ne(AdwebEnquiry::getPrincipalType, 1);
        enquiryUpdateWrapper.setSql("principal_uid = uid");
        adwebEnquiryService.update(enquiryUpdateWrapper);
        return Result.OK();
    }

    /** 更改分配方式 */
    @AutoLog(value = "询盘管理-询盘分配-分配规则切换")
    @PostMapping(value = "/updateDistributeType")
    public Result<?> updateDistributeType(
            @RequestParam Integer siteId, @RequestParam String distributeType) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //        if(sysUser.isPerform()){
        //            return Result.FORBIDDEN("\"演示版\"没有操作权限，如果需要操作，请切换到\"正式版\"再操作！");
        //        }
        LambdaUpdateWrapper<AdwebSite> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AdwebSite::getId, siteId);
        updateWrapper.set(AdwebSite::getEnquiryDistributeType, distributeType);
        adwebSiteService.update(updateWrapper);

        // 修改询盘的跟进人
        if (EnquiryDistributeTypeConstant.MASTER.equals(distributeType)) {
            LambdaUpdateWrapper<AdwebEnquiry> enquiryUpdateWrapper = new LambdaUpdateWrapper<>();
            enquiryUpdateWrapper.ne(AdwebEnquiry::getPrincipalType, 1);
            enquiryUpdateWrapper.setSql("principal_uid = uid");
            adwebEnquiryService.update(enquiryUpdateWrapper);
        } else if (EnquiryDistributeTypeConstant.ALL.equals(distributeType)) {
            LambdaUpdateWrapper<AdwebEnquiry> enquiryUpdateWrapper = new LambdaUpdateWrapper<>();
            enquiryUpdateWrapper.ne(AdwebEnquiry::getPrincipalType, 1);
            enquiryUpdateWrapper.set(AdwebEnquiry::getPrincipalUid, "ALL");
            adwebEnquiryService.update(enquiryUpdateWrapper);
        } else if (EnquiryDistributeTypeConstant.REGION.equals(distributeType)) {
            adwebEnquiryService.updatePrincipalUidByRegion(siteId);
        }
        return Result.OK();
    }

    /** 更改询盘发送规则 */
    @AutoLog(value = "询盘管理-询盘分配-更改询盘发送规则")
    @PostMapping(value = "/updateSendEmailType")
    public Result<?> updateSendEmailType(
            @RequestParam Integer siteId, @RequestParam String sendEmailType) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //        if(sysUser.isPerform()){
        //            return Result.FORBIDDEN("\"演示版\"没有操作权限，如果需要操作，请切换到\"正式版\"再操作！");
        //        }
        LambdaUpdateWrapper<AdwebSite> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AdwebSite::getId, siteId);
        updateWrapper.set(AdwebSite::getEnquirySendEmailType, sendEmailType);
        adwebSiteService.update(updateWrapper);

        return Result.OK();
    }

    /** 根据站点id获取站点信息 */
    @GetMapping(value = "/getSiteBySiteId")
    public Result<?> getSiteBySiteId(Integer siteId) {
        AdwebSite site = adwebSiteService.getById(siteId);
        return Result.OK(site);
    }

    /**
     * 添加
     *
     * @param adwebUserCountry
     * @return
     */
    @AutoLog(value = "adweb_user_country-添加")
    @Operation(description = "adweb_user_country-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AdwebUserCountry adwebUserCountry) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //        if(sysUser.isPerform()){
        //            return Result.FORBIDDEN("\"演示版\"没有操作权限，如果需要操作，请切换到\"正式版\"再操作！");
        //        }
        adwebUserCountryService.save(adwebUserCountry);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param adwebUserCountry
     * @return
     */
    @AutoLog(value = "adweb_user_country-编辑")
    @Operation(description = "adweb_user_country-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AdwebUserCountry adwebUserCountry) {
        adwebUserCountryService.updateById(adwebUserCountry);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "adweb_user_country-通过id删除")
    @Operation(description = "adweb_user_country-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        adwebUserCountryService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "adweb_user_country-批量删除")
    @Operation(description = "adweb_user_country-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.adwebUserCountryService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "adweb_user_country-通过id查询")
    @Operation(description = "adweb_user_country-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AdwebUserCountry adwebUserCountry = adwebUserCountryService.getById(id);
        if (adwebUserCountry == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(adwebUserCountry);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param adwebUserCountry
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AdwebUserCountry adwebUserCountry) {
        return super.exportXls(
                request, adwebUserCountry, AdwebUserCountry.class, "adweb_user_country");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AdwebUserCountry.class);
    }
}
