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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hzs.common.core.annotation.Log;
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.EOperationBusiness;
import com.hzs.common.core.enums.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
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.domain.vertex.ext.BdVertexExt;
import com.hzs.common.security.utils.SecurityUtils;

import com.hzs.common.util.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 IBdVertexService vertexService;

    @DubboReference
    IMemberTeamServiceApi memberTeamServiceApi;
    @DubboReference
    IMemberServiceApi memberServiceApi;

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

    /**
     * 新增体系配置
     *
     * @param vertexParam
     * @return
     */
    @Log(module = EOperationModule.SPECS_VERTEX_LIST, business = EOperationBusiness.VERTEX_CONFIG, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody VertexParam vertexParam) {
        Integer systemType = SecurityUtils.getSystemType();

        LambdaQueryWrapper<BdVertex> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BdVertex::getVertexName, vertexParam.getVertexName());
        wrapper.eq(BdVertex::getSystemType, systemType);
        if (vertexService.count(wrapper) > 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("用户编号不存在");
        }
        LambdaQueryWrapper<BdVertex> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdVertex::getPkMember, mb.getPkId());
        if (vertexService.count(queryWrapper) > 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());
        bdVertex.setSystemType(systemType);
        vertexService.save(bdVertex);
        return AjaxResult.success();
    }

    /**
     * 修改体系认证
     *
     * @return
     */
    @Log(module = EOperationModule.SPECS_VERTEX_LIST, business = EOperationBusiness.VERTEX_CONFIG, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody VertexParam vertexParam) {
        Integer systemType = SecurityUtils.getSystemType();

        LambdaQueryWrapper<BdVertex> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BdVertex::getVertexName, vertexParam.getVertexName());
        wrapper.eq(BdVertex::getSystemType, systemType);
        wrapper.notIn(BdVertex::getPkId, vertexParam.getPkId());
        if (vertexService.count(wrapper) > 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("用户编号不存在");
        }
        LambdaQueryWrapper<BdVertex> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdVertex::getPkMember, mb.getPkId());
        queryWrapper.notIn(BdVertex::getPkId, vertexParam.getPkId());
        if (vertexService.count(queryWrapper) > 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());
        if (null == bdVertex.getPkParent()) {
            bdVertex.setPkParent(0);
        }
        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
     */
    @Log(module = EOperationModule.SPECS_VERTEX_LIST, business = EOperationBusiness.VERTEX_CONFIG, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    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));
        }
        LambdaUpdateWrapper<BdVertex> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BdVertex::getPkId, pkId);
        updateWrapper.set(BdVertex::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(BdVertex::getModifiedTime, new Date());
        updateWrapper.set(BdVertex::getPkModified, SecurityUtils.getUserId());
        return AjaxResult.success(vertexService.update(updateWrapper));
    }

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

    /**
     * 查询体系以及子体系
     *
     * @return
     */
    @GetMapping("/vertex-child")
    public AjaxResult vertexChild() {
        List<BdVertexExt> list = vertexService.queryBdVertexChild(SecurityUtils.getPkCountry(), SecurityUtils.getSystemType());
        return AjaxResult.success(list);
    }

    /**
     * 根据国家查询体系配置
     *
     * @param pkCountryList 国家ID列表
     * @return
     */
    @GetMapping("/find-country")
    public AjaxResult findByCountry(@RequestParam List<Long> pkCountryList) {
        LambdaQueryWrapper<BdVertex> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(BdVertex::getPkCountry, pkCountryList);
        queryWrapper.eq(BdVertex::getSystemType, SecurityUtils.getSystemType());
        queryWrapper.orderByAsc(BdVertex::getVertexName);
        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, business = EOperationBusiness.VERTEX_CONFIG, method = EOperationMethod.RENEW)
    @GetMapping("/update-vertex/{pkVertex}")
    public AjaxResult updateVertex(@PathVariable Integer pkVertex) {
        vertexService.updateBdVertexById(pkVertex);
        return AjaxResult.success();
    }

    /**
     * 刷新全部体系
     *
     * @return
     */
    @Log(module = EOperationModule.SPECS_VERTEX_LIST, business = EOperationBusiness.VERTEX_CONFIG, method = EOperationMethod.RENEW)
    @GetMapping("/flush-all")
    public AjaxResult flushAll() {
        vertexService.flushAllVertex(SecurityUtils.getPkCountry(), SecurityUtils.getSystemType());
        return AjaxResult.success();
    }

    /**
     * 查询体系配置
     */
    @GetMapping("/find-vertex")
    public AjaxResult findVertex() {
        LambdaQueryWrapper<BdVertex> qw = new LambdaQueryWrapper<>();
        qw.eq(BdVertex::getPkCountry, SecurityUtils.getPkCountry());
        List<BdVertex> list = vertexService.list(qw);
        return AjaxResult.success(list);
    }
}
