package com.yami.shop.platform.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.param.OrderRefundStaisticsParam;
import com.yami.shop.bean.po.EnterpriseUserLogPo;
import com.yami.shop.bean.po.EnterpriseUserPo;
import com.yami.shop.bean.vo.EnterpriseUserVo;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.UserService;
import com.yami.shop.sys.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/admin/enterprise")
public class UserEnterpriseController {

    @Autowired
    private UserService userService;
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/downloadErrorExcel")
    @ApiOperation("导出失败记录")
    public R<Void> downloadErrorExcel(HttpServletResponse response,String batchNo) {
        userService.downloadErrorExcel(response,batchNo);
        return R.SUCCESS();
    }


    @SneakyThrows
    @GetMapping("/downloadXlsx")
    @ApiOperation("下载导入企业员工模板(示例版)")
    public R<Void> downloadZip(HttpServletResponse response) {
        response.sendRedirect("https://zswl-shop.oss-cn-chengdu.aliyuncs.com/2025/10/da9bf7eb40ad4cd6ba2566c13b5ba8d4.xlsx");
        return R.SUCCESS();
    }

    @GetMapping("/downloadExcel")
    @ApiOperation("下载导入企业员工模板(无示例版)")
    public R<Void> downloadExcelGoods(HttpServletResponse response) {
        userService.downloadExcelGoods(response);
        return R.SUCCESS();
    }

    @ApiOperation("导入企业员工")
    @PostMapping("/uploadExcelGoods")
    public R<Void> downloadExcelGoods(MultipartFile file) {
        userService.uploadExcelGoods(file, SecurityUtils.getSysUser().getUsername());
        return R.SUCCESS();
    }

    @ApiOperation("员工列表")
    @GetMapping("/enterpriseUserList")
    public R<IPage<EnterpriseUserVo>> enterpriseUserList(EnterpriseUserPo po, PageParam<EnterpriseUserPo> page) {
        getEnterpriseUserPo(po);
        IPage<EnterpriseUserVo> userPage =  userService.enterpriseUserList(page,po);
        return R.SUCCESS(userPage);
    }

    @GetMapping("/enterpriseUserLogList")
    @ApiOperation("员工导入记录")
    public R<IPage<EnterpriseUserLogPo>> enterpriseUserLogList(PageParam<EnterpriseUserLogPo> page) {
        IPage<EnterpriseUserLogPo> logList =  userService.enterpriseUserLogList(page);
        return R.SUCCESS(logList);
    }

    @PostMapping("/addUser")
    @ApiOperation("新增企业员工")
    public R<Void> addUser(@RequestBody EnterpriseUserPo po) {
        userService.addUser2(po);
        return R.SUCCESS();
    }

    @ApiOperation("删除员工")
    @DeleteMapping("/deleteUserById")
    public R<Void> deleteUserById(String userId) {
        userService.removeById(userId);
        return R.SUCCESS();
    }

    @GetMapping("/info/{userId}")
    public R<User> info(@PathVariable("userId") String userId) {
        return R.SUCCESS(userService.getById(userId));
    }

    @PutMapping
    public R<Void> update(@RequestBody User user) {
        User updateUser = new User();
        updateUser.setModifyTime(new Date());
        updateUser.setRealName(user.getRealName());
        updateUser.setUserName(user.getUserMobile());
        updateUser.setUserMobile(user.getUserMobile());
        updateUser.setChannelId(user.getChannelId());
        updateUser.setUserId(user.getUserId());
        updateUser.setStatus(user.getStatus());
        updateUser.setUserAttrType(user.getUserAttrType());
        userService.updateById(updateUser);
        return R.SUCCESS();
    }


    /**
     * 导出
     * @param po
     * @param response
     */
    @GetMapping("/export")
    @ApiOperation("后管端-用户列表导出")
    public void export(EnterpriseUserPo po, HttpServletResponse response) {
        getEnterpriseUserPo(po);
        userService.export(po,response);
    }

    private void getEnterpriseUserPo(EnterpriseUserPo po){
        if (po.getChannelIdList()==null||po.getChannelIdList().isEmpty()){
            throw new GlobalException("请求参数-所属企业不允许为空");
        }
        if (ObjectUtil.isEmpty(po.getUserAttrType())){
            po.setUserAttrType("1");//默认查询正常人员属性
        }
        if (po.getChannelIdList().contains(0L)){
            Long userId = null;
            try {
                userId = SecurityUtils.getSysUser().getUserId();
            } catch (Exception e) {
                throw new GlobalException("获取当前登录用户失败");
            }
            List<Long> channelIdList =  sysUserService.findByUserIdListId(userId);
            po.setChannelIdList(channelIdList);
            if (userId != Constant.SUPER_ADMIN_ID&&(po.getChannelIdList()==null||po.getChannelIdList().isEmpty())){
                List<Long> longs = new ArrayList<>();
                longs.add(0L);
                po.setChannelIdList(longs);
            }
        }
    }
}
