package com.bs.ct.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.bs.common.utils.SecurityUtils;
import com.bs.common.utils.StringUtils;
import com.bs.ct.domain.CtGalleryShareUser;
import com.bs.ct.service.ICtGalleryShareUserService;
import com.bs.system.service.ISysDeptService;
import com.bs.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.ct.domain.CtGalleryCataShare;
import com.bs.ct.service.ICtGalleryCataShareService;
import javax.annotation.Resource;

/**
 * 图库目录共享Controller
 *
 * @author bs
 * @date 2025-02-22
 */
@Api(tags = "图库目录共享")
@RestController
@RequestMapping("/gallery/cata/share")
public class CtGalleryCataShareController extends BaseController {
    @Resource
    private ICtGalleryCataShareService ctGalleryCataShareService;

    @Resource
    private ICtGalleryShareUserService ctGalleryShareUserService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysDeptService sysDeptService;
    /**
     * 分页查询图库目录共享列表
     */
    @ApiOperation("分页查询图库目录共享列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CtGalleryCataShare ctGalleryCataShare) {
        startPage();
        LambdaQueryWrapper<CtGalleryCataShare> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctGalleryCataShare);
        List<CtGalleryCataShare> list = ctGalleryCataShareService.list(queryWrapper);
        if ("mine".equals(ctGalleryCataShare.getQueryType())) {
            list = getShareUser(list);
        }
        return getDataTable(list);
    }

    /**
     * 查询图库目录共享列表
     */
    @ApiOperation("查询图库目录共享列表")
    @GetMapping("/list")
    public AjaxResult list(CtGalleryCataShare ctGalleryCataShare) {
        LambdaQueryWrapper<CtGalleryCataShare> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctGalleryCataShare);
        List<CtGalleryCataShare> list = ctGalleryCataShareService.list(queryWrapper);
        if ("mine".equals(ctGalleryCataShare.getQueryType())) {
            list = getShareUser(list);
        }
        return success(list);
    }

    private List<CtGalleryCataShare> getShareUser(List<CtGalleryCataShare> list) {
        List<Long> ids = new ArrayList<>();
        Map<Long, List<CtGalleryShareUser>> dataMap = new HashMap<>();
        if (null != list && list.size() > 0) {
            for (CtGalleryCataShare share : list) {
                ids.add(share.getId());
            }
            List<CtGalleryShareUser> lsUser = ctGalleryShareUserService.list(new LambdaQueryWrapper<CtGalleryShareUser>().in(CtGalleryShareUser::getShareId, ids));
            if (null != lsUser && lsUser.size() > 0) {
                for (CtGalleryShareUser user : lsUser) {
                    List<CtGalleryShareUser> lsShareUser = dataMap.get(user.getShareId());
                    if (null == lsShareUser) {
                        lsShareUser = new ArrayList<>();
                    }
                    if (null != user.getUserId()) {
                        if ("user".equals(user.getUserType())) {
                            user.setUser(sysUserService.selectUserById(user.getUserId()));
                        } else if ("dept".equals(user.getUserType())) {
                            user.setDept(sysDeptService.selectDeptById(user.getUserId()));
                        }
                    }
                    lsShareUser.add(user);
                    dataMap.put(user.getShareId(), lsShareUser);
                }
            }
            for (CtGalleryCataShare share : list) {
                share.setLsUsers(dataMap.get(share.getId()));
            }
        }
        return list;
    }

    /**
     * 导出图库目录共享列表
     */
    @ApiOperation("导出图库目录共享列表")
    @Log(title = "图库目录共享导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CtGalleryCataShare ctGalleryCataShare) {
        LambdaQueryWrapper<CtGalleryCataShare> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctGalleryCataShare);
        List<CtGalleryCataShare> list = ctGalleryCataShareService.list(queryWrapper);
        ExcelUtil<CtGalleryCataShare> util = new ExcelUtil<CtGalleryCataShare>(CtGalleryCataShare. class);
        util.exportExcel(response, list, "图库目录共享数据");
    }

    /**
     * 获取图库目录共享详细信息
     */
    @ApiOperation("获取图库目录共享详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ctGalleryCataShareService.getById(id));
    }

    /**
     * 新增图库目录共享
     */
    @ApiOperation("新增图库目录共享")
    @Log(title = "图库目录共享新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CtGalleryCataShare ctGalleryCataShare) {
        if (null != ctGalleryCataShare) {
            if (StringUtils.isEmpty(ctGalleryCataShare.getType())) {
                return warn("请选择需要共享的类型");
            }
            if (null == ctGalleryCataShare.getCataIds() || ctGalleryCataShare.getCataIds().size() == 0) {
                return warn("请选择需要共享的图片/目录");
            }
            if (StringUtils.isEmpty(ctGalleryCataShare.getUserType())) {
                return warn("请选择需要共享的用户类型");
            }
            if (null == ctGalleryCataShare.getUserIds() || ctGalleryCataShare.getUserIds().size() == 0) {
                return warn("请选择需要共享的部门/人员");
            }
            for (Long cataId : ctGalleryCataShare.getCataIds()) {
                for (Long userId : ctGalleryCataShare.getUserIds()) {
                    // 判断是否有重复共享
                    LambdaQueryWrapper<CtGalleryCataShare> queryWrapper = new LambdaQueryWrapper();
                    queryWrapper.eq(CtGalleryCataShare::getType, ctGalleryCataShare.getType());
                    queryWrapper.eq(CtGalleryCataShare::getCataId, cataId);
                    List<CtGalleryCataShare> lsData = ctGalleryCataShareService.list(queryWrapper);
                    Long shareId = -1L;
                    if (null != lsData && lsData.size() > 0) {
                        shareId = lsData.get(0).getId();
                    } else {
                        // 未共享，则生成共享数据
                        CtGalleryCataShare share = new CtGalleryCataShare();
                        share.setType(ctGalleryCataShare.getType());
                        share.setCataId(cataId);
                        share.setCataName(ctGalleryCataShare.getCataName());
                        ctGalleryCataShareService.save(share);
                        shareId = share.getId();
                    }
                    if (shareId > 0) {
                        //queryWrapper.inSql(CtGalleryCataShare::getId, "select share_id from ct_gallery_share_user where type='" + ctGalleryCataShare.getUserType() + "' and user_id =" + userId);
                        // 如果有数据，则先删除旧数据
                        LambdaQueryWrapper<CtGalleryShareUser> userWrapper = new LambdaQueryWrapper();
                        userWrapper.eq(CtGalleryShareUser::getShareId, shareId);
                        userWrapper.eq(CtGalleryShareUser::getUserId, userId);
                        userWrapper.eq(CtGalleryShareUser::getUserType, ctGalleryCataShare.getUserType());
                        ctGalleryShareUserService.remove(userWrapper);
                        // 插入新数据
                        CtGalleryShareUser user = new CtGalleryShareUser();
                        user.setUserType(ctGalleryCataShare.getUserType());
                        user.setUserId(userId);
                        user.setShareId(shareId);
                        user.setBeginDate(ctGalleryCataShare.getBeginDate());
                        user.setEndDate(ctGalleryCataShare.getEndDate());
                        ctGalleryShareUserService.save(user);
                    }
                }
            }
        } else {
            return error("请选择需要共享的图片/目录");
        }
        return toAjax(ctGalleryCataShareService.save(ctGalleryCataShare));
    }

    /**
     * 修改图库目录共享
     */
    @ApiOperation("修改图库目录共享")
    @Log(title = "图库目录共享修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CtGalleryCataShare ctGalleryCataShare) {
        return toAjax(ctGalleryCataShareService.updateById(ctGalleryCataShare));
    }

    /**
     * 删除图库目录共享
     */
    @ApiOperation("删除图库目录共享")
    @Log(title = "图库目录共享删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        LambdaQueryWrapper<CtGalleryShareUser> userWrapper = new LambdaQueryWrapper();
        userWrapper.in(CtGalleryShareUser::getShareId, ids);
        ctGalleryShareUserService.remove(userWrapper);
        return toAjax(ctGalleryCataShareService.removeBatchByIds(ids));
    }

    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<CtGalleryCataShare> queryWrapper,CtGalleryCataShare ctGalleryCataShare){
        queryWrapper.orderByAsc(CtGalleryCataShare::getType);
        if ("mine".equals(ctGalleryCataShare.getQueryType())) {
            // 查询自己共享给别人的数据
            queryWrapper.eq(CtGalleryCataShare::getCreateBy, SecurityUtils.getUserId());
        } else if ("other".equals(ctGalleryCataShare.getQueryType())) {
            // 查询他人共享给本用户的数据
            queryWrapper.inSql(CtGalleryCataShare::getId, "select share_id from ct_gallery_share_user where del_flag = 0 and ( (user_type = 'user' and user_id = " + SecurityUtils.getUserId() +") or (user_type = 'dept' and user_id = " + SecurityUtils.getDeptId() + ") and ifnull(end_date,date(sysdate())) >= date(sysdate()) )");
        }

        //id
        if(Validator.isNotEmpty(ctGalleryCataShare.getId())){
            queryWrapper.eq(CtGalleryCataShare::getId,ctGalleryCataShare.getId());
        }

        //共享类型目录共享、图片共享
        if(Validator.isNotEmpty(ctGalleryCataShare.getType())){
            queryWrapper.eq(CtGalleryCataShare::getType,ctGalleryCataShare.getType());
        }

        if(Validator.isNotEmpty(ctGalleryCataShare.getCataName())) {
            queryWrapper.like(CtGalleryCataShare::getCataName, ctGalleryCataShare.getCataName());
        }

        //目录id
        if(Validator.isNotEmpty(ctGalleryCataShare.getCataId())){
            queryWrapper.eq(CtGalleryCataShare::getCataId,ctGalleryCataShare.getCataId());
        }

        //共享用户
        if(Validator.isNotEmpty(ctGalleryCataShare.getUserId())){
            queryWrapper.eq(CtGalleryCataShare::getUserId,ctGalleryCataShare.getUserId());
        }

        //开始时间
        if(Validator.isNotEmpty(ctGalleryCataShare.getBeginDate())){
            queryWrapper.eq(CtGalleryCataShare::getBeginDate,ctGalleryCataShare.getBeginDate());
        }

        //结束时间
        if(Validator.isNotEmpty(ctGalleryCataShare.getEndDate())){
            queryWrapper.eq(CtGalleryCataShare::getEndDate,ctGalleryCataShare.getEndDate());
        }

        //备注
        if(Validator.isNotEmpty(ctGalleryCataShare.getRemarks())){
            queryWrapper.eq(CtGalleryCataShare::getRemarks,ctGalleryCataShare.getRemarks());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(ctGalleryCataShare.getDelFlag())){
            queryWrapper.eq(CtGalleryCataShare::getDelFlag,ctGalleryCataShare.getDelFlag());
        }

        //创建部门
        if(Validator.isNotEmpty(ctGalleryCataShare.getCreateDept())){
            queryWrapper.eq(CtGalleryCataShare::getCreateDept,ctGalleryCataShare.getCreateDept());
        }

        //创建人
        if(Validator.isNotEmpty(ctGalleryCataShare.getCreateBy())){
            queryWrapper.eq(CtGalleryCataShare::getCreateBy,ctGalleryCataShare.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(ctGalleryCataShare.getCreateTime())){
            queryWrapper.eq(CtGalleryCataShare::getCreateTime,ctGalleryCataShare.getCreateTime());
        }

        //修改人
        if(Validator.isNotEmpty(ctGalleryCataShare.getUpdateBy())){
            queryWrapper.eq(CtGalleryCataShare::getUpdateBy,ctGalleryCataShare.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(ctGalleryCataShare.getUpdateTime())){
            queryWrapper.eq(CtGalleryCataShare::getUpdateTime,ctGalleryCataShare.getUpdateTime());
        }

        //租户ID
        if(Validator.isNotEmpty(ctGalleryCataShare.getTenantId())){
            queryWrapper.eq(CtGalleryCataShare::getTenantId,ctGalleryCataShare.getTenantId());
        }

        }

}
