package com.hzs.system.config.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.VertexConstants;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.core.enums.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.vertex.BdVertex;
import com.hzs.common.security.utils.SecurityUtils;

import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.member.base.IMemberTeamServiceApi;
import com.hzs.system.config.param.VertexParam;
import com.hzs.system.config.service.IBdVertexService;
import com.hzs.system.config.vo.VertexVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @Description: 体系配置
 * @Author: yuhui
 * @Time: 2022/11/1 11:11
 * @Classname: BdVertexController
 * @PackageName: com.hzs.sale.vertex.controller.manage
 */
@Slf4j
@RestController
@RequestMapping("/manage/vertex")
public class BdVertexController extends BaseController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private IBdVertexService vertexService;
    @DubboReference
    private IMemberTeamServiceApi memberTeamServiceApi;
    @DubboReference
    private IMemberServiceApi memberServiceApi;

    /**
     * 查询列表
     *
     * @return
     */
    @GetMapping("list")
    @Log(module = EOperationModule.SPECS_VERTEX_LIST, method = EOperationMethod.SELECT)
    public TableDataInfo list(VertexParam vertex) {
        startPage();
        vertex.setPkCountry(SecurityUtils.getPkCountry());
        List<VertexVo> list = vertexService.selectByList(vertex);

        return getDataTable(list);
    }

    /**
     * 新增体系配置
     *
     * @param vertexParam
     * @return
     */
    @PostMapping("save")
    @Log(module = EOperationModule.SPECS_VERTEX_SAVE, method = EOperationMethod.INSERT)
    public AjaxResult save(@RequestBody VertexParam vertexParam) {
        QueryWrapper<BdVertex> wrapper = new QueryWrapper<>();
        wrapper.eq("VERTEX_NAME", vertexParam.getVertexName());
        int nameCount = vertexService.count(wrapper);
        if (nameCount > 0) {
            // 体系名称已存在
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.VERTEX_NAME_EXITS));
        }
        //  会员编号检验是否存在
        R<CuMember> member = memberServiceApi.getMember(vertexParam.getMemberCode());
        CuMember mb = member.getData();
        if (mb == null) {
            return AjaxResult.error("用户编号不存在");
        }
//        R<Boolean> isExist = memberServiceApi.getMemberPlaceParent(VertexConstants.GJ30720200, vertexParam.getMemberCode());
//        if (!isExist.getData()) {
//            // 只能是 cn30720200 编号的下一级
//            return AjaxResult.error("体系编号只能为首层编号");
//        }
        QueryWrapper<BdVertex> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_MEMBER", mb.getPkId());
        int count = vertexService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_CODE_EXITS));
        }

        BdVertex bdVertex = BeanUtil.copyProperties(vertexParam, BdVertex.class);
        bdVertex.setCreationTime(new Date());
        bdVertex.setPkCountry(SecurityUtils.getPkCountry());
        bdVertex.setPkCreator(SecurityUtils.getUserId());
        bdVertex.setPkMember(mb.getPkId());
        vertexService.save(bdVertex);
        // TODO  体系配置增删改需要修改用户相关缓存
        return AjaxResult.success();
    }

    /**
     * 修改体系认证
     *
     * @return
     */
    @PostMapping("update")
    @Log(module = EOperationModule.SPECS_VERTEX_UPDATE, method = EOperationMethod.UPDATE)
    public AjaxResult update(@RequestBody VertexParam vertexParam) {

        QueryWrapper<BdVertex> wrapper = new QueryWrapper<>();
        wrapper.eq("VERTEX_NAME", vertexParam.getVertexName());
        wrapper.notIn("PK_ID", vertexParam.getPkId());
        int nameCount = vertexService.count(wrapper);
        if (nameCount > 0) {
            // 体系名称已存在
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.VERTEX_NAME_EXITS));
        }
        //  会员编号检验是否存在
        R<CuMember> member = memberServiceApi.getMember(vertexParam.getMemberCode());
        CuMember mb = member.getData();
        if (mb == null) {
            return AjaxResult.error("用户编号不存在");
        }
        R<Boolean> isExist = memberServiceApi.getMemberPlaceParent(VertexConstants.GJ30720200, vertexParam.getMemberCode());
        if (!isExist.getData()) {
            // 只能是 cn30720200 编号的下一级
            return AjaxResult.error("体系编号只能为首层编号");
        }
        QueryWrapper<BdVertex> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_MEMBER", mb.getPkId());
        queryWrapper.notIn("PK_ID", vertexParam.getPkId());
        int count = vertexService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_CODE_EXITS));
        }
        BdVertex bdVertex = BeanUtil.copyProperties(vertexParam, BdVertex.class);
        bdVertex.setPkMember(mb.getPkId());
        bdVertex.setModifiedTime(new Date());
        bdVertex.setPkModified(SecurityUtils.getUserId());
        String redisKey = CacheConstants.BD_VERTEX + bdVertex.getPkId();
        redisService.deleteObject(redisKey);
        // TODO  体系配置增删改需要修改用户相关缓存  删除数量过于庞大 暂时不操作 后期需要讨论之后删除
        return toAjax(vertexService.updateById(bdVertex));
    }

    /**
     * 根据id
     *
     * @param pkId
     * @return
     */
    @GetMapping("detail")
    public AjaxResult detail(Integer pkId) {
        BdVertex vertex = vertexService.getById(pkId);
        VertexVo vertexVo = BeanUtil.copyProperties(vertex, VertexVo.class);
        R<CuMember> member = memberServiceApi.getMember(vertex.getPkMember());
        vertexVo.setMemberCode(member.getData().getMemberCode());
        return AjaxResult.success(vertexVo);
    }

    /**
     * 删除
     *
     * @param pkId
     * @return
     */
    @DeleteMapping("/{pkId}")
    @Log(module = EOperationModule.SPECS_VERTEX_DELETE, method = EOperationMethod.DELETE)
    public AjaxResult delete(@PathVariable Integer pkId) {
        R<Boolean> mt = memberTeamServiceApi.checkVertex(pkId);
        if (mt.getData()) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.VERTEX_MEMBER_TEAM_REGISTER));
        }
        UpdateWrapper<BdVertex> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_ID", pkId);
        updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        updateWrapper.set("MODIFIED_TIME", new Date());
        updateWrapper.set("PK_MODIFIED", SecurityUtils.getUserId());
        String redisKey = CacheConstants.BD_VERTEX + pkId;
        redisService.deleteObject(redisKey);
        // TODO  体系配置增删改需要修改用户相关缓存  删除数量过于庞大 暂时不操作 后期需要讨论之后删除
        return AjaxResult.success(vertexService.update(updateWrapper));
    }

    /**
     * 查询全部体系配置
     *
     * @return
     */
    @GetMapping("/find-all")
    public AjaxResult findAll() {
        QueryWrapper<BdVertex> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.orderByAsc("VERTEX_NAME");
        return AjaxResult.success(vertexService.list(queryWrapper));
    }

    /**
     * 根据国家查询体系配置
     *
     * @param pkCountryList 国家ID列表
     * @return
     */
    @GetMapping("/find-country")
    public AjaxResult findByCountry(@RequestParam List<Long> pkCountryList) {
        QueryWrapper<BdVertex> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("PK_COUNTRY", pkCountryList);
        queryWrapper.orderByAsc("VERTEX_NAME");
        return AjaxResult.success(vertexService.list(queryWrapper));
    }

    /**
     * @description: 更新体系（隶属体系）
     * @author: sui  q
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECS_VERTEX_LIST, method = EOperationMethod.RENEW)
    @GetMapping("/update-vertex/{pkVertex}")
    public AjaxResult updateVertex(@PathVariable Integer pkVertex) {
        vertexService.updateBdVertexById(pkVertex);
        return AjaxResult.success();
    }
}
