package com.maintain.business.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.maintain.business.domain.ErpCar;
import com.maintain.business.domain.ErpClient;
import com.maintain.business.domain.bo.ErpClientBo;
import com.maintain.business.domain.vo.ErpClientVo;
import com.maintain.business.listener.ErpClientImportListener;
import com.maintain.business.mapper.ErpCarMapper;
import com.maintain.business.mapper.ErpClientMapper;
import com.maintain.business.service.IErpClientService;
import com.maintain.common.annotation.Log;
import com.maintain.common.annotation.RepeatSubmit;
import com.maintain.common.core.controller.BaseController;
import com.maintain.common.core.domain.PageQuery;
import com.maintain.common.core.domain.R;
import com.maintain.common.core.page.TableDataInfo;
import com.maintain.common.core.validate.AddGroup;
import com.maintain.common.core.validate.EditGroup;
import com.maintain.common.enums.BusinessType;
import com.maintain.common.excel.ExcelResult;
import com.maintain.common.exception.ServiceException;
import com.maintain.common.utils.poi.ExcelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 客户信息-客户
 *
 * @author liushuai
 * @date 2025-03-25
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/client")
public class ErpClientController extends BaseController {

    private final IErpClientService iErpClientService;
    private final ErpClientMapper clientMapper;
    private final ErpCarMapper carMapper;

    /**
     * 查询客户信息-客户列表
     */
    @SaCheckPermission("business:client:list")
    @GetMapping("/list")
    public TableDataInfo<ErpClientVo> list(ErpClientBo bo, PageQuery pageQuery) {
        return iErpClientService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询客户信息-客户列表
     */
    @GetMapping("/listAll")
    public R<List<ErpClientVo>> list(ErpClientBo bo) {
        return R.ok(iErpClientService.queryList(bo));
    }

    /**
     * 客户信息-客户导入模板下载
     */
    @PostMapping("/importTemplate")
    public void importTemplate(ErpClientBo bo, HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "客户信息-客户", ErpClientVo.class, response);
    }

    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "单位管理", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<ErpClientVo> result = ExcelUtil.importExcel(file.getInputStream(), ErpClientVo.class, new ErpClientImportListener(updateSupport));
        return R.ok(result.getAnalysis());
    }

    /**
     * 导出客户信息-客户列表
     */
    @SaCheckPermission("business:client:export")
    @Log(title = "客户信息-客户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ErpClientBo bo, HttpServletResponse response) {
        List<ErpClientVo> list = iErpClientService.queryList(bo);
        ExcelUtil.exportExcel(list, "客户信息", ErpClientVo.class, response);
    }

    /**
     * 获取客户信息-客户详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("business:client:query")
    @GetMapping("/{id}")
    public R<ErpClientVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iErpClientService.queryById(id));
    }

    /**
     * 新增客户信息-客户
     */
    @SaCheckPermission("business:client:add")
    @Log(title = "客户信息-客户", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ErpClientBo bo) {
        return toAjax(iErpClientService.insertByBo(bo));
    }

    /**
     * 修改客户信息-客户
     */
    @SaCheckPermission("business:client:edit")
    @Log(title = "客户信息-客户", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ErpClientBo bo) {
        return toAjax(iErpClientService.updateByBo(bo));
    }

    /**
     * 删除客户信息-客户
     *
     * @param ids 主键串
     */
    @SaCheckPermission("business:client:remove")
    @Log(title = "客户信息-客户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        LambdaQueryWrapper<ErpCar> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.in(ErpCar::getClientId, Arrays.asList(ids));
        if (!carMapper.selectList(lambdaQuery).isEmpty()) {
            throw new ServiceException("客户已绑定车辆，无法删除！");
        }
        // 状态更改为注销
        LambdaUpdateWrapper<ErpClient> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(ErpClient::getId, Arrays.asList(ids)).set(ErpClient::getState, 1);
        return toAjax(clientMapper.update(updateWrapper));
    }
}
