package com.ozs.web.controller.base;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ozs.base.domain.BaseProfessional;
import com.ozs.base.domain.vo.BaseProfessionalVo;
import com.ozs.base.service.BaseProfessionalService;
import com.ozs.common.annotation.Log;
import com.ozs.common.config.PurchaseConfig;
import com.ozs.common.constant.ModularConstans;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.R;
import com.ozs.common.core.domain.model.LoginUser;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.file.FileUtils;
import com.ozs.common.utils.poi.ExcelUtil;
import com.ozs.plan.doman.ProvisionalPlan;
import com.ozs.plan.doman.vo.requestVo.ProvisionalPlanVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

/**
 * 专业库管理
 *
 * @author sunhh
 */
@Api(tags = "专业库管理")
@RestController
@RequestMapping("/base/professional")
@Slf4j
public class BaseProfessionalController extends BaseController {

    @Autowired
    private BaseProfessionalService baseProfessionalService;

    @ApiOperation(value = "新增专业库", notes = "必传 专业库名称、一级分类、编码、父级编码；没有父级编码传0")
    @PostMapping("/insertProfessional")
    @PreAuthorize("@ss.hasPermi('base:professional:insertProfessional')")
    @Log(title = ModularConstans.professional, businessType = BusinessType.INSERT)
    public AjaxResult insertProfessional(@RequestBody BaseProfessional baseProfessional) {
        if (StringUtils.isNull(baseProfessional)
                || StringUtils.isNull(baseProfessional.getProfessionalName())
                || StringUtils.isNull(baseProfessional.getProfessionalCode())
                || StringUtils.isNull(baseProfessional.getProfessionalGrade())
                || StringUtils.isNull(baseProfessional.getParentCode())) {
            return error("专业库名称、编码、一级分类、父级ID 不能为空");
        }
        LambdaQueryWrapper<BaseProfessional> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseProfessional::getProfessionalCode, baseProfessional.getProfessionalCode());
        List<BaseProfessional> list = baseProfessionalService.list(wrapper);
        if (!ObjectUtils.isEmpty(list)) {
            return AjaxResult.error("编码信息不可重复使用！");
        }
        return toAjax(baseProfessionalService.save(baseProfessional));
    }

    @ApiOperation(value = "删除专业库", notes = "必传 id")
    @PostMapping("/deleteProfessional")
    @PreAuthorize("@ss.hasPermi('base:professional:deleteProfessional')")
    @Log(title = ModularConstans.professional, businessType = BusinessType.DELETE)
    public AjaxResult deleteProfessional(@RequestBody BaseProfessional baseProfessional) {
        if (StringUtils.isNull(baseProfessional) || StringUtils.isNull(baseProfessional.getId())) {
            return error("专业库id不能为空");
        }
        return toAjax(baseProfessionalService.deleteId(baseProfessional.getId()));
    }

    @ApiOperation(value = "批量删除专业库", notes = "必传 idList")
    @PostMapping("/deleteIds")
    @PreAuthorize("@ss.hasPermi('base:professional:deleteIds')")
    @Log(title = ModularConstans.professional, businessType = BusinessType.DELETE)
    public AjaxResult deleteByIdLIst(@RequestBody BaseProfessionalVo baseProfessionalVo) {
        baseProfessionalService.deleteIds(baseProfessionalVo.getDeleteIds());
        return success();
    }

    @ApiOperation(value = "修改专业库", notes = "必传 id 及修改数据")
    @PostMapping("/updateProfessional")
    @PreAuthorize("@ss.hasPermi('base:professional:updateProfessional')")
    @Log(title = ModularConstans.professional, businessType = BusinessType.UPDATE)
    public AjaxResult updateProfessional(@RequestBody BaseProfessional baseProfessional) {
        if (StringUtils.isNull(baseProfessional) || StringUtils.isNull(baseProfessional.getId())) {
            return error("专业库id和修改数据不能为空");
        }
        LambdaQueryWrapper<BaseProfessional> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseProfessional::getProfessionalCode, baseProfessional.getProfessionalCode());
        wrapper.ne(BaseProfessional::getId, baseProfessional.getId());
        List<BaseProfessional> list = baseProfessionalService.list(wrapper);
        if (!ObjectUtils.isEmpty(list)) {
            return AjaxResult.error("编码信息不可重复使用！");
        }
        return toAjax(baseProfessionalService.updateProfessional(baseProfessional));
    }

    @ApiOperation(value = "查询专业库树结构", notes = "非必传 查询条件：品目名称")
    @PostMapping("/selectBaseProfessional")
    @PreAuthorize("@ss.hasPermi('base:professional:selectBaseProfessional')")
    @Log(title = ModularConstans.professional, businessType = BusinessType.QUERY)
    public AjaxResult selectBaseProfessional(@RequestBody BaseProfessionalVo baseProfessionalVo) {
        List<BaseProfessionalVo> baseSupplierList = baseProfessionalService.selectBaseProfessionalVo(baseProfessionalVo);
        return success(baseSupplierList);
    }

    @ApiOperation(value = "导入专业库", notes = "导入表格")
    @PostMapping("/importBaseProfessional")
    @PreAuthorize("@ss.hasPermi('base:professional:importBaseProfessional')")
    @Log(title = ModularConstans.professional, businessType = BusinessType.IMPORT)
    public AjaxResult importBaseProfessional(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BaseProfessional> util = new ExcelUtil<>(BaseProfessional.class);
        List<BaseProfessional> baseProfessionalList = util.importExcel(file.getInputStream());
        if (StringUtils.isNull(baseProfessionalList) || baseProfessionalList.size() == 0) {
            throw new ServiceException("导入专业库数据不能为空！");
        }
        // String operName = getUsername();
        String message = baseProfessionalService.importBaseProfessional(baseProfessionalList, updateSupport);
        return success(message);
    }

    @ApiOperation("导出专业库")
    @PostMapping("/exportBaseProfessional")
    @PreAuthorize("@ss.hasPermi('base:professional:exportBaseProfessional')")
    @Log(title = ModularConstans.professional, businessType = BusinessType.EXPORT)
    public void exportBaseProfessional(HttpServletResponse response, @RequestBody BaseProfessionalVo baseProfessionalVo) {
        List<BaseProfessional> list = baseProfessionalService.selectBaseProfessional(baseProfessionalVo);
        ExcelUtil<BaseProfessional> util = new ExcelUtil<>(BaseProfessional.class);
        util.exportExcel(response, list, "专业库数据");
    }

    @ApiOperation("文件下载")
    @GetMapping("/downloaExcel")
    @PreAuthorize("@ss.hasPermi('base:professional:downloaExcel')")
    @Log(title = ModularConstans.professional, businessType = BusinessType.OTHER)
    public void downloadZip(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 文件路径
//            String downloadPath = this.getClass().getResource("/template/professional.xlsx").getPath();
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/template/professional.xlsx");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, "专业库模板.xlsx");
            FileUtils.writeBytesByInput(resourceAsStream, response.getOutputStream());

        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }


}
