/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.xrtymis.custom.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.xrtymis.custom.service.GdflowconfigService;
import com.tofly.xrtymis.custom.service.GdgltypebmService;
import com.tofly.xrtymis.entity.Gdflowconfig;
import com.tofly.xrtymis.entity.Gdgltypebm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;

/**
 * 业务工单类型编码表
 *
 * @author fu
 * @date Sat Mar 20 00:00:00 CST 2021
 */
@RestController
@RequestMapping("/gdgltypebm")
@Api(tags="业务工单类型编码表接口")
public class GdgltypebmController {
    @Autowired
    private  GdgltypebmService gdgltypebmService;

    @Autowired
    private GdflowconfigService gdflowconfigService;


    /**
     * 分页查询
     * @param page 分页对象
     * @param gdgltypebm 业务工单类型编码表
     * @return
     */
    @GetMapping("/page" )
    @ApiOperation(value = "分页查询")
    public ResultRespone getGdgltypebmPage(Page page, @ModelAttribute Gdgltypebm gdgltypebm) {
        if(StringUtils.isEmpty(gdgltypebm.getDataType())){
            gdgltypebm.setDataType("0");
        }
        String viewType = null;
        if (StringUtil.isNotEmpty(gdgltypebm.getViewType())){
            viewType = gdgltypebm.getViewType();
            gdgltypebm.setViewType(null);
        }
        gdgltypebm.setStatusFlag(null);
        return ResultRespone.success(gdgltypebmService.page(page, Wrappers.query(gdgltypebm).lambda()
                .eq(Gdgltypebm::getStatusFlag,"1").like(StringUtil.isNotEmpty(viewType) , Gdgltypebm::getViewType , viewType)
                .orderByAsc(Gdgltypebm::getCreateTime)));
    }

    /**
     * 不分页查询
     * @return
     */
    @GetMapping("/getGdgltypebmAll" )
    @ApiOperation(value = "不分页查询")
    public ResultRespone getGdgltypebmAll(@ModelAttribute Gdgltypebm gdgltypebm) {
        if(StringUtils.isEmpty(gdgltypebm.getDataType())){
            gdgltypebm.setDataType("0");
        }
        String viewType = null;
        if (StringUtil.isNotEmpty(gdgltypebm.getViewType())){
            viewType = gdgltypebm.getViewType();
            gdgltypebm.setViewType(null);
        }
        gdgltypebm.setStatusFlag(null);
        return ResultRespone.success(gdgltypebmService.list(Wrappers.query(gdgltypebm).lambda()
                .eq(Gdgltypebm::getStatusFlag,"1").like(StringUtil.isNotEmpty(viewType) , Gdgltypebm::getViewType , viewType)
                .orderByAsc(Gdgltypebm::getCreateTime)));
    }

    /**
     * 通过id查询业务工单类型编码表
     * @param gdlxBm id
     * @return ResultRespone
     */
    @GetMapping("/{gdlxBm}" )
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gdlxBm", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone getById(@PathVariable("gdlxBm" ) Long gdlxBm) {
      return ResultRespone.success(gdgltypebmService.getById(gdlxBm));
    }

    /**
     * 新增业务工单类型编码表
     * @param gdgltypebm 业务工单类型编码表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="新增业务工单类型编码表" )
    @ApiOperation(value = "新增业务工单类型编码表")
    @PostMapping
    public ResultRespone save(@RequestBody Gdgltypebm gdgltypebm) {
        if(gdgltypebm.getGdlxId()==null){
            gdgltypebm.setGdlxId(0l);
        }
        if(StringUtils.isEmpty(gdgltypebm.getDataType())){
            gdgltypebm.setDataType("0");
        }
        if(StringUtils.isEmpty(gdgltypebm.getGdlxMc())){
            return ResultRespone.failed("创建的类型名称不能为空");
        }
        if(StringUtils.isEmpty(gdgltypebm.getDataType())){
            gdgltypebm.setDataType("0");
        }
        if(gdgltypebm.getGdlxId()!=0){
            Gdgltypebm gdf = gdgltypebmService.getById(gdgltypebm.getGdlxId());
            if(gdf==null){
                return ResultRespone.failed("父级类型不存在");
            }else if(!gdf.getDataType().equals(gdgltypebm.getDataType())){
                return ResultRespone.failed("父级与子级类型的DataType不一致");
            }
        }
        Gdgltypebm gd = gdgltypebmService.getOne(new QueryWrapper<Gdgltypebm>().lambda().eq(Gdgltypebm::getGdlxMc,gdgltypebm.getGdlxMc())
                .eq(Gdgltypebm::getGdlxId,gdgltypebm.getGdlxId()).eq(Gdgltypebm::getStatusFlag,"1").eq(Gdgltypebm::getDataType,gdgltypebm.getDataType()));
        if (gd!=null){
            return ResultRespone.failed("创建的类型名称重复");
        }
      return ResultRespone.success(gdgltypebmService.save(gdgltypebm));
    }

    /**
     * 修改业务工单类型编码表
     * @param gdgltypebm 业务工单类型编码表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="修改业务工单类型编码表" )
    @ApiOperation(value = "修改业务工单类型编码表")
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone updateById(@RequestBody Gdgltypebm gdgltypebm) {
        try {
            Gdgltypebm gd = null;
            if (StringUtils.isEmpty(gdgltypebm.getDataType())) {
                gdgltypebm.setDataType("0");
            }

            Gdgltypebm gtype = gdgltypebmService.getById(gdgltypebm.getId());
            if (gtype == null || "0".equals(gtype.getStatusFlag())) {
                return ResultRespone.failed(false, "数据不存在");
            } else if (!gtype.getGdlxId().equals(0) && !gdgltypebm.getDataType().equals(gtype.getDataType())) {
                return ResultRespone.failed(false, "存在父节点不允许修改dataType数据类型!");
            } else if (gtype.getGdlxId().equals(0) && !gdgltypebm.getDataType().equals(gtype.getDataType())) {
                int count = gdgltypebmService.count(new QueryWrapper<Gdgltypebm>().lambda()
                        .eq(Gdgltypebm::getGdlxId, gdgltypebm.getId()));
                if (count > 0) {
                    return ResultRespone.failed(false, "存在子节点不允许修改dataType数据类型!");
                }
            }
            if (!StringUtils.isEmpty(gdgltypebm.getGdlxMc())) {
                if (gdgltypebm.getGdlxId() == null) {
                    gdgltypebm.setGdlxId(0l);
                }
                gd = gdgltypebmService.getOne(new QueryWrapper<Gdgltypebm>().lambda().eq(Gdgltypebm::getGdlxMc, gdgltypebm.getGdlxMc())
                        .eq(Gdgltypebm::getGdlxId, gdgltypebm.getGdlxId()).eq(Gdgltypebm::getStatusFlag, "1"));
            }

            if ("0".equals(gdgltypebm.getYxbz())) {
                int count = gdgltypebmService.count(new QueryWrapper<Gdgltypebm>().lambda()
                        .eq(Gdgltypebm::getGdlxId, gdgltypebm.getId()).eq(Gdgltypebm::getStatusFlag, "1").eq(Gdgltypebm::getYxbz, "1"));
                if (count > 0) {
                    return ResultRespone.failed(false, "存在未禁用子节点");
                }
            } else if ("1".equals(gdgltypebm.getYxbz()) && (gdgltypebm.getGdlxId() != null && gdgltypebm.getGdlxId() != 0)) {
                int count = gdgltypebmService.count(new QueryWrapper<Gdgltypebm>().lambda().eq(Gdgltypebm::getStatusFlag, "1")
                        .eq(Gdgltypebm::getId, gdgltypebm.getGdlxId()).eq(Gdgltypebm::getYxbz, "1"));
                if (count == 0) {
                    return ResultRespone.failed(false, "父节点未启用");
                }
            }
           /* else if ("1".equals(gdgltypebm.getYxbz())) {
                int count = gdgltypebmService.count(new QueryWrapper<Gdgltypebm>().lambda().eq(Gdgltypebm::getStatusFlag, "1")
                        .eq(Gdgltypebm::getId, gdgltypebm.getId()).eq(Gdgltypebm::getGdlxId, 0));
                if (count == 0) {
                    return ResultRespone.failed(false, "");
                }

            }*/
            /**
             * @author WJL
             * @date 2021-10-28 14:12:50
             * 修改之前的 gd.getId()==gdgltypebm.getId()
             * 由于部分 id 已经超过Long的缓存范围128了；使用==比较不出来
             * 修改之后的 gd.getId().equals(gdgltypebm.getId()
             */
            if (gd == null || gd.getId().equals(gdgltypebm.getId())) {
                //修改工单类型
                boolean flag = gdgltypebmService.updateById(gdgltypebm);
                if (flag) {
                    Long id = gdgltypebm.getId();
                    //修改流程配置中的viewType;
                    String viewType = gdgltypebm.getViewType();
                    //判断第几级
                    Long gdlxId = gdgltypebm.getGdlxId();
                    if (gdlxId.equals(0L)) {
                        gdflowconfigService.update(Wrappers.<Gdflowconfig>lambdaUpdate().eq(Gdflowconfig::getGdlx, id)
                                .set(StringUtil.isNotEmpty(viewType), Gdflowconfig::getViewType, viewType)
                                .set(StringUtil.isEmpty(viewType), Gdflowconfig::getViewType, ""));
                    } else {
                        Gdgltypebm gdgltypebmServiceById = gdgltypebmService.getById(gdlxId);
                        if (gdgltypebmServiceById.getGdlxId().equals(0L)) {
                            gdflowconfigService.update(Wrappers.<Gdflowconfig>lambdaUpdate().eq(Gdflowconfig::getGdxf1, id)
                                    .set(StringUtil.isNotEmpty(viewType), Gdflowconfig::getViewType, viewType)
                                    .set(StringUtil.isEmpty(viewType), Gdflowconfig::getViewType, ""));
                        } else {
                            gdflowconfigService.update(Wrappers.<Gdflowconfig>lambdaUpdate().eq(Gdflowconfig::getGdxf2, id)
                                    .set(StringUtil.isNotEmpty(viewType), Gdflowconfig::getViewType, viewType)
                                    .set(StringUtil.isEmpty(viewType), Gdflowconfig::getViewType, ""));
                        }
                    }
                }
                return ResultRespone.success();
            } else {
                return ResultRespone.failed(false, "可能是同级类型名称重复了");
            }
        }catch (Exception e) {
            e.printStackTrace();
            return ResultRespone.failed(e.getMessage());
        }
    }

    /**
     * 通过id删除业务工单类型编码表
     * @param gdlxBm id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除业务工单类型编码表" )
    @ApiOperation(value = "通过ID删除业务工单类型编码表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gdlxBm", value = "ID", required = true, dataType = "Long")
    })
    @DeleteMapping("/{gdlxBm}" )
    public ResultRespone removeById(@PathVariable Long gdlxBm) {
        int count = gdgltypebmService.count(new QueryWrapper<Gdgltypebm>().lambda().eq(Gdgltypebm::getGdlxId,gdlxBm).eq(Gdgltypebm::getStatusFlag,"1"));
        int ct = gdflowconfigService.count(new QueryWrapper<Gdflowconfig>().lambda().and(wp->wp.eq(Gdflowconfig::getGdlx,gdlxBm).or().eq(Gdflowconfig::getGdxf1,gdlxBm)));

        if(count>0||ct>0){
            return ResultRespone.success(false);
        }
      return ResultRespone.success(gdgltypebmService.update(new UpdateWrapper<Gdgltypebm>().lambda().set(Gdgltypebm::getStatusFlag,"0").eq(Gdgltypebm::getId,gdlxBm)));
    }

    /**
     * 通过id批量删除业务工单类型编码表
     * @param ids id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id批量删除业务工单类型编码表" )
    @ApiOperation(value = "通过ID批量删除业务工单类型编码表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds" )
    public ResultRespone removeByIds(String ids) {
        //判断有子集的不能删除
        List list = Arrays.asList(ids.split(","));
        int count=gdgltypebmService.count(new QueryWrapper<Gdgltypebm>().lambda().in(Gdgltypebm::getGdlxId,list).eq(Gdgltypebm::getStatusFlag,"1"));
        if(count>0){
            return ResultRespone.failed(false,"当前类型下有工单类型细分，不能删除");
        }
        //TODO 不知道那位大神写的代码，表中明确了逻辑删除，这里判断查询又不写，到处都是bug.........
        //int ct = gdflowconfigService.count(new QueryWrapper<Gdflowconfig>().lambda().and(wp->wp.in(Gdflowconfig::getGdlx,list).or().in(Gdflowconfig::getGdxf1,list).or()));
        int ct = gdflowconfigService.count(Wrappers.<Gdflowconfig>lambdaQuery()
                .eq(Gdflowconfig::getSfDelete,"1")
                .and(gdflowconfigLambdaQueryWrapper -> gdflowconfigLambdaQueryWrapper.in(Gdflowconfig::getGdlx,list)
                        .or().in(Gdflowconfig::getGdxf1,list)));
        if (ct > 0){
            return ResultRespone.failed(false,"当前类型或细分下有配置流程，不能删除");
        }
        return ResultRespone.success(gdgltypebmService.update(new UpdateWrapper<Gdgltypebm>().lambda().set(Gdgltypebm::getStatusFlag,"0").in(Gdgltypebm::getId,Arrays.asList(ids.split(",")))));
    }

    /**
     * 获取树形结构的工单类型数据
     */
    @GetMapping("/getGdgltypeTree" )
    @ApiOperation(value = "获取树形结构的工单类型数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yxbz", value = " 有效标记标志 1启用或空", required = false, dataType = "String"),
            @ApiImplicitParam(name = "dataType", value = " 数据类型；0:业务工单类型;1:归档故障类型 默认0", required = false, dataType = "String")
    })
    public ResultRespone getGdgltypeTree( String yxbz,String dataType,String viewType) throws InvocationTargetException, IllegalAccessException {
        return gdgltypebmService.getGdgltypeTree(yxbz,dataType,viewType);
    }


//    @ApiOperation(value = "批量导入工单类型")
//    @PostMapping("/orderTypeImport")
//    public ResultRespone orderTypeImport(MultipartFile file){
//        return ResultRespone.success(gdgltypebmService.orderTypeImport(file));
//    }

}
