package com.ruoyi.ibs.dashboard.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ibs.dashboard.domain.LscjSysuser;
import com.ruoyi.ibs.dashboard.domain.vo.LscjSysuserVo;
import com.ruoyi.ibs.dashboard.mapper.LscjSysuserMapper;
import com.ruoyi.ibs.dashboard.service.ILscjSysuserService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2025-08-04
 */
@RestController
@RequestMapping("/system/lscjSysuser")
public class LscjSysuserController extends BaseController
{
    @Autowired
    private ILscjSysuserService lscjSysuserService;

    @Value("${ruoyi.downloadProductManualPath}")
    private String downloadProductManualPath;


    @Autowired
    private ISysDeptService iSysDeptService;

    @Resource
    private ISysUserService sysUserService;

    @Autowired
    private LscjSysuserMapper lscjSysuserMapper;

    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询列表")
    public LscjSysuserVo list(LscjSysuser lscjSysuser)
    {
        LscjSysuserVo vo = new LscjSysuserVo();
        vo.setRows(lscjSysuserService.selectLscjSysuserList(lscjSysuser));
        vo.setTotal(lscjSysuserService.selectLscjSysuserListCount(lscjSysuser));
        return  vo;

    }



    /**
     * 新增【请填写功能名称】
     */

    @ApiOperation("导入")
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file)
    {
        ExcelUtil<LscjSysuser> util = new ExcelUtil<>(LscjSysuser.class);
        List<LscjSysuser> customersList = new ArrayList<>();
        try {
            customersList = util.importExcel(file.getInputStream());
        } catch (Exception e) {
            return AjaxResult.error("文件内容有误");
        }
        if(customersList == null || customersList.size()==0){
            return AjaxResult.error("文件内容为空");
        }

        for (LscjSysuser lscjSysuser : customersList) {
            if(StringUtils.isEmpty(lscjSysuser.getUserId())){
                return AjaxResult.error("柜员号不能为空");
            }
            LambdaQueryWrapper<LscjSysuser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LscjSysuser::getUserId,lscjSysuser.getUserId());
            if (lscjSysuserMapper.selectCount(queryWrapper) > 0){
                continue;
            }
            SysUser sysUser = sysUserService.selectUserByUserName(lscjSysuser.getUserId());
            if (Objects.isNull(sysUser)){
                return AjaxResult.error("柜员不存在");
            }
            lscjSysuser.setId(UUID.randomUUID().toString());
            lscjSysuser.setOrgId(sysUser.getDeptId().toString());
            lscjSysuser.setCreateTime(new Date());
            lscjSysuser.setBelongDeptId(SecurityUtils.getDeptId().toString());

//            LscjSysuser lscjSysuser1 = new LscjSysuser();
//            lscjSysuser1.setUserId(lscjSysuser.getUserId());
//            lscjSysuser1.setOrgId(String.valueOf(SecurityUtils.getDeptId()/1000*1000));
//            lscjSysuser1.setLevel(lscjSysuser.getLevel());
//            lscjSysuser1.setSize(100);
//            List<LscjSysuser> lscjSysusers = lscjSysuserService.selectLscjSysuserList(lscjSysuser1);
////            if(lscjSysusers.size()>0){
////                return AjaxResult.error("层级数据重复！");
////            }
//            lscjSysuser.setId(String.valueOf(UUID.randomUUID()));
//            Long org3=(SecurityUtils.getDeptId()/1000);
//            lscjSysuser.setId(UUID.randomUUID().toString());
//            lscjSysuser.setBelongDeptId(String.valueOf(SecurityUtils.getDeptId()/1000*1000));
//            lscjSysuser.setOrgId( iSysDeptService.deptLevelId(lscjSysuser.getUserId(),"0".equalsIgnoreCase(lscjSysuser.getLevel())?
//                    "head":"1".equalsIgnoreCase(lscjSysuser.getLevel())?"branch":"outlet"));
//            lscjSysuser.setLevel(LevelEnum.getDescriptionByCode(lscjSysuser.getLevel()));
//            if(!StringUtils.isNotEmpty(lscjSysuser.getUserId())){
//                return AjaxResult.error("柜员有误不能为空");
//            }
//
//
            lscjSysuserService.insertLscjSysuser(lscjSysuser);
        }
        return AjaxResult.success();

    }

    /**
     * 修改【请填写功能名称】
     */

    @PutMapping
    @ApiOperation(value = "编辑")
    public AjaxResult edit(@RequestBody LscjSysuser lscjSysuser)
    {
        if(!StringUtils.isNotEmpty(lscjSysuser.getUserId())){
            return AjaxResult.error("柜员有误不能为空");
        }
        SysUser sysUser = sysUserService.selectUserByUserName(lscjSysuser.getUserId());
        if (Objects.isNull(sysUser)){
            return AjaxResult.error("柜员不存在");
        }
        lscjSysuser.setOrgId(sysUser.getDeptId().toString());
//        lscjSysuser.setBelongDeptId( iSysDeptService.deptLevelId(lscjSysuser.getUserId(),"0".equalsIgnoreCase(lscjSysuser.getLevel())?
//                "head":"1".equalsIgnoreCase(lscjSysuser.getLevel())?"branch":"outlet"));
        lscjSysuser.setBelongDeptId(SecurityUtils.getDeptId().toString());
        lscjSysuser.setCreateTime(new Date());
        return toAjax(lscjSysuserService.updateLscjSysuser(lscjSysuser));
    }

    /**
     * 删除【请填写功能名称】
     */

	@DeleteMapping("/{ids}")
    @ApiOperation(value = "删除")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(lscjSysuserService.deleteLscjSysuserByIds(ids));
    }


    @ApiOperation(value = "模板下载", notes = "模板下载")
    @PostMapping("/export")
    public ResponseEntity<?> export()
    {

        Path filePath = Paths.get(downloadProductManualPath, "shishimoban.xlsx");

        // 验证文件是否存在且是.doc文件
        if (!Files.exists(filePath) || Files.isDirectory(filePath)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件不存在");
        }
        String docName = "层级设置模板";

        try {
            // 设置响应头
            ContentDisposition contentDisposition = ContentDisposition
                    .attachment()
                    .filename(docName)
                    .build();

            // 打开文件输入流
            InputStream inputStream = Files.newInputStream(filePath);

            return ResponseEntity.ok()
                    .headers(headers -> headers.setContentDisposition(contentDisposition))
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(Files.size(filePath))
                    .body(new InputStreamResource(inputStream));
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("下载文件时出错: " + e.getMessage());
        }
    }

}
