package com.fs.company.controller.course;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.bean.BeanUtils;
import com.fs.course.domain.FsCoursePlaySourceConfig;
import com.fs.course.param.FsCoursePlaySourceConfigCreateParam;
import com.fs.course.param.FsCoursePlaySourceConfigEditParam;
import com.fs.course.service.IFsCoursePlaySourceConfigService;
import com.fs.course.vo.FsCoursePlaySourceConfigVO;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/course/playSourceConfig")
@AllArgsConstructor
public class FsCoursePlaySourceConfigController extends BaseController {

    private final IFsCoursePlaySourceConfigService fsCoursePlaySourceConfigService;
    private final RedisCache redisCache;

    @PreAuthorize("@ss.hasPermi('course:playSourceConfig:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) String name,
                              @RequestParam(required = false) String appid,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("appid", appid);
        params.put("companyId", SecurityUtils.getLoginUser().getCompany().getCompanyId());

        PageHelper.startPage(pageNum, pageSize);
        List<FsCoursePlaySourceConfigVO> list = fsCoursePlaySourceConfigService.selectCoursePlaySourceConfigVOListByMap(params);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('course:playSourceConfig:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        FsCoursePlaySourceConfig config = fsCoursePlaySourceConfigService.getById(id);
        if (Objects.isNull(config)) {
            return AjaxResult.success(null);
        }

        FsCoursePlaySourceConfigVO configVO = new FsCoursePlaySourceConfigVO();
        BeanUtils.copyProperties(config, configVO);
        return AjaxResult.success(configVO);
    }

    @PreAuthorize("@ss.hasPermi('course:playSourceConfig:add')")
    @Log(title = "点播播放源配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody FsCoursePlaySourceConfigCreateParam param) {
        Wrapper<FsCoursePlaySourceConfig> queryWrapper = Wrappers.<FsCoursePlaySourceConfig>lambdaQuery()
                .eq(FsCoursePlaySourceConfig::getAppid, param.getAppid())
                .eq(FsCoursePlaySourceConfig::getIsDel, 0);
        if (fsCoursePlaySourceConfigService.count(queryWrapper) > 0) {
            return AjaxResult.error("appid已存在");
        }

        FsCoursePlaySourceConfig config = new FsCoursePlaySourceConfig();
        BeanUtils.copyProperties(param, config);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        config.setCompanyId(loginUser.getCompany().getCompanyId());
        config.setCompanyUserId(loginUser.getUser().getUserId());
        config.setIsDel(0);
        config.setCreateTime(LocalDateTime.now());
        config.setUpdateTime(LocalDateTime.now());
        fsCoursePlaySourceConfigService.save(config);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('course:playSourceConfig:edit')")
    @Log(title = "点播播放源配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody FsCoursePlaySourceConfigEditParam param) {
        FsCoursePlaySourceConfig config = fsCoursePlaySourceConfigService.getById(param.getId());
        if (Objects.isNull(config)) {
            return AjaxResult.error("点播播放源配置不存在");
        }

        Wrapper<FsCoursePlaySourceConfig> queryWrapper = Wrappers.<FsCoursePlaySourceConfig>lambdaQuery()
                .eq(FsCoursePlaySourceConfig::getAppid, param.getAppid())
                .eq(FsCoursePlaySourceConfig::getIsDel, 0)
                .last("limit 1");
        FsCoursePlaySourceConfig one = fsCoursePlaySourceConfigService.getOne(queryWrapper);
        if (Objects.nonNull(one) && !one.getId().equals(config.getId())) {
            return AjaxResult.error("appid已存在");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!loginUser.getCompany().getCompanyId().equals(config.getCompanyId())) {
            return AjaxResult.error("非法操作");
        }

        BeanUtils.copyProperties(param, config);
        fsCoursePlaySourceConfigService.updateById(config);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('course:playSourceConfig:remove')")
    @Log(title = "点播播放源配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Wrapper<FsCoursePlaySourceConfig> updateWrapper = Wrappers.<FsCoursePlaySourceConfig>lambdaUpdate()
                .set(FsCoursePlaySourceConfig::getIsDel, 1)
                .eq(FsCoursePlaySourceConfig::getCompanyId, loginUser.getCompany().getCompanyId())
                .in(FsCoursePlaySourceConfig::getId, Arrays.asList(ids));
        fsCoursePlaySourceConfigService.update(updateWrapper);
        return AjaxResult.success();
    }

    /**
     * 启用-关闭小程序销售管理
     * @param bock
     * @return
     */
    @GetMapping("/updateIsTownOn")
    public R queryIsTownOn(String bock, String appId)
    {
        String key = appId+"start_status_001";
        String start = redisCache.getCacheObject(key);
        if (ObjectUtil.isNotEmpty(bock)){
            if (bock.equals("001")){
                redisCache.setCacheObject(key,bock);
                return R.ok("调整成功");
            }else if (bock.equals("002")){
                redisCache.setCacheObject(key,bock);
                return R.ok("调整成功");
            }

        }
        return R.ok().put("date",start);
    }
}
