package com.hzs.member.base.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.StringUtils;
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.member.base.CuMemberTeam;
import com.hzs.common.domain.member.ext.CuMemberTeamExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.member.base.service.ICuMemberTeamService;
import com.hzs.member.base.vo.CuMemberTeamVO;
import com.hzs.system.base.ITransactionServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 会员所属团队（隶属团队）前端控制器
 *
 * @author zhangjing
 * @since 2022-09-16
 */
@RestController
@RequestMapping("/manage/member-team")
public class CuMemberTeamController extends BaseController {

    @Autowired
    private ICuMemberTeamService cuMemberTeamService;

    @DubboReference
    ITransactionServiceApi iTransactionServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;

    /**
     * @description: 查询会员所属团队（隶属团队）列表
     * @author: zhang jing
     * @date: 2022/8/30 10:20
     * @param: [cuMemberTeam]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.CU_MEMBER_TEAM, business = EOperationBusiness.AFFILIATION_TEAM, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(CuMemberTeamExt cuMemberTeam) {
        cuMemberTeam.setPkCountry(SecurityUtils.getPkCountry());
        cuMemberTeam.setSystemType(SecurityUtils.getSystemType());

        startPage();
        List<CuMemberTeamExt> list = cuMemberTeamService.queryCuMemberTeam(cuMemberTeam);
        return getDataTable(list);
    }

    /**
     * @description: 隶属团队下拉选
     * @author: zhang jing
     * @date: 2022/11/16 15:43
     * @param: [cuMemberTeam]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.CU_MEMBER_TEAM, business = EOperationBusiness.AFFILIATION_TEAM, method = EOperationMethod.SELECT)
    @GetMapping("/listNoPage")
    public TableDataInfo listNoPage(CuMemberTeamExt cuMemberTeam) {
        cuMemberTeam.setPkCountry(SecurityUtils.getPkCountry());
        cuMemberTeam.setSystemType(SecurityUtils.getSystemType());

        List<CuMemberTeamExt> list = cuMemberTeamService.queryCuMemberTeam(cuMemberTeam);
        List<CuMemberTeamVO> listVo = new ArrayList<>();
        list.forEach(item -> listVo.add(BeanUtil.copyProperties(item, CuMemberTeamVO.class)));
        return getDataTable(listVo);
    }

    /**
     * 查询全部团队
     *
     * @return
     */
    @GetMapping("/find-all")
    public AjaxResult findAll() {
        return AjaxResult.success(cuMemberTeamService.list(
                Wrappers.<CuMemberTeam>lambdaQuery().eq(CuMemberTeam::getSystemType, SecurityUtils.getSystemType()))
        );
    }

    /**
     * 根据体系查询团队配置
     *
     * @param pkVertexList
     * @return
     */
    @GetMapping("/find-vertex")
    public AjaxResult findByVertex(@RequestParam List<Long> pkVertexList) {
        LambdaQueryWrapper<CuMemberTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CuMemberTeam::getPkBdVertex, pkVertexList);
        queryWrapper.orderByAsc(CuMemberTeam::getTeamName);
        return AjaxResult.success(cuMemberTeamService.list(queryWrapper));
    }


    /**
     * @description: 新增会员所属团队（隶属团队）
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [cuMemberTeam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.CU_MEMBER_TEAM, business = EOperationBusiness.AFFILIATION_TEAM, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody CuMemberTeamExt cuMemberTeam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isEmpty(cuMemberTeam.getTeamName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.TEAM_NAME_NOT_NULL));
        }
        if (StringUtils.isEmpty(cuMemberTeam.getTeamCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.TEAM_CODE_NOT_NULL));
        }

        if (StringUtils.isNull(cuMemberTeam.getMemberCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
        }
        R<CuMember> member = iMemberServiceApi.getMember(cuMemberTeam.getMemberCode());
        if (StringUtils.isNull(member.getData())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        LambdaQueryWrapper<CuMemberTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberTeam::getPkMember, member.getData().getPkId());
        List<CuMemberTeam> list = cuMemberTeamService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_REPEAT));
        }
        cuMemberTeam.setPkMember(member.getData().getPkId());
        //字段翻译保存到数据库
        R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.MEMBER,
                cuMemberTeam.getTeamName(), EYesNo.NO, EYesNo.NO);
        cuMemberTeam.setPkTransaction(pkTransaction.getData());
        cuMemberTeam.setPkCountry(pkCountry);
        cuMemberTeam.setPkCreator(SecurityUtils.getUserId());
        cuMemberTeam.setCreationTime(new Date());
        cuMemberTeam.setSystemType(SecurityUtils.getSystemType());
        return toAjax(cuMemberTeamService.save(cuMemberTeam));
    }


    /**
     * @description: 修改会员所属团队（隶属团队）
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [cuMemberTeam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.CU_MEMBER_TEAM, business = EOperationBusiness.AFFILIATION_TEAM, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody CuMemberTeamExt cuMemberTeam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isEmpty(cuMemberTeam.getTeamName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.TEAM_NAME_NOT_NULL));
        }
        if (StringUtils.isEmpty(cuMemberTeam.getTeamCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.TEAM_CODE_NOT_NULL));
        }
        if (StringUtils.isNull(cuMemberTeam.getPkBdVertex())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_BD_VERTEX_NOT_NULL));
        }
        if (StringUtils.isNull(cuMemberTeam.getMemberCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
        }
        R<CuMember> member = iMemberServiceApi.getMember(cuMemberTeam.getMemberCode());
        if (StringUtils.isNull(member.getData())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        LambdaQueryWrapper<CuMemberTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberTeam::getPkMember, member.getData().getPkId());
        queryWrapper.ne(CuMemberTeam::getPkId, cuMemberTeam.getPkId());
        List<CuMemberTeam> list = cuMemberTeamService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_REPEAT));
        }
        cuMemberTeam.setPkMember(member.getData().getPkId());

        if (null != cuMemberTeam.getPkTransaction()) {
            iTransactionServiceApi.updateTransaction(pkCountry,
                    cuMemberTeam.getTeamName(), cuMemberTeam.getPkTransaction(), true);
        } else {
            //字段翻译保存到数据库
            R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.MEMBER,
                    cuMemberTeam.getTeamName(), EYesNo.NO, EYesNo.NO);
            cuMemberTeam.setPkTransaction(pkTransaction.getData());
        }

        cuMemberTeam.setPkModified(SecurityUtils.getUserId());
        cuMemberTeam.setModifiedTime(new Date());
        return toAjax(cuMemberTeamService.updateById(cuMemberTeam));
    }


    /**
     * @description: 查询单条会员所属团队（隶属团队）
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.CU_MEMBER_TEAM, business = EOperationBusiness.AFFILIATION_TEAM, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        CuMemberTeamExt memberTeam = new CuMemberTeamExt();
        memberTeam.setPkId(pkId);
        List<CuMemberTeamExt> cuMemberTeam = cuMemberTeamService.queryCuMemberTeam(memberTeam);
        CuMemberTeamExt cuMemberTeamExt = cuMemberTeam.get(0);
        return AjaxResult.success(cuMemberTeamExt);
    }


    /**
     * @description: 删除会员所属团队（隶属团队）
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.CU_MEMBER_TEAM, business = EOperationBusiness.AFFILIATION_TEAM, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        LambdaUpdateWrapper<CuMemberTeam> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CuMemberTeam::getPkId, pkId);
        updateWrapper.set(CuMemberTeam::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(CuMemberTeam::getPkModified, SecurityUtils.getUserId());
        updateWrapper.set(CuMemberTeam::getModifiedTime, new Date());
        //删除翻译
        CuMemberTeam memberTeam = cuMemberTeamService.getById(pkId);
        List<Long> pkIdList = new ArrayList<>();
        pkIdList.add(memberTeam.getPkTransaction().longValue());
        iTransactionServiceApi.removeTransactionByPkId(pkIdList);
        return toAjax(cuMemberTeamService.update(updateWrapper));
    }

    /**
     * @description: 更新所属团队（隶属团队）
     * @author: sui  q
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.CU_MEMBER_TEAM, business = EOperationBusiness.AFFILIATION_TEAM, method = EOperationMethod.RENEW)
    @GetMapping("/update-team/{pkTeamCode}")
    public AjaxResult updateTeamByVertex(@PathVariable Long pkTeamCode) {
        cuMemberTeamService.updateCuMemberTeamByVertex(pkTeamCode);
        return AjaxResult.success();
    }

    /**
     * 刷新全部团队
     *
     * @return
     */
    @Log(module = EOperationModule.CU_MEMBER_TEAM, business = EOperationBusiness.AFFILIATION_TEAM, method = EOperationMethod.RENEW)
    @GetMapping("/flush-all")
    public AjaxResult flushAll() {
        cuMemberTeamService.flushAllTeam(SecurityUtils.getPkCountry());
        return AjaxResult.success();
    }

}
