package com.ruoyi.tc.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tc.entity.AssetMiniPrograms;
import com.ruoyi.tc.entity.AssetTask;
import com.ruoyi.tc.entity.Unit;
import com.ruoyi.tc.entity.po.AssetMiniProgramsCpPo;
import com.ruoyi.tc.entity.po.AssetMiniProgramsJyPo;
import com.ruoyi.tc.entity.request.AssetAuditPageRequest;
import com.ruoyi.tc.entity.request.AssetAuditRequest;
import com.ruoyi.tc.entity.request.AssetMiniProgramsPageRequest;
import com.ruoyi.tc.entity.zztb.AssetMiniProgramsZztbPo;
import com.ruoyi.tc.service.*;
import com.ruoyi.tc.zztbService.AssetMiniProgramsZztbService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * 小程序资产表(asset_mini_programs)表控制层
 *
 * @author makejava
 * @since 2024-11-28 17:13:05
 */
@Api(tags = "小程序资产")
@RestController
@RequestMapping("/tc/miniPrograms")
public class AssetMiniProgramsController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private AssetMiniProgramsService assetMiniProgramsService;

    @Resource
    private AssetMiniProgramsJyService assetMiniProgramsJyService;


    @Resource
    private AssetTaskService assetTaskService;
    @Resource
    private AssetMiniProgramsCpService assetMiniProgramsCpService;

    @Resource
    private UnitService unitService;


    @Resource
    private AssetMiniProgramsZztbService assetMiniProgramsZztbService;


    /**
     * 分页查询
     *
     * @param req 分页对象
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询")
    @GetMapping
    public AjaxResult queryByPage(AssetMiniProgramsPageRequest req) {
        Page<AssetMiniPrograms> page = new Page<>();
        page.setCurrent(req.getCurrent());
        page.setSize(req.getSize());
        try {
            if (!SecurityUtils.getLoginUser().getUser().isAdmin() && !SecurityUtils.hasRole("common")) {
                req.setDwmc(SecurityUtils.getLoginUser().getUser().getNickName());
            }
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常");
        }
        return success(assetMiniProgramsService.page(page, req));
    }

    //=================================================

    /**
     * 单位自编辑进行校验
     */
    @ApiOperation(value = "单位自编辑进行校验")
    @PreAuthorize("@ss.hasAnyRoles('unit')")
    @PostMapping("/unitEdit")
    public AjaxResult unitEdit(@RequestBody @Valid AssetMiniProgramsZztbPo assetMiniProgramsZztbPo) {
        List<Unit> list = unitService.lambdaQuery().eq(Unit::getNickName, assetMiniProgramsZztbPo.getSsdw()).eq(Unit::getDelFlag, 0).list();
        if (list == null || list.isEmpty()) {
            throw new ServiceException("请选择已有单位!");
        }


        AssetMiniProgramsZztbPo one = assetMiniProgramsZztbService.lambdaQuery().eq(AssetMiniProgramsZztbPo::getSsdw, assetMiniProgramsZztbPo.getSsdw())
                .eq(AssetMiniProgramsZztbPo::getXcxmc, assetMiniProgramsZztbPo.getXcxmc()).isNull(AssetMiniProgramsZztbPo::getTaskId).one();
        assetMiniProgramsZztbPo.setAuditState("1");
        assetMiniProgramsZztbPo.setAuditYy(null);
        if (one != null) {
            assetMiniProgramsZztbPo.setMiniId(one.getMiniId());
            assetMiniProgramsZztbPo.setAssetId(one.getAssetId());
            assetMiniProgramsZztbService.updateById(assetMiniProgramsZztbPo);
        } else {
            assetMiniProgramsZztbPo.setAssetId(assetMiniProgramsService.lambdaQuery().eq(AssetMiniPrograms::getSsdw, assetMiniProgramsZztbPo.getSsdw())
                    .eq(AssetMiniPrograms::getXcxmc, assetMiniProgramsZztbPo.getXcxmc()).one().getId());
            assetMiniProgramsZztbService.save(assetMiniProgramsZztbPo);
        }
        return success();
    }

    /**
     * 分页查询管理端或者单位端审核列表
     *
     * @param as 查询实体
     * @return 所有数据
     */
    @ApiOperation(value = "分页查询管理端或者单位端审核列表", response = AssetMiniProgramsZztbPo.class)
    @GetMapping("/getAuditList")
    public AjaxResult getAuditList(AssetAuditPageRequest as) {
        Page<AssetMiniProgramsZztbPo> page = new Page<>();
        page.setSize(as.getSize());
        page.setCurrent(as.getCurrent());
        try {
            if (!SecurityUtils.getLoginUser().getUser().isAdmin() && !SecurityUtils.hasRole("common")) {
                as.setDwmc(SecurityUtils.getLoginUser().getUser().getNickName());
            }
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常");
        }
        return success(assetMiniProgramsZztbService.getAuditList(page, as));
    }

    /**
     * 查看中间数据详情
     */
    @ApiOperation(value = "单位端查看中间数据详情", response = AssetMiniProgramsJyPo.class)
    @GetMapping("/lookInfo/{id}")
    public AjaxResult lookInfo(@PathVariable Long id) {
        return success(assetMiniProgramsZztbService.getById(id));
    }

    /**
     * 管理端审核
     *
     * @param as 查询实体
     * @return 所有数据
     */
    @PreAuthorize("@ss.hasAnyRoles('admin,common')")
    @ApiOperation(value = "管理端审核")
    @PostMapping("/audit")
    public AjaxResult audit(@Valid @RequestBody AssetAuditRequest as) {
        AssetMiniProgramsZztbPo ass = new AssetMiniProgramsZztbPo();
        BeanUtil.copyProperties(as, ass);
        ass.setMiniId(as.getCurrentId());
        assetMiniProgramsZztbService.updateById(ass);
        //通过数据同步
        if ("2".equals(as.getAuditState()) && as.getXzType() != 1) {
            AssetMiniProgramsJyPo byId = assetMiniProgramsJyService.getById(as.getCurrentId());
            AssetMiniPrograms aa = new AssetMiniPrograms();
            BeanUtil.copyProperties(byId, aa);
            aa.setId(byId.getAssetId());
            //修改主表
            aa.setDelFlag("0");
            assetMiniProgramsService.updateById(aa);
            //如果有任务也修改任务这边
            AssetMiniProgramsJyPo one = assetMiniProgramsJyService.lambdaQuery()
                    .isNotNull(AssetMiniProgramsJyPo::getTaskId)
                    .ne(AssetMiniProgramsJyPo::getStatus, 5)
                    .eq(AssetMiniProgramsJyPo::getAssetId, byId.getAssetId())
                    .orderByDesc(AssetMiniProgramsJyPo::getMiniId)
                    .last("LIMIT 1").one();
            if (one != null) {
                //根据任务id查询任务是否关闭
                AssetTask two = assetTaskService.lambdaQuery().eq(AssetTask::getId, one.getTaskId()).eq(AssetTask::getTaskStatus, 0).one();
                if (two == null) {
                    Integer taskId = one.getTaskId();
                    Long appId = one.getMiniId();
                    Integer status = one.getStatus();
                    BeanUtil.copyProperties(byId, one);
                    one.setMiniId(appId);
                    one.setTaskId(taskId);
                    one.setAuditState(null);
                    one.setAuditYy(null);
                    one.setStatus(status);
                    assetMiniProgramsJyService.updateById(one);
                }

            }
        }
        else if("2".equals(as.getAuditState())){
            AssetMiniProgramsZztbPo byId = assetMiniProgramsZztbService.getById(as.getCurrentId());
            AssetMiniPrograms aa = new AssetMiniPrograms();
            BeanUtil.copyProperties(byId, aa);
            aa.setId(byId.getAssetId());
            //根据资产名称和所属单位查询主表是否有数据
            AssetMiniPrograms assetMiniPrograms = assetMiniProgramsService.lambdaQuery().eq(AssetMiniPrograms::getXcxmc, byId.getXcxmc()).eq(AssetMiniPrograms::getSsdw, byId.getSsdw()).one();
            if (assetMiniPrograms != null) {
                //修改主表
                if (assetMiniPrograms.getXzType()==0){
                    BeanUtil.copyProperties(aa, assetMiniPrograms, "id");
                    //区分数据是管理端新增还是单位端新增
                    assetMiniPrograms.setXzType(0);
                    assetMiniPrograms.setDelFlag("0");
                    assetMiniProgramsService.updateById(assetMiniPrograms);
                }else{
                    BeanUtil.copyProperties(aa, assetMiniPrograms, "id");
                    assetMiniPrograms.setDelFlag("0");
                    assetMiniProgramsService.updateById(assetMiniPrograms);
                }
                //如果有任务也修改任务这边
                AssetMiniProgramsJyPo one = assetMiniProgramsJyService.lambdaQuery()
                        .ne(AssetMiniProgramsJyPo::getStatus, 5)
                        .eq(AssetMiniProgramsJyPo::getXcxmc, byId.getXcxmc())
                        .orderByDesc(AssetMiniProgramsJyPo::getMiniId)
                        .last("LIMIT 1").one();
                if (one != null) {
                    //根据任务id查询任务是否关闭
                    AssetTask two = assetTaskService.lambdaQuery().eq(AssetTask::getId, one.getTaskId()).eq(AssetTask::getTaskStatus, 0).one();
                    if (two == null) {
                        Integer status = one.getStatus();
                        Integer taskId = one.getTaskId();
                        Long appId = one.getMiniId();
                        BeanUtil.copyProperties(byId, one);
                        one.setMiniId(appId);
                        one.setTaskId(taskId);
                        one.setAuditState(null);
                        one.setAuditYy(null);
                        one.setStatus(status);
                        assetMiniProgramsJyService.updateById(one);
                    }

                }
            } else {
                //新增主表
                assetMiniProgramsService.save(aa);
                //查询改单位下是否有进行中的任务
                AssetTask task= assetTaskService.lambdaQuery().like(AssetTask::getDwmc,aa.getSsdw()).like(AssetTask::getType,"1").eq(AssetTask::getTaskStatus,1).one();
              if (task!=null){
                  AssetMiniProgramsCpPo bb = new AssetMiniProgramsCpPo();
                  BeanUtil.copyProperties(byId, bb);
                  bb.setAssetId(aa.getId());
                  bb.setMiniId(null);
                  bb.setTaskId(task.getId());
                  assetMiniProgramsCpService.save(bb);
              }

            }

        }
        else if("3".equals(as.getAuditState())){
            AssetMiniProgramsZztbPo byId = assetMiniProgramsZztbService.getById(as.getCurrentId());
            AssetMiniPrograms aa = new AssetMiniPrograms();
            BeanUtil.copyProperties(byId, aa);
            aa.setId(byId.getAssetId());
            //根据资产名称和所属单位查询主表是否有数据
            AssetMiniPrograms assetMiniPrograms = assetMiniProgramsService.lambdaQuery().eq(AssetMiniPrograms::getXcxmc, byId.getXcxmc()).eq(AssetMiniPrograms::getSsdw, byId.getSsdw()).one();
            if (assetMiniPrograms != null) {
                //修改主表
                if (assetMiniPrograms.getXzType() == 0) {
                    BeanUtil.copyProperties(aa, assetMiniPrograms, "id");
                    //区分数据是管理端新增还是单位端新增
                    assetMiniPrograms.setXzType(0);
                    assetMiniPrograms.setDelFlag("1");
                    assetMiniProgramsService.updateById(assetMiniPrograms);
                } else {
                    BeanUtil.copyProperties(aa, assetMiniPrograms, "id");
                    assetMiniPrograms.setDelFlag("1");
                    assetMiniProgramsService.updateById(assetMiniPrograms);
                }
            }
        }
        return success();
    }
    //=================================================


    /**
     * 通过主键查询单条小程序数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "通过主键查询单条小程序数据")
    @GetMapping("/{id}")
    public AjaxResult queryById(@PathVariable("id") Long id) {
        return success(assetMiniProgramsService.getById(id));
    }

    /**
     * 新增小程序数据
     *
     * @param assetMiniPrograms 实体
     * @return 新增结果
     */
    @ApiOperation(value = "新增小程序数据")
    @PostMapping
    @Log(title = "新增小程序数据", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody AssetMiniPrograms assetMiniPrograms) {
        return success(assetMiniProgramsService.add(assetMiniPrograms));
    }

    /**
     * 编辑小程序数据
     *
     * @param assetMiniPrograms 实体
     * @return 编辑结果
     */
    @ApiOperation(value = "编辑小程序数据")
    @Log(title = "编辑小程序数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AssetMiniPrograms assetMiniPrograms) {

        //根据资产id查询资产子表,判断是否有此资产进行中的任务,如果资产状态是已关停与修改的数据不符，则修改任务中的资产状态
        List<AssetMiniProgramsCpPo> assetMiniProgramsCpPo = assetMiniProgramsCpService.findDwmc(assetMiniPrograms.getId());
        if (assetMiniProgramsCpPo != null) {
            for (AssetMiniProgramsCpPo s : assetMiniProgramsCpPo) {
                //查询任务是否为进行中
                AssetTask assetTask = assetTaskService.findByTaskId(s.getTaskId());
                if (assetTask != null) {
                    if (assetTask.getTaskStatus().equals(1)) {
                        //修改任务中资产状态
                        s.setStatus(0);
                        s.setBfyy(null);
                        s.setBtgyy(null);

                        s.setUpdateTime(null);
                        assetTask.setTaskStatus(1);
                        s.setMiniId(s.getMiniId());
                        assetMiniProgramsCpService.updateById(s);
                        assetTaskService.update(assetTask);

                    }
                }
            }
        }
        return success(assetMiniProgramsService.edit(assetMiniPrograms));
    }

    /**
     * 删除小程序数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @ApiOperation(value = "删除小程序数据")
    @Log(title = "删除小程序数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{id}")
    public AjaxResult deleteById(@PathVariable Long id) {
        assetMiniProgramsService.deleteById(id);
        return success();
    }

    /**
     * 下载资产导入模板
     */
    @ApiOperation(value = "下载App导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<AssetMiniPrograms> util = new ExcelUtil<>(AssetMiniPrograms.class);
        util.importTemplateExcel(response, "App导入模板");
    }

    /**
     * 小程序导出
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "小程序导出")
    @Log(title = "小程序导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AssetMiniProgramsPageRequest unit) {
        List<AssetMiniPrograms> list = assetMiniProgramsService.getAllList(unit);
        ExcelUtil<AssetMiniPrograms> util = new ExcelUtil<>(AssetMiniPrograms.class);
        util.exportExcel(response, list, "小程序数据");
    }

    /**
     * 小程序导入
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "小程序导入")
    @Log(title = "小程序导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<AssetMiniPrograms> util = new ExcelUtil<>(AssetMiniPrograms.class);
        List<AssetMiniPrograms> list = util.importExcel(file.getInputStream());
        if (list != null) {
            list.forEach(x -> {
                AssetMiniPrograms one = assetMiniProgramsService.lambdaQuery().eq(AssetMiniPrograms::getSsdw, x.getSsdw())
                        .eq(AssetMiniPrograms::getXcxmc, x.getXcxmc()).one();
                if (one != null) {
                    x.setId(one.getId());
                    assetMiniProgramsService.edit(x);
                } else {
                    assetMiniProgramsService.add(x);
                }
            });
        } else {
            throw new ServiceException("小程序导入数据不能为空!");
        }
        return AjaxResult.success("导入成功");
    }
}

