package com.fs.company.controller.qw;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.core.domain.R;
import com.fs.common.utils.ServletUtils;
import com.fs.framework.security.LoginUser;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsCoursePlaySourceConfig;
import com.fs.course.service.IFsCoursePlaySourceConfigService;
import com.fs.course.utils.FsCoursePlaySourceConfigQuery;
import com.fs.framework.service.TokenService;
import com.fs.qw.vo.QwOptionsVO;
import com.fs.system.service.ISysConfigService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.service.IQwCompanyService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;

/**
 * 企微主体Controller
 *
 * @author fs
 * @date 2024-10-09
 */
@RestController
@RequestMapping("/qw/qwCompany")
public class QwCompanyController extends BaseController
{
    @Autowired
    private IQwCompanyService qwCompanyService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IFsCoursePlaySourceConfigService coursePlaySourceConfigService;

    /**
     * 查询企微主体列表（仅查询登录公司下的主体）
     */
    @PreAuthorize("@ss.hasPermi('qw:qwCompany:list')")
    @GetMapping("/list")
    public TableDataInfo list(QwCompany qwCompany)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 只查询登录公司下的主体
        if (loginUser != null && loginUser.getCompany() != null && loginUser.getCompany().getCompanyId() != null) {
            qwCompany.setCompanyIds(String.valueOf(loginUser.getCompany().getCompanyId()));
        }
        List<QwCompany> list = qwCompanyService.selectQwCompanyList(qwCompany);
        return getDataTable(list);
    }


    @GetMapping("/all")
    public R all()
    {
        Long userId = null;
        Long deptId = null;
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = json != null ? JSONUtil.toBean(json, CourseConfig.class) : null;
        boolean isAdmin = loginUser != null && loginUser.getUser() != null && loginUser.getUser().isAdmin();
        if (!isAdmin && config != null) {
            if (Boolean.TRUE.equals(config.getDept())) {
                deptId = loginUser.getUser() != null ? loginUser.getUser().getDeptId() : null;
            } else {
                userId = loginUser.getUser() != null ? loginUser.getUser().getUserId() : null;
            }
        }
        List<QwOptionsVO> list = qwCompanyService.selectQwCompanyListOptionsVO(userId, deptId);
        return R.ok().put("data", list);
    }
    /**
     * 导出企微主体列表
     */
    @PreAuthorize("@ss.hasPermi('qw:qwCompany:export')")
    @Log(title = "企微主体", businessType = BusinessType.EXPORT, isStoreLog = true)
    @GetMapping("/export")
    public AjaxResult export(QwCompany qwCompany)
    {
        List<QwCompany> list = qwCompanyService.selectQwCompanyList(qwCompany);
        ExcelUtil<QwCompany> util = new ExcelUtil<QwCompany>(QwCompany.class);
        return util.exportExcel(list, "企微主体数据");
    }

    /**
     * 获取企微主体详细信息
     */
    @PreAuthorize("@ss.hasPermi('qw:qwCompany:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(qwCompanyService.selectQwCompanyById(id));
    }

    /**
     * 新增企微主体
     */
    @PreAuthorize("@ss.hasPermi('qw:qwCompany:add')")
    @Log(title = "企微主体", businessType = BusinessType.INSERT, isStoreLog = true)
    @PostMapping
    public AjaxResult add(@RequestBody QwCompany qwCompany)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser.getUser() != null) {
            qwCompany.setCreateUserId(loginUser.getUser().getUserId());
            qwCompany.setCreateDeptId(loginUser.getUser().getDeptId());
        }
        return toAjax(qwCompanyService.insertQwCompany(qwCompany));
    }

    /**
     * 修改企微主体
     */
    @PreAuthorize("@ss.hasPermi('qw:qwCompany:edit')")
    @Log(title = "企微主体", businessType = BusinessType.UPDATE, isStoreLog = true)
    @PutMapping
    public AjaxResult edit(@RequestBody QwCompany qwCompany)
    {
        return toAjax(qwCompanyService.updateQwCompany(qwCompany));
    }


    /**
     * 批量更换勾选主体的小程序
     */
    @Log(title = "批量更换小程序", businessType = BusinessType.UPDATE)
    @PostMapping("/batchUpdateMiniAppId")
    public R batchUpdateMiniAppId(@RequestBody QwCompany qwCompany)
    {
        if (qwCompany.getMiniAppId() == null || qwCompany.getMiniAppId().trim().isEmpty()) {
            return R.error("请选择小程序");
        }
        if (qwCompany.getIds() == null || qwCompany.getIds().length == 0) {
            return R.error("请至少勾选一个企业微信主体");
        }
        return qwCompanyService.batchUpdateMiniAppId(qwCompany.getMiniAppId(), qwCompany.getIds());
    }

    /**
     * 获取小程序配置列表
     */
    @GetMapping("/getMiniAppList")
    public R getMiniAppList()
    {
        QueryWrapper<FsCoursePlaySourceConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 1);
        queryWrapper.eq("is_del", 0);
        FsCoursePlaySourceConfigQuery.excludeBanned(queryWrapper);
        queryWrapper.orderByDesc("create_time");

        List<FsCoursePlaySourceConfig> configs = coursePlaySourceConfigService.list(queryWrapper);
        if (configs == null || configs.isEmpty()) {
            return R.ok().put("data", new ArrayList<>());
        }
        List<Map<String, String>> list = new ArrayList<>();
        for (FsCoursePlaySourceConfig config : configs) {
            if (config.getAppid() != null && !config.getAppid().trim().isEmpty()) {
                Map<String, String> map = new HashMap<>();
                map.put("label", config.getName() != null ? config.getName() : config.getAppid());
                map.put("value", config.getAppid());
                list.add(map);
            }
        }

        return R.ok().put("data", list);
    }

    /**
     * 删除企微主体
     */
    @PreAuthorize("@ss.hasPermi('qw:qwCompany:remove')")
    @Log(title = "企微主体", businessType = BusinessType.DELETE, isStoreLog = true)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(qwCompanyService.deleteQwCompanyByIds(ids));
    }
}
