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.AssetEmail;
import com.ruoyi.tc.entity.AssetMiniPrograms;
import com.ruoyi.tc.entity.po.AssetAppCpPo;
import com.ruoyi.tc.entity.po.AssetAppJyPo;
import com.ruoyi.tc.entity.po.AssetEmailJyPo;
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.service.AssetMiniProgramsJyService;
import com.ruoyi.tc.service.AssetMiniProgramsService;
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;
    /**
     * 分页查询
     *
     * @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 AssetMiniProgramsJyPo assetMiniProgramsJyPo) {
        AssetMiniProgramsJyPo one = assetMiniProgramsJyService.lambdaQuery().eq(AssetMiniProgramsJyPo::getSsdw,assetMiniProgramsJyPo.getSsdw())
                .eq(AssetMiniProgramsJyPo::getXcxmc,assetMiniProgramsJyPo.getXcxmc()).isNull(AssetMiniProgramsJyPo::getTaskId).one();
        assetMiniProgramsJyPo.setAuditState("1");
        assetMiniProgramsJyPo.setAuditYy(null);
        if (one != null) {
            assetMiniProgramsJyPo.setMiniId(one.getMiniId());
            assetMiniProgramsJyPo.setAssetId(one.getAssetId());
            assetMiniProgramsJyService.updateById(assetMiniProgramsJyPo);
        } else {
            assetMiniProgramsJyPo.setAssetId(assetMiniProgramsService.lambdaQuery().eq(AssetMiniPrograms::getSsdw,assetMiniProgramsJyPo.getSsdw())
                    .eq(AssetMiniPrograms::getXcxmc,assetMiniProgramsJyPo.getXcxmc()).one().getId());
            assetMiniProgramsJyService.save(assetMiniProgramsJyPo);
        }
        return success();
    }

    /**
     * 分页查询管理端或者单位端审核列表
     *
     * @param as 查询实体
     * @return 所有数据
     */
    @ApiOperation(value = "分页查询管理端或者单位端审核列表", response = AssetMiniProgramsJyPo.class)
    @GetMapping("/getAuditList")
    public AjaxResult getAuditList(AssetAuditPageRequest as) {
        Page<AssetMiniProgramsJyPo> 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(assetMiniProgramsJyService.getAuditList(page, as));
    }

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

    /**
     * 管理端审核
     *
     * @param as 查询实体
     * @return 所有数据
     */
    @PreAuthorize("@ss.hasAnyRoles('admin,common')")
    @ApiOperation(value = "管理端审核")
    @PostMapping("/audit")
    public AjaxResult audit(@Valid @RequestBody AssetAuditRequest as) {
        AssetMiniProgramsJyPo ass = new AssetMiniProgramsJyPo();
        BeanUtil.copyProperties(as, ass);
        ass.setMiniId(as.getCurrentId());
        assetMiniProgramsJyService.updateById(ass);
        //通过数据同步
        if ("2".equals(as.getAuditState())) {
            AssetMiniProgramsJyPo byId = assetMiniProgramsJyService.getById(as.getCurrentId());
            AssetMiniPrograms aa = new  AssetMiniPrograms();
            BeanUtil.copyProperties(byId, aa);
            aa.setId(byId.getAssetId());
            //修改主表
            assetMiniProgramsService.updateById(aa);
            //如果有任务也修改任务这边
            AssetMiniProgramsJyPo one = assetMiniProgramsJyService.lambdaQuery()
                    .isNotNull(AssetMiniProgramsJyPo::getTaskId)
                    .ne(AssetMiniProgramsJyPo::getStatus, 5)
                    .eq(AssetMiniProgramsJyPo::getAssetId, byId.getAssetId()).one();
            if(one!=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);
            }
        }
        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) {
        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("导入成功");
    }
}

