package cn.cecep.talroad.controller;

import cn.cecep.talroad.common.core.exception.CommonException;
import cn.cecep.talroad.common.core.utils.poi.ExcelUtil;
import cn.cecep.talroad.common.core.web.controller.BasesController;
import cn.cecep.talroad.common.core.web.domain.AjaxResults;
import cn.cecep.talroad.common.log.annotation.Log;
import cn.cecep.talroad.common.log.enums.BusinessType;
import cn.cecep.talroad.common.security.annotation.RequiresPermissions;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.PcFactory;
import cn.cecep.talroad.enums.EnIndustry;
import cn.cecep.talroad.service.IPcFactoryService;
import cn.cecep.talroad.vo.*;
import cn.cecep.talroad.vo.query.PcFactoryQuery;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.security.InvalidParameterException;
import java.util.*;
import java.util.stream.IntStream;


/**
 * * 开发公司：中节能天融科技有限公司
 * 企业基本信息Controller 控制层
 *
 * @author szhpt
 * @date 2023-01-11*/
@Api(tags = "基础信息--企业基本信息")
@RestController
@RequestMapping("/pcFactory")
public class PcFactoryController extends BasesController
{
    @Autowired
    private IPcFactoryService pcFactoryService;

    /**
     * 查询企业基本信息列表
     */
    @ApiOperation(value = "查询企业基本信息")
    @GetMapping("/list")
    public AjaxResults<IPage<PcFactory>> list(PcFactoryQuery pcFactory)
    {
        Page<PcFactory> page = new Page<>(pcFactory.getPageNum(), pcFactory.getPageSize());
        IPage<PcFactory> list = pcFactoryService.page(page, PcFactoryQuery.createLambdaQueryWrapper(pcFactory));
        return AjaxResults.success(list);
    }

    @GetMapping("/getFactorysByIndustry")
    @ApiOperation(value = "根据行业获取企业列表", notes = "")
    public AjaxResults<List<PcFactory>> getFactorysByIndustry(
            @ApiParam(name = "industry", value = "GT:钢铁,JH:焦化,SN:水泥,FS:焚烧,BL:玻璃", defaultValue = "", allowableValues = "GT,JH,SN,FS,BL") @RequestParam(required = false) String industry) {
        if (StringUtils.isBlank(industry)) {
            industry = EnIndustry.GT.id();
        }
        List<PcFactory> list = pcFactoryService.lambdaQuery().eq(PcFactory::getIndustryCategory, industry).list();
        return AjaxResults.success(list);
    }

    /**
     * 查询企业基本信息列表
     */
    @ApiOperation(value = "查询企业基本信息列表")
    @GetMapping("/selectList")
    public AjaxResults<List<PcFactory>> selectList(PcFactoryQuery pcFactory)
    {
        List<PcFactory> list = pcFactoryService.list(PcFactoryQuery.createLambdaQueryWrapper(pcFactory));
        return AjaxResults.success(list);
    }

    @ApiOperation(value = "企业高级搜索")
    @PostMapping("/search")
    public AjaxResults<IPage<PcFactoryVo>> search(@RequestBody PcFactoryQuery.SearchVo searchVo) {
        Page<PcFactoryVo> page = new Page<>(searchVo.getPageNum(), searchVo.getPageSize());

        // 默认查标签
        if (searchVo.getShowMainLable() == null) {
            searchVo.setShowMainLable(true);
        }
        pcFactoryService.search(page, searchVo, "list", SecurityUtils.getLoginUser().getSysUser().getRegionCode());
        return AjaxResults.success(page);
    }

    @ApiOperation(value = "排污许可-基本信息列表")
    @PostMapping("/pwxk/list")
    public AjaxResults<IPage<PwxkFactoryVo>> pwxkList(@RequestBody PcFactoryQuery.SearchVo searchVo) {
        Page<PwxkFactoryVo> pwxkFactoryVoPage = new Page<>(searchVo.getPageNum(), searchVo.getPageSize());
        List<PwxkFactoryVo> records = pcFactoryService.selectPwxkList(pwxkFactoryVoPage, searchVo);
        pwxkFactoryVoPage.setRecords(records);
        return AjaxResults.success(pwxkFactoryVoPage);
    }

    @ApiOperation(value = "排污许可-基本信息列表导出")
    @PostMapping("/export/pwxk/list")
    public void exportPwxkList(HttpServletResponse response, @RequestBody PcFactoryQuery.SearchVo searchVo)
    {
        Page<PwxkFactoryVo> pwxkFactoryVoPage = new Page<>(searchVo.getPageNum(), searchVo.getPageSize());
        List<PwxkFactoryVo> records = pcFactoryService.selectPwxkList(pwxkFactoryVoPage, searchVo);

        ExcelUtil<PwxkFactoryVo> util = new ExcelUtil<>(PwxkFactoryVo.class);
        util.exportExcel(response, records, "排污许可基本信息统计");
    }

    @ApiOperation(value = "获取企业的关联设备类型")
    @GetMapping("/deviceType/{id}")
    public AjaxResults<List<Map<String, Object>>> list(@PathVariable("id") String id)
    {
        List<Map<String, Object>> list = pcFactoryService.getDeviceType(id);
        return AjaxResults.success(list);
    }

    /**
     * 导出企业基本信息列表
     */
    @ApiOperation(value = "导出企业基本信息")
    @Log(title = "企业基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody PcFactoryQuery.SearchVo searchVo)
    {
        Page<PcFactoryVo> page = new Page<>(searchVo.getPageNum(), searchVo.getPageSize());
        // 默认查标签
        if (searchVo.getShowMainLable() == null) {
            searchVo.setShowMainLable(true);
        }
        pcFactoryService.search(page, searchVo, "list", SecurityUtils.getLoginUser().getSysUser().getRegionCode());
        ExcelUtil<PcFactoryVo> util = new ExcelUtil<>(PcFactoryVo.class);
        util.exportExcel(response, page.getRecords(), "企业基本信息数据");
    }

    /**
     * 获取企业基本信息详细信息
     */
    @ApiOperation(value = "获取企业基本信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResults<PcFactoryVo> getInfo(@PathVariable("id") String id) {
        return AjaxResults.success(pcFactoryService.getInfo(id));
    }
    /**
     * 新增企业基本信息
     */
    @ApiOperation(value = "新增企业基本信息")
    @Log(title = "企业基本信息", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResults<Boolean> add(@RequestBody PcFactory pcFactory) {
        return toAjax(pcFactoryService.save(pcFactory));
    }
    /**
     * 修改企业基本信息
     */
    @ApiOperation(value = "修改企业基本信息")
    @Log(title = "企业基本信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResults<Boolean> edit(@RequestBody PcFactoryVo pcFactoryVo) {
        if(ObjectUtil.isEmpty(pcFactoryVo)){
            throw new InvalidParameterException("参数为空");
        }
        if(ObjectUtil.isEmpty(pcFactoryVo.getId())){
            throw new InvalidParameterException("参数id为空");
        }
        PcFactory pcFactory = pcFactoryService.getById(pcFactoryVo.getId());
        if(ObjectUtil.isEmpty(pcFactory)){
            throw new CommonException(StrUtil.format("根据id{}查询不到数据", pcFactoryVo.getId()));
        }
        //赋值
        BeanUtil.copyProperties(pcFactoryVo,pcFactory);
        return toAjax(pcFactoryService.saveOrUpdate(pcFactory));
    }

    /**
     * 删除企业基本信息
     */
    @ApiOperation(value = "删除企业基本信息")
    @RequiresPermissions("talroad:factory:remove")
    @Log(title = "企业基本信息", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    public AjaxResults<Boolean> remove(@PathVariable String[] ids) {
        return toAjax(pcFactoryService.removeByIds(Arrays.asList(ids)));
    }

    @ApiOperation(value = "批量生成企业标签数据")
    @PostMapping("/batchCreateLabel")
    public AjaxResults batchCreateLabel() {
        pcFactoryService.batchCreateLabel();
        return AjaxResults.success();
    }

    @ApiOperation(value = "分表计电大屏-报警企业排名")
    @PostMapping("/warningRank")
    public AjaxResults<List<PcFactoryVo.WarningRank>> warningRank() {
        List<PcFactoryVo.WarningRank> rankList = pcFactoryService.getWarningRank();
        return AjaxResults.success(rankList);
    }

    /**
     * 修改企业基本信息
     */
    @ApiOperation(value = "修改企业基本信息-企业端")
    @Log(title = "修改企业基本信息-企业端", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editFactory")
    public AjaxResults<Boolean> editFactory(@RequestBody PcFactoryVo pcFactoryVo) {
        if(ObjectUtil.isEmpty(pcFactoryVo)){
            throw new InvalidParameterException("参数为空");
        }
        if(ObjectUtil.isEmpty(pcFactoryVo.getId())){
            throw new InvalidParameterException("参数id为空");
        }
        PcFactory pcFactory = pcFactoryService.getById(pcFactoryVo.getId());

        if(ObjectUtil.isEmpty(pcFactory)){
            throw new CommonException(StrUtil.format("根据id{}查询不到数据", pcFactoryVo.getId()));
        }
        //赋值
        pcFactory.setProductionLon(pcFactoryVo.getProductionLon());
        pcFactory.setProductionLat(pcFactoryVo.getProductionLat());

        return toAjax(pcFactoryService.saveOrUpdate(pcFactory));
    }


    /**
     * 查询企业坐标信息
     */
    @ApiOperation(value = "查询企业坐标信息")
    @GetMapping("/coordinateList")
    public AjaxResults<IPage<PcFactory>> coordinateList(PcFactoryQuery pcFactory)
    {
        String id = pcFactory.getId();
        if(StringUtils.isEmpty(id)){
            Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
            if(ObjectUtil.equal(roleId,10L)) {
                String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
                pcFactory.setId(factoryId);
            }
        }
        Page<PcFactory> page = new Page<>(pcFactory.getPageNum(), pcFactory.getPageSize());
        IPage<PcFactory> list = pcFactoryService.page(page, PcFactoryQuery.createLambdaQueryWrapper(pcFactory).orderByDesc("factory_name"));
        return AjaxResults.success(list);
    }

    /**
     * 导出企业坐标信息列表
     */
    @ApiOperation(value = "导出企业坐标信息")
    @Log(title = "企业坐标信息列表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportCoordinateList")
    public void exportCoordinateList(HttpServletResponse response,@RequestBody PcFactoryQuery pcFactoryQuery)
    {
        String id = pcFactoryQuery.getId();
        if(StringUtils.isEmpty(id)){
            Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
            if(ObjectUtil.equal(roleId,10L)) {
                String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
                pcFactoryQuery.setId(factoryId);
            }
        }
        List<PcFactory> list = pcFactoryService.list(PcFactoryQuery.createLambdaQueryWrapper(pcFactoryQuery).orderByDesc("factory_name"));
        List<PcFactoryCoordinateVo> pcFactoryCoordinateVoList = new ArrayList<>();
        PrimitiveIterator.OfInt iterator = IntStream.iterate(1, k -> k + 1).iterator();
        list.forEach(e -> {
            PcFactoryCoordinateVo pcFactoryCoordinateVo = new PcFactoryCoordinateVo();
            BeanUtil.copyProperties(e, pcFactoryCoordinateVo);
            pcFactoryCoordinateVo.setSerialnumber(iterator.next());
            pcFactoryCoordinateVoList.add(pcFactoryCoordinateVo);
        });
        ExcelUtil<PcFactoryCoordinateVo> util = new ExcelUtil<>(PcFactoryCoordinateVo.class);
        util.exportExcel(response, pcFactoryCoordinateVoList, "企业坐标信息数据");
    }

    /**
     * 批量修改企业坐标信息
     */
    @ApiOperation(value = "批量修改企业坐标信息")
    @Log(title = "企业坐标信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editBatchCoordinate")
    public AjaxResults<Boolean> editBatch(@RequestBody PcFactory[] pcFactoryArr) {
        if (pcFactoryArr ==null || pcFactoryArr.length < 1) {
            throw new InvalidParameterException("参数为空");
        }
        pcFactoryService.editBatch(pcFactoryArr);
        return toAjax(true);
    }

    /**
     * 大屏任务调度-企业许可证发放情况
     */
    @ApiOperation(value = "大屏任务调度-企业许可证发放情况")
    @GetMapping("/licenSingStatusList")
    public AjaxResults<PcFactoryLicensingStatusVo> licenSingStatusList() {
        return AjaxResults.success(pcFactoryService.licenSingStatusList());
    }

    /**
     * 大屏任务调度-行业分布情况
     */
    @ApiOperation(value = "大屏任务调度-行业分布情况")
    @GetMapping("/professionStatusChart")
    public AjaxResults<PcProfessionLicensingStatusVo> professionStatusChart() {
        return AjaxResults.success(pcFactoryService.professionStatusChart());
    }
}
