package com.zksy.web.controller.basicData;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.common.annotation.Log;
import com.zksy.common.core.controller.BaseController;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.enums.BusinessType;
import com.zksy.common.utils.file.ExcelUtils;
import com.zksy.system.basicData.domain.CrmEnterpriseTrademarkInformation;
import com.zksy.system.basicData.domain.CrmFile;
import com.zksy.system.basicData.mapper.CrmEnterpriseTrademarkInformationMapper;
import com.zksy.system.basicData.service.impl.CrmEnterpriseTrademarkInformationServiceImpl;
import com.zksy.utils.DowntemplateUtil;
import com.zksy.utils.SearchUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业商标信息Controller
 *
 * @author sy
 * @date 2024-04-02
 */
@RestController
@RequestMapping("/crmEnterpriseTrademarkInformation")
@Api(tags = "企业商标信息", description = "企业商标信息desc")
public class CrmEnterpriseTrademarkInformationController extends BaseController {
    @Value("${local.fileserver.upload.path}")
    private String localFileServerUploadDir;

    @Value("${local.fileserver.mapping.path}")
    private String localFileServerMappingPath;

    @Value("${server.port}")
    private int port;
    @Autowired
    private CrmEnterpriseTrademarkInformationServiceImpl service;

    @GetMapping("/getById/{borrowId}")
    @ApiOperation(value = "企业商标信息搜索getById")
    public AjaxResult getById(@PathVariable String borrowId) {
        return AjaxResult.success(service.getById(borrowId));
    }

    @GetMapping("/findByPage")
    @ApiOperation(value = "企业商标信息分页")
    public Page findByPage(long pageNum, long pageSize, String conditionJson) throws Exception {
        return service.page(new Page<>(pageNum, pageSize), SearchUtil.parseWhereSql(conditionJson));
    }

    @GetMapping("/getList")
    @ApiOperation(value = "企业商标信息查询所有")
    public AjaxResult getList(String conditionJson) throws Exception {
        return AjaxResult.success(service.list(SearchUtil.parseWhereSql(conditionJson)));
    }

    /**
     * 新增企业商标信息
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增企业商标信息新增")
    @Log(title = "新增企业商标信息", businessType = BusinessType.INSERT)
    public boolean save(@RequestBody CrmEnterpriseTrademarkInformation crmEnterpriseTrademarkInformation) {
        return service.save(crmEnterpriseTrademarkInformation);
    }

    /**
     * 修改企业商标信息
     */
    @PostMapping("/updateById")
    @ApiOperation(value = "新增企业商标信息修改")
    @Log(title = "修改企业商标信息", businessType = BusinessType.UPDATE)
    public boolean updateById(@RequestBody CrmEnterpriseTrademarkInformation crmEnterpriseTrademarkInformation) {
        return service.updateById(crmEnterpriseTrademarkInformation);
    }

    /**
     * 导入企业商标信息
     */
    @ApiOperation("企业商标信息导入")
    @Log(title = "企业商标信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file)
    {
        try {
            List<CrmEnterpriseTrademarkInformation> crmEnterpriseTrademarkInformationAll = service.list();
            // column 为图片所在列
            List<CrmEnterpriseTrademarkInformation> list = ExcelUtils.readCrmEnterpriseTrademarkInformationMultipartFile(
                    file, CrmEnterpriseTrademarkInformation.class,CrmEnterpriseTrademarkInformation.class.getDeclaredFields().length -4,4,localFileServerUploadDir,localFileServerMappingPath);

            if(crmEnterpriseTrademarkInformationAll != null && crmEnterpriseTrademarkInformationAll.size() > 0){
                //return AjaxResult.error("数据已存在，如需重新导入请清空数据");
            }
            if(list.size() > 0){
                service.saveBatch(list);
                return AjaxResult.success("导入成功，共计："+list.size()+"条");
            }else{
                return AjaxResult.error("无数据");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("导入数据失败");
        }
    }

    @ApiOperation("企业商标信息导出")
    @Log(title = "企业商标信息", businessType = BusinessType.EXPORT)
    @PostMapping("/exportData")
    public AjaxResult exportData(HttpServletResponse response, String conditionJson){
        try {
            List<CrmEnterpriseTrademarkInformation> wrapperList = service.list(SearchUtil.parseWhereSql(conditionJson));
            wrapperList.forEach(list ->{
                try {
                    String ip = InetAddress.getLocalHost().getHostAddress();
                    list.setImage(new URL("http://"+ip+":"+port+list.getTrademarkImage()));
                } catch (MalformedURLException | UnknownHostException e) {
                    throw new RuntimeException(e);
                }
            });
            ExcelUtils.export(response, "企业商标信息", wrapperList, CrmEnterpriseTrademarkInformation.class);
            return AjaxResult.success("导出数据成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("导出数据失败");
        }
    }

    @Log(title = "企业商标信息", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    @ApiOperation(value = "删除企业商标信息", notes = "删除企业商标信息")
    public AjaxResult delete(@RequestBody List<String> ids)
    {
        try{
            service.removeFileById(ids,localFileServerMappingPath,localFileServerUploadDir);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("删除失败");
        }
        return AjaxResult.success("删除成功");
    }

    @DeleteMapping("/deleteAll")
    @ApiOperation(value = "清除数据", notes = "清除数据")
    public AjaxResult deleteAll(){
        QueryWrapper<CrmEnterpriseTrademarkInformation> wrapper = new QueryWrapper<>();
        wrapper.select("id");
        CrmEnterpriseTrademarkInformationMapper baseMapper = service.getBaseMapper();
        List<CrmEnterpriseTrademarkInformation> list = baseMapper.selectList(wrapper);
        List<String> ids = list.stream().map(q -> String.valueOf(q.getId())).collect(Collectors.toList());
        return service.removeFileById(ids,localFileServerMappingPath,localFileServerUploadDir);
    }
    @PostMapping("/getUploadTemplate")
    @ApiOperation(value = "获取上传模板", notes = "获取上传模板")
    public void getUploadTemplate(HttpServletResponse response) throws IOException {
        DowntemplateUtil.downloadTemplate(response,"企业商标信息模板");
    }
}

