package com.bs.jxc.controller;

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

import com.bs.jxc.domain.CkCargoStock;
import com.bs.jxc.domain.CmCargo;
import com.bs.jxc.service.ICkCargoStockService;
import com.bs.jxc.service.ICmCargoService;
import com.bs.jxc.service.ICmStockService;
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.jxc.domain.CmCust;
import com.bs.jxc.service.ICmCustService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 客户信息Controller
 *
 * @author bs
 * @date 2023-07-10
 */
@Api(tags = "客户信息")
@RestController
@RequestMapping("/jxc/cust")
public class CmCustController extends BaseController {
    @Resource
    private ICmCustService cmCustService;


    /**
     * 分页查询客户信息列表
     */
    @ApiOperation("分页查询客户信息列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CmCust cmCust) {
        startPage();
        LambdaQueryWrapper<CmCust> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmCust);
        List<CmCust> list = cmCustService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询客户信息列表
     */
    @ApiOperation("查询客户信息列表")
    @GetMapping("/list")
    public AjaxResult list(CmCust cmCust) {
        LambdaQueryWrapper<CmCust> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmCust);
        List<CmCust> list = cmCustService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出客户信息列表
     */
    @ApiOperation("导出客户信息列表")
    @Log(title = "客户信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmCust cmCust) {
        LambdaQueryWrapper<CmCust> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmCust);
        List<CmCust> list = cmCustService.list(queryWrapper);
        ExcelUtil<CmCust> util = new ExcelUtil<CmCust>(CmCust. class);
        util.exportExcel(response, list, "客户信息数据");
    }
    @Log(title = "客户信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) {
        try {
            ExcelUtil<CmCust> util = new ExcelUtil<>(CmCust.class);
            List<CmCust> custList = util.importExcel(file.getInputStream());

            // 创建 LambdaQueryWrapper 对象
            LambdaQueryWrapper<CmCust> queryWrapper = new LambdaQueryWrapper<>();

            // 根据具体需求进行导入操作
            for (CmCust cust : custList) {
                // 按照业务需求构建查询条件
                queryWrapper.eq(CmCust::getId, cust.getId()); // 示例：根据 ID 判断是否存在

                // 查询数据库中是否已存在相同记录
                Long count = cmCustService.count(queryWrapper);

                if (count > 0) {
                    // 如果已存在记录，则进行更新操作
                    cmCustService.update(cust, queryWrapper);
                } else {
                    // 如果不存在记录，则进行插入操作
                    cmCustService.save(cust);
                }
            }

            return AjaxResult.success("导入成功");
        } catch (Exception e) {
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    @ApiOperation("导入客户信息列表模板")
    @Log(title = "导入客户信息模板", businessType = BusinessType.EXPORT)
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response, CmCust cmCust) {
        // 创建一个空的客户信息列表
        List<CmCust> emptyList = new ArrayList<>();

        // 导出空列表为 Excel 文件
        ExcelUtil<CmCust> util = new ExcelUtil<>(CmCust.class);
        util.exportExcel(response, emptyList, "客户信息模板");
    }


    /**
     * 获取客户信息详细信息
     */
    @ApiOperation("获取客户信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(cmCustService.getById(id));
    }

    /**
     * 新增客户信息
     */
    @ApiOperation("新增客户信息")
    @Log(title = "客户信息新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmCust cmCust) {

        CmCust cmCust1 = cmCustService.getOne(new LambdaQueryWrapper<CmCust>().eq(CmCust::getCustCode,cmCust.getCustCode()));
        if(cmCust1!=null){
            return error("客户代码已经存在，请重新输入");
        }
        return toAjax(cmCustService.save(cmCust));
    }

    /**
     * 修改客户信息
     */
    @ApiOperation("修改客户信息")
    @Log(title = "客户信息修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmCust cmCust) {

        CmCust cmCust1= cmCustService.getOne(new LambdaQueryWrapper<CmCust>().eq(CmCust::getCustCode,cmCust.getCustCode()).ne(CmCust::getId,cmCust.getId()));
        if(cmCust1!=null){
            return error("客户代码已经存在，请重新输入");
        }
        return toAjax(cmCustService.updateById(cmCust));
    }

    /**
     * 删除客户信息
     */
    @ApiOperation("删除客户信息")
    @Log(title = "客户信息删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(cmCustService.removeBatchByIds(ids));
    }

    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<CmCust> queryWrapper,CmCust cmCust){




        //客户代码
        if(Validator.isNotEmpty(cmCust.getCustCode())){
            queryWrapper.like(CmCust::getCustCode,cmCust.getCustCode());
        }

        //客户名称
        if(Validator.isNotEmpty(cmCust.getCustName())){
            queryWrapper.like(CmCust::getCustName,cmCust.getCustName());
        }

        //营业执照号码
        if(Validator.isNotEmpty(cmCust.getLicenseNumber())){
            queryWrapper.like(CmCust::getLicenseNumber,cmCust.getLicenseNumber());
        }

        //联系方式
        if(Validator.isNotEmpty(cmCust.getContactWay())){
            queryWrapper.like(CmCust::getContactWay,cmCust.getContactWay());
        }

        //联系人
        if(Validator.isNotEmpty(cmCust.getContactPerson())){
            queryWrapper.like(CmCust::getContactPerson,cmCust.getContactPerson());
        }

        if(Validator.isNotEmpty(cmCust.getCustType())) {
            queryWrapper.like(CmCust::getCustType, cmCust.getCustType());
        }

        //备注
        if(Validator.isNotEmpty(cmCust.getRemark())){
            queryWrapper.eq(CmCust::getRemark,cmCust.getRemark());
        }

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



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

        }

}
