package com.cpop.oam.business.controller.backstage;

import com.cpop.common.utils.StringUtils;
import com.cpop.common.utils.bean.BeanUtils;
import com.cpop.core.annontation.OperationLog;
import com.cpop.core.base.R;
import com.cpop.core.base.enums.OperationLogEnum;
import com.cpop.core.base.exception.ServiceException;
import com.cpop.core.base.table.SysConfig;
import com.cpop.core.service.CoreService;
import com.cpop.core.service.RedisService;
import com.cpop.core.utils.SpringUtils;
import com.cpop.oam.business.bo.*;
import com.cpop.oam.business.service.CommonService;
import com.cpop.oam.business.service.SignAreaService;
import com.cpop.oam.business.vo.ConfigInfoVo;
import com.cpop.oam.business.vo.SignGoalConfigInfoVo;
import com.cpop.oam.business.vo.SignGoalPageVo;
import com.cpop.oam.business.vo.StaffPageVo;
import com.cpop.oam.framework.constant.OamConfigKey;
import com.cpop.oam.framework.enums.OamConfigEnum;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.DbChain;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import com.cpop.oam.business.entity.SignGoal;
import com.cpop.oam.business.service.SignGoalService;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cpop.core.base.table.table.SysConfigTableDef.SYS_CONFIG;
import static com.cpop.oam.business.entity.table.SignAreaTableDef.SIGN_AREA;

/**
 * 签约目标表 控制层。
 *
 * @author DB
 * @since 2024-02-19
 */
@RestController
@Api(tags = "签约目标接口")
@RequestMapping("/backstage/signGoal")
public class BackstageSignGoalController {

    @Autowired
    private SignGoalService signGoalService;

    /**
     * 签约指标分页
     * @author DB
     * @since 2024/2/19
     * @return R<Page<SignGoalPageVo>>
     */
    @ApiOperation("签约指标分页")
    @GetMapping("/getSignGoalPage")
    public R<Page<SignGoalPageVo>> getSignGoalPage() {
        Page<SignGoalPageVo> pageVo = signGoalService.getSignGoalPage();
        return R.ok(pageVo);
    }

    /**
     * 设置签约间隔配置信息
     * @author DB
     * @since 2024/2/19
     * @param bo 请求参数
     * @return R<Void>
     */
    @ApiOperation("设置签约间隔配置信息")
    @PutMapping("/setSignConfigInfo")
    public R<Void> setSignConfigInfo(@RequestBody @Validated SignGoalConfigInfoBo bo) {
        CoreService coreService = SpringUtils.getBean(CoreService.class);
        CommonService commonService = SpringUtils.getBean(CommonService.class);
        // 遍历属性名与值
        try {
            for (Field field : bo.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                // 获取枚举
                OamConfigEnum sysConfigEnum = OamConfigEnum.matchField(field.getName());
                if (null != sysConfigEnum) {
                    SysConfig sysConfig = new SysConfig();
                    sysConfig.setConfigName(sysConfigEnum.getName())
                            .setConfigKey(sysConfigEnum.getKey())
                            .setConfigValue(field.get(bo).toString());
                    // 修改
                    if (DbChain.table(SYS_CONFIG)
                            .where(SYS_CONFIG.CONFIG_KEY.eq(sysConfig.getConfigKey()))
                            .count() > 0) {
                        coreService.updateConfig(sysConfig);
                    } else {
                        coreService.insertConfig(sysConfig);
                    }
                    // 更新缓存
                    SpringUtils.getBean(RedisService.class).setCacheObject(commonService.getCacheKey(sysConfigEnum.getKey()), sysConfig.getConfigValue());
                }
            }
        } catch (IllegalAccessException e) {
            throw new ServiceException("设置签约间隔配置信息失败,请联系相关人员!");
        }
        return R.ok();
    }

    /**
     * 获取签约间隔配置信息
     * @author DB
     * @since 2024/2/19
     * @return R<SignGoalConfigInfoVo>
     */
    @ApiOperation("获取签约间隔配置信息")
    @GetMapping("/getSignConfigInfo")
    public R<SignGoalConfigInfoVo> getSignConfigInfo() {
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        CoreService coreService = SpringUtils.getBean(CoreService.class);
        CommonService commonService = SpringUtils.getBean(CommonService.class);
        Map<String, String> configMap = new HashMap<>(8);
        Arrays.asList(OamConfigKey.SIGN_GOAL).forEach(item -> {
            String cacheInfo = redisService.getCacheObject(commonService.getCacheKey(item));
            if (StringUtils.isNotBlank(cacheInfo)) {
                // 获取枚举
                OamConfigEnum sysConfigEnum = OamConfigEnum.matchKey(item);
                configMap.put(sysConfigEnum.getField(), cacheInfo);
            } else {
                // 查询系统
                SysConfig sysConfig = coreService.selectConfigByKey(item);
                if (null != sysConfig) {
                    // 获取枚举
                    OamConfigEnum sysConfigEnum = OamConfigEnum.matchKey(item);
                    configMap.put(sysConfigEnum.getField(), sysConfig.getConfigValue());
                }
            }
        });
        SignGoalConfigInfoVo signGoalConfigInfoVo = new SignGoalConfigInfoVo();
        BeanUtils.mapToObj(configMap, signGoalConfigInfoVo);
        return R.ok(signGoalConfigInfoVo);
    }

    /**
     * 新增签约指标
     * @author DB
     * @since 2024/2/19
     * @param bo 请求参数
     * @return R<Void>
     */
    @ApiOperation("新增签约指标")
    @PostMapping("/insertSignGoal")
    public R<Void> insertSignGoal(@RequestBody @Validated SignGoalBo bo) {
        signGoalService.insertSignGoal(bo);
        return R.ok();
    }

    /**
     * 修改签约指标
     * @author DB
     * @since 2024/2/19
     * @param bo 请求参数
     * @return R<Void>
     */
    @ApiOperation("修改签约指标")
    @PutMapping("/updateSignGoal")
    public R<Void> updateSignGoal(@RequestBody @Validated SignGoalBo bo) {
        signGoalService.updateSignGoal(bo);
        return R.ok();
    }

    /**
     * 删除签约指标
     * @author DB
     * @since 2024/2/19
     * @param id 主键
     * @return R<Void>
     */
    @ApiOperation("删除签约指标")
    @DeleteMapping("/removeSignGoal/{id}")
    public R<Void> removeSignGoal(@PathVariable String id) {
        signGoalService.removeById(id);
        SpringUtils.getBean(SignAreaService.class).remove(QueryWrapper.create().where(SIGN_AREA.SIGN_GOAL_ID.eq(id)));
        return R.ok();
    }
}
