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.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.AssetOfficialAccount;
import com.ruoyi.tc.entity.AssetTask;
import com.ruoyi.tc.entity.Unit;
import com.ruoyi.tc.entity.po.AssetOfficialAccountCpPo;
import com.ruoyi.tc.entity.po.AssetOfficialAccountJyPo;
import com.ruoyi.tc.entity.request.AssetAuditPageRequest;
import com.ruoyi.tc.entity.request.AssetAuditRequest;
import com.ruoyi.tc.entity.request.AssetOfficialAccountMenu;
import com.ruoyi.tc.entity.request.AssetOfficialAccountPageRequest;
import com.ruoyi.tc.entity.zztb.AssetOfficialAccountZztbPo;
import com.ruoyi.tc.service.*;
import com.ruoyi.tc.zztbService.AssetOfficialAccountZztbService;
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.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * 公众号资产(asset_official_account)表控制层
 *
 * @author makejava
 * @since 2024-11-28 17:13:05
 */
@Api(tags = "公众号资产")
@RestController
@RequestMapping("/tc/assetOfficialAccount")
public class AssetOfficialAccountController {
    /**
     * 服务对象
     */
    @Resource
    private AssetOfficialAccountService assetOfficialAccountService;

    @Resource
    private AssetOfficialAccountJyService assetOfficialAccountJyService;

    @Resource
    private UnitService unitService;
    @Resource
    private AssetTaskService assetTaskService;
    @Resource
    private AssetOfficialAccountCpService assetOfficialAccountCpService;


    @Resource
    private AssetOfficialAccountZztbService assetOfficialAccountZztbService;

    /**
     * 分页查询
     *
     * @param req 分页对象
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询")
    @GetMapping
    public AjaxResult queryByPage(AssetOfficialAccountPageRequest req) {
        Page<AssetOfficialAccount> 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(assetOfficialAccountService.page(page, req));
    }

    /**
     * 通过主键查询单条公众号数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "通过主键查询单条公众号数据")
    @GetMapping("/{id}")
    public AjaxResult queryById(@PathVariable("id") Long id) {
        AssetOfficialAccount byId = assetOfficialAccountService.getById(id);
        List<AssetOfficialAccountMenu> a1 = new ArrayList<>();
        String[] s1 = byId.getCdmc().split("\\|");
        String[] s2 = byId.getCdlj().split("\\|");
        String[] s3 = byId.getCdlx().split("\\|");
        for (int i = 0; i < s1.length; i++) {
            AssetOfficialAccountMenu as = new AssetOfficialAccountMenu();
            if (s1[i] != null && !Objects.equals(s1[i], "")) {
                as.setCdmc(s1[i]);
            }
            if (s2[i] != null && !Objects.equals(s2[i], "")) {
                as.setCdlj(s2[i]);
            }
            if (s3[i] != null && !Objects.equals(s3[i], "")) {
                as.setCdlx(s3[i]);
            }
            a1.add(as);
        }
        byId.setCdList(a1);
        return success(byId);
    }

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

    /**
     * 单位自编辑进行校验
     */
    @ApiOperation(value = "单位自编辑进行校验")
    @PreAuthorize("@ss.hasAnyRoles('unit')")
    @PostMapping("/unitEdit")
    public AjaxResult unitEdit(@RequestBody @Valid AssetOfficialAccountZztbPo ao) {

        List<Unit> list = unitService.lambdaQuery().eq(Unit::getNickName, ao.getSsdw()).eq(Unit::getDelFlag, 0).list();
        if (list == null || list.isEmpty()) {
            throw new ServiceException("请选择已有单位!");
        }


        if (ao.getCdList() != null && !ao.getCdList().isEmpty()) {
            StringBuilder a = new StringBuilder();
            StringBuilder b = new StringBuilder();
            StringBuilder c = new StringBuilder();
            ao.getCdList().forEach(x -> {
                if (!Objects.equals(x.getCdmc(), "") && x.getCdmc() != null) {
                    a.append(x.getCdmc()).append("|");
                }
                if (!Objects.equals(x.getCdlj(), "") && x.getCdlj() != null) {
                    b.append(x.getCdlj()).append("|");
                }
                if (!Objects.equals(x.getCdlx(), "") && x.getCdlx() != null) {
                    c.append(x.getCdlx()).append("|");
                }
            });
            ao.setCdmc(a.toString());
            ao.setCdlj(b.toString());
            ao.setCdlx(c.toString());
        }

        AssetOfficialAccountZztbPo one = assetOfficialAccountZztbService.lambdaQuery().eq(AssetOfficialAccountZztbPo::getGzhmc, ao.getGzhmc())
                .eq(AssetOfficialAccountZztbPo::getSsdw, ao.getSsdw()).isNull(AssetOfficialAccountZztbPo::getTaskId).one();
        ao.setAuditState("1");
        ao.setAuditYy(null);
        if (one != null) {
            ao.setAccountId(one.getAccountId());
            ao.setAssetId(one.getAssetId());
            assetOfficialAccountZztbService.updateById(ao);
        } else {
            ao.setAssetId(assetOfficialAccountService.lambdaQuery().eq(AssetOfficialAccount::getSsdw, ao.getSsdw())
                    .eq(AssetOfficialAccount::getGzhmc, ao.getGzhmc()).one().getId());
            assetOfficialAccountZztbService.save(ao);
        }
        return success();
    }

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

    /**
     * 查看中间数据详情
     */
    @ApiOperation(value = "单位端查看中间数据详情", response = AssetOfficialAccountZztbPo.class)
    @GetMapping("/lookInfo/{id}")
    public AjaxResult lookInfo(@PathVariable Long id) {
        AssetOfficialAccountZztbPo byId = assetOfficialAccountZztbService.getById(id);
        List<AssetOfficialAccountMenu> a1 = new ArrayList<>();
        String[] s1 = byId.getCdmc().split("\\|");
        String[] s2 = byId.getCdlj().split("\\|");
        String[] s3 = byId.getCdlx().split("\\|");
        for (int i = 0; i < s1.length; i++) {
            AssetOfficialAccountMenu as = new AssetOfficialAccountMenu();
            if (s1[i] != null && !Objects.equals(s1[i], "")) {
                as.setCdmc(s1[i]);
            }
            if (s2[i] != null && !Objects.equals(s2[i], "")) {
                as.setCdlj(s2[i]);
            }
            if (s3[i] != null && !Objects.equals(s3[i], "")) {
                as.setCdlx(s3[i]);
            }
            a1.add(as);
        }
        byId.setCdList(a1);
        return success(byId);
    }

    /**
     * 管理端审核
     *
     * @param as 查询实体
     * @return 所有数据
     */
    @PreAuthorize("@ss.hasAnyRoles('admin,common')")
    @ApiOperation(value = "管理端审核")
    @PostMapping("/audit")
    public AjaxResult audit(@Valid @RequestBody AssetAuditRequest as) {
        AssetOfficialAccountZztbPo ass = new AssetOfficialAccountZztbPo();
        BeanUtil.copyProperties(as, ass);
        ass.setAccountId(as.getCurrentId());
        assetOfficialAccountZztbService.updateById(ass);
        //通过数据同步
        if ("2".equals(as.getAuditState()) && as.getXzType() != 1) {
            AssetOfficialAccountJyPo byId = assetOfficialAccountJyService.getById(as.getCurrentId());
            AssetOfficialAccount aa = new AssetOfficialAccount();
            BeanUtil.copyProperties(byId, aa);
            aa.setId(byId.getAssetId());
            //修改主表
            aa.setDelFlag("0");
            assetOfficialAccountService.updateById(aa);
            //如果有任务也修改任务这边
            AssetOfficialAccountJyPo one = assetOfficialAccountJyService.lambdaQuery()
                    .isNotNull(AssetOfficialAccountJyPo::getTaskId)
                    .ne(AssetOfficialAccountJyPo::getStatus, 5)
                    .eq(AssetOfficialAccountJyPo::getAssetId, byId.getAssetId())
                    .orderByDesc(AssetOfficialAccountJyPo::getAccountId)
                    .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.getAccountId();
                    BeanUtil.copyProperties(byId, one);
                    one.setAccountId(appId);
                    one.setTaskId(taskId);
                    one.setAuditState(null);
                    one.setAuditYy(null);
                    one.setStatus(status);
                    assetOfficialAccountJyService.updateById(one);
                }

            }
        }
        else if("2".equals(as.getAuditState()) ) {
            AssetOfficialAccountZztbPo byId = assetOfficialAccountZztbService.getById(as.getCurrentId());
            AssetOfficialAccount aa = new AssetOfficialAccount();
            BeanUtil.copyProperties(byId, aa);
            aa.setId(byId.getAssetId());
            //根据资产名称和所属单位查询主表是否有数据
            AssetOfficialAccount assetOfficialAccount = assetOfficialAccountService.lambdaQuery().eq(AssetOfficialAccount::getGzhmc, byId.getGzhmc()).eq(AssetOfficialAccount::getSsdw, byId.getSsdw()).one();
            if (assetOfficialAccount != null) {
                //修改主表
                if (assetOfficialAccount.getXzType() == 0) {

                    BeanUtil.copyProperties(aa, assetOfficialAccount, "id");
                    assetOfficialAccount.setXzType(0);
                    assetOfficialAccount.setDelFlag("0");
                    assetOfficialAccountService.updateById(assetOfficialAccount);

                } else {
                    BeanUtil.copyProperties(aa, assetOfficialAccount, "id");
                    assetOfficialAccount.setDelFlag("0");
                    assetOfficialAccountService.updateById(assetOfficialAccount);
                }

                //如果有任务也修改任务这边
                AssetOfficialAccountJyPo one = assetOfficialAccountJyService.lambdaQuery()
                        .ne(AssetOfficialAccountJyPo::getStatus, 5)
                        .eq(AssetOfficialAccountJyPo::getGzhmc, byId.getGzhmc())
                        .orderByDesc(AssetOfficialAccountJyPo::getAccountId)
                        .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.getAccountId();
                        BeanUtil.copyProperties(byId, one);
                        one.setAccountId(appId);
                        one.setTaskId(taskId);
                        one.setAuditState(null);
                        one.setAuditYy(null);
                        one.setStatus(status);
                        assetOfficialAccountJyService.updateById(one);
                    }

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


        }
        else if("3".equals(as.getAuditState()) ){
            AssetOfficialAccountZztbPo byId = assetOfficialAccountZztbService.getById(as.getCurrentId());
            AssetOfficialAccount aa = new AssetOfficialAccount();
            BeanUtil.copyProperties(byId, aa);
            aa.setId(byId.getAssetId());
            //根据资产名称和所属单位查询主表是否有数据
            AssetOfficialAccount assetOfficialAccount = assetOfficialAccountService.lambdaQuery().eq(AssetOfficialAccount::getGzhmc, byId.getGzhmc()).eq(AssetOfficialAccount::getSsdw, byId.getSsdw()).one();
            if (assetOfficialAccount != null) {
                //修改主表
                if (assetOfficialAccount.getXzType() == 0) {

                    BeanUtil.copyProperties(aa, assetOfficialAccount, "id");
                    assetOfficialAccount.setXzType(0);
                    assetOfficialAccount.setDelFlag("1");
                    assetOfficialAccountService.updateById(assetOfficialAccount);

                } else {
                    BeanUtil.copyProperties(aa, assetOfficialAccount, "id");
                    assetOfficialAccount.setDelFlag("1");
                    assetOfficialAccountService.updateById(assetOfficialAccount);
                }
            }
        }
        return success();
    }
    //=================================================

    /**
     * 新增公众号数据
     *
     * @param assetOfficialAccount 实体
     * @return 新增结果
     */
    @ApiOperation(value = "新增公众号数据")
    @PostMapping
    @Log(title = "新增公众号数据", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody AssetOfficialAccount assetOfficialAccount) {


        return success(assetOfficialAccountService.add(assetOfficialAccount));
    }

    /**
     * 编辑公众号数据
     *
     * @param assetOfficialAccount 实体
     * @return 编辑结果
     */
    @ApiOperation(value = "编辑公众号数据")
    @Log(title = "编辑公众号数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AssetOfficialAccount assetOfficialAccount) {
        //根据资产id查询资产子表,判断是否有此资产进行中的任务,如果资产状态是已关停与修改的数据不符，则修改任务中的资产状态
        List<AssetOfficialAccountCpPo> assetOfficialAccountCpPo = assetOfficialAccountCpService.findDwmc(assetOfficialAccount.getId());
        if (assetOfficialAccountCpPo != null) {
            for (AssetOfficialAccountCpPo s : assetOfficialAccountCpPo) {

                //查询任务是否为进行中
                AssetTask assetTask = assetTaskService.findByTaskId(s.getTaskId());
                if (assetTask != null) {

                    if (assetTask.getTaskStatus().equals(1)) {

                        //修改任务中资产状态
                        s.setStatus(0);
                        s.setBtgyy(null);
                        s.setBtgyy(null);

                        s.setUpdateTime(null);
                        assetTask.setTaskStatus(1);
                        assetTaskService.update(assetTask);
                        s.setAccountId(s.getAccountId());
                        assetOfficialAccountCpService.updateById(s);

                    }
                }
            }
        }
        return success(assetOfficialAccountService.edit(assetOfficialAccount));
    }

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

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

    /**
     * app导出
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "公众号导出")
    @Log(title = "公众号导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AssetOfficialAccountPageRequest unit) {
        List<AssetOfficialAccount> list = assetOfficialAccountService.getAllList(unit);
        ExcelUtil<AssetOfficialAccount> util = new ExcelUtil<>(AssetOfficialAccount.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<AssetOfficialAccount> util = new ExcelUtil<>(AssetOfficialAccount.class);
        List<AssetOfficialAccount> list = util.importExcel(file.getInputStream());
        if (list != null) {
            list.forEach(x -> {
                AssetOfficialAccount one = assetOfficialAccountService.lambdaQuery().eq(AssetOfficialAccount::getSsdw, x.getSsdw())
                        .eq(AssetOfficialAccount::getGzhmc, x.getGzhmc()).one();
                if (one != null) {
                    x.setId(one.getId());
                    assetOfficialAccountService.edit(x);
                } else {
                    assetOfficialAccountService.add(x);
                }
            });
        } else {
            throw new ServiceException("公众号导入数据不能为空!");
        }
        return AjaxResult.success("导入成功");
    }
}

