package com.testor.module.fives.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.common.core.utils.StringUtils;
import com.testor.module.fives.model.domain.TFivesToolEvaluate;
import com.testor.module.fives.model.domain.TFivesToolUse;
import com.testor.module.fives.model.dto.TFivesToolEvaluateDelParam;
import com.testor.module.fives.model.dto.TFivesToolEvaluateParam;
import com.testor.module.fives.service.TFivesToolEvaluateService;
import com.testor.module.fives.service.TFivesToolUseService;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.service.NewSysOrgService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 5s工具运用评价Controller
 *
 * @author testor-framework
 * @date 2022-07-21 15:56:53
 */
@RestController
@RequestMapping("/module/fives/tool/evaluate")
@Api(value = "TFivesToolEvaluate", tags = "5s工具运用评价")
@Slf4j
public class TFivesToolEvaluateController extends SuperController {
    @Autowired
    private TFivesToolEvaluateService tFivesToolEvaluateService;
    @Autowired
    private NewSysOrgService newSysOrgService;
    @Autowired
    private TFivesToolUseService tFivesToolUseService;

    @ApiOperation(value = "获取评价人详情 ", notes = "id 工具运用id")
    @GetMapping(value = "/getAppraise")
    public BaseResponse<Map<String, List<TFivesToolEvaluate>>> getAppraise(String id) {
        BaseResponse<Map<String, List<TFivesToolEvaluate>>> response = new BaseResponse<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        // 获取当前登录用户评价内容
        TFivesToolEvaluate serviceOne = tFivesToolEvaluateService.getOne(new QueryWrapper<TFivesToolEvaluate>().eq(TFivesToolEvaluate.TOOL_USE_ID, id)
                .ne(TFivesToolEvaluate.STATUS, BizConstants.STATUS_DELETE).eq(TFivesToolEvaluate.EVALUATE_USE_ID, loginUser.getUserId())
        );
        // 获取所有评价
        List<TFivesToolEvaluate> list = tFivesToolEvaluateService.list(new LambdaQueryWrapper<TFivesToolEvaluate>()
                .eq(TFivesToolEvaluate::getToolUseId, id)
                .ne(TFivesToolEvaluate::getStatus, BizConstants.STATUS_DELETE)
        );
        if (ObjectHelper.isEmpty(serviceOne)) {
            TFivesToolEvaluate tFivesToolEvaluate = new TFivesToolEvaluate();
            String nature = newSysOrgService.getOrgNatureById(loginUser.getOrgId());

            tFivesToolEvaluate.setOrgId(loginUser.getOrgId());
            tFivesToolEvaluate.setEvaluateUseId(loginUser.getUserId());
            tFivesToolEvaluate.setToolUseId(id);
            tFivesToolEvaluate.setTreeLevel(new BigDecimal(nature));
            // 7 表示未平
            tFivesToolEvaluate.setScore(BigDecimal.valueOf(7));
            list.add(tFivesToolEvaluate);
        }
        // 按照 级别区分
        Map<String, List<TFivesToolEvaluate>> levelToItemsMap = list.stream().collect(Collectors.groupingBy(item -> item.getTreeLevel().toString()));

        response.setData(levelToItemsMap);
        return response ;
    }



    @ApiOperation(value = "新增 5s工具运用评价", notes = "id 工具运用id")
    @PostMapping(value = "/add")
    public BaseResponse<TFivesToolEvaluate> addEntity(@RequestBody TFivesToolEvaluate addRequest) {
        BaseResponse<TFivesToolEvaluate> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            UserInfo loginUser = ContextUtils.getLoginUser();
            String nature = newSysOrgService.getOrgNatureById(loginUser.getOrgId());
            // 工具运用id
            String toolId = addRequest.getId();
            if ("4".equals(nature)) {
                boolean update = tFivesToolUseService.update(new UpdateWrapper<TFivesToolUse>()
                        .eq(TFivesToolUse.ID, toolId).set(TFivesToolUse.SCORE, "6").set( TFivesToolUse.SCORE_TYPE, "6"));
            } else {
                boolean update = tFivesToolUseService.update(new UpdateWrapper<TFivesToolUse>()
                        .eq(TFivesToolUse.ID, toolId).set(addRequest.getScore() != null, TFivesToolUse.SCORE, addRequest.getScore())
                        .set(addRequest.getScore() != null, TFivesToolUse.SCORE_TYPE, addRequest.getScore())
                );
            }
            String id = IdHelper.getId32bit();
            TFivesToolEvaluate data = BeanHelper.beanToBean(addRequest, TFivesToolEvaluate.class);
            data.setId(id);
            data.setToolUseId(toolId);
            data.setOrgId(loginUser.getOrgId());
            data.setEvaluateUseId(loginUser.getUserId());
            data.setTreeLevel(new BigDecimal(nature));
            boolean result = tFivesToolEvaluateService.save(data);
            if (result) {
                TFivesToolEvaluate newEntity = new TFivesToolEvaluate();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        }
        return baseResponse;
    }


    public BaseResponse<TFivesToolEvaluate> getById(String id) {
        BaseResponse<TFivesToolEvaluate> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            // TODO 按需求添加业务异常判断
            TFivesToolEvaluate data = tFivesToolEvaluateService.getById(id);
            baseResponse.setData(data);
        }
        return baseResponse;
    }


    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TFivesToolEvaluate updateRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TFivesToolEvaluate data = BeanHelper.beanToBean(updateRequest, TFivesToolEvaluate.class);
            boolean result = tFivesToolEvaluateService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TFivesToolEvaluateDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TFivesToolEvaluate data = new TFivesToolEvaluate();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = tFivesToolEvaluateService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TFivesToolEvaluateDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TFivesToolEvaluate> tFivesToolEvaluateList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TFivesToolEvaluate data = new TFivesToolEvaluate();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tFivesToolEvaluateList.add(data);
            }
            boolean result = tFivesToolEvaluateService.updateBatchById(tFivesToolEvaluateList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    public BaseResponse<BaseResponseList<TFivesToolEvaluate>> listEntity(TFivesToolEvaluateParam param) {
        BaseResponse<BaseResponseList<TFivesToolEvaluate>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TFivesToolEvaluate> resultPage = new Page<>(page, limit);
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TFivesToolEvaluate> queryWrapper = this.createQuery(param);
        Page<TFivesToolEvaluate> resultList = tFivesToolEvaluateService.page(resultPage, queryWrapper);
        BaseResponseList<TFivesToolEvaluate> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }


    public BaseResponse<BaseResponseList<TFivesToolEvaluate>> listAllEntity(TFivesToolEvaluateParam param) {
        BaseResponse<BaseResponseList<TFivesToolEvaluate>> baseResponse = new BaseResponse<>();
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TFivesToolEvaluate> queryWrapper = this.createQuery(param);
        List<TFivesToolEvaluate> resultList = tFivesToolEvaluateService.list(queryWrapper);
        BaseResponseList<TFivesToolEvaluate> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TFivesToolEvaluate> createQuery(TFivesToolEvaluateParam queryParam) {
        QueryWrapper<TFivesToolEvaluate> queryWrapper = new QueryWrapper<>();
        if (StringHelper.isNotEmpty(queryParam.getRefId())) {
            queryWrapper.eq(TFivesToolEvaluate.REF_ID, queryParam.getRefId());
        }
        if (StringHelper.isNotEmpty(queryParam.getParentId())) {
            queryWrapper.eq(TFivesToolEvaluate.PARENT_ID, queryParam.getParentId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TFivesToolEvaluate.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TFivesToolEvaluate.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TFivesToolEvaluate.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getEvaluateUseId())) {
            queryWrapper.eq(TFivesToolEvaluate.EVALUATE_USE_ID, queryParam.getEvaluateUseId());
        }
        if (StringHelper.isNotEmpty(queryParam.getToolUseId())) {
            queryWrapper.eq(TFivesToolEvaluate.TOOL_USE_ID, queryParam.getToolUseId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TFivesToolEvaluate.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TFivesToolEvaluate.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TFivesToolEvaluate.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
