package com.tofly.feesapi.bjgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tofly.feesapi.common.core.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.bjgl.entity.YhBjflFb;
import com.tofly.feesapi.bjgl.entity.YhBjflZb;
import com.tofly.feesapi.bjgl.entity.dto.YhBjflZbFilter;
import com.tofly.feesapi.bjgl.entity.vo.YhBjflZbSelect;
import com.tofly.feesapi.bjgl.service.YhBjflFbService;
import com.tofly.feesapi.bjgl.service.YhBjflZbService;
import com.tofly.feesapi.common.core.dto.PageDto;
import com.tofly.feesapi.common.core.vo.PageResult;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;
import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.xtgl.service.ISyscommlogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("/yhbjflzb")
@Api(tags = "用户表分类(总分类表、子母表)主表接口")
public class YhBjflZbController {

    @Autowired
    private YhBjflZbService yhBjflZbService;
    @Autowired
    private YhBjflFbService yhBjflFbService;

    @Autowired
    private ISyscommlogService syscommlogService;

    @GetMapping("/page")
    @ApiOperation(value = "分页查询", tags = "档案管理")
    public ResultRespone<PageResult<YhBjflZbSelect>> getPage(@ModelAttribute PageDto pageDto,
                                                             @ModelAttribute YhBjflZbFilter filter) {
        return ResultRespone.success(yhBjflZbService.getPage(pageDto, filter));
    }

    @PostMapping
    @ApiOperation(value = "添加用户表分类(总分类表、子母表)主表", tags = "档案管理")
    public ResultRespone save(@RequestBody YhBjflZb yhBjflZb) {
        if (StringUtil.isEmpty(yhBjflZb.getYhbh())) {
            throw new FeesException("用户编号不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(yhBjflZb.getCbkh())) {
            throw new FeesException("抄表卡号不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(yhBjflZb.getTypeId())) {
            throw new FeesException("分类1总分表2子母表不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        long count = yhBjflZbService.count(
                Wrappers.<YhBjflZb>lambdaQuery()
                        .eq(YhBjflZb::getYhbh, yhBjflZb.getYhbh())
                        .eq(YhBjflZb::getCbkh, yhBjflZb.getCbkh())
                        .eq(YhBjflZb::getTypeId, yhBjflZb.getTypeId())
        );
        if (count > 0) {
            if (yhBjflZb.getTypeId().equals("1")) {
                throw new FeesException("总表已存在，不能重复添加总表！", FeesErrorCode.BUSINESS_ERROR);
            } else {
                throw new FeesException("母表已存在，不能重复添加母表！", FeesErrorCode.BUSINESS_ERROR);
            }
        }
        yhBjflZb.setCzry(SecurityUtils.getUserId().toString());
        yhBjflZb.setCzryxm(SecurityUtils.getUser().getRealName());
        yhBjflZb.setCzsj(new Date());
        yhBjflZb.setId(yhBjflZbService.getMaxid());
        String tablename = "yh_bjfl_zb";
        if (yhBjflZb.getTypeId().equals("1")) {
            String remark = String.format("%s-添加总表户号：%s",
                    SecurityUtils.getUser().getRealName(),
                    yhBjflZb.getYhbh()
            );
            syscommlogService.LogSave(tablename, "添加总表户号", "ADD", remark, "");
        } else {
            String remark = String.format("%s-添加母表户号：%s",
                    SecurityUtils.getUser().getRealName(),
                    yhBjflZb.getYhbh());
            syscommlogService.LogSave(tablename, "添加母表户号", "ADD", remark, "");
        }
        return ResultRespone.success(yhBjflZbService.save(yhBjflZb));
    }

    @ApiOperation(value = "通过ID删除用户表分类(总分类表、子母表)主表", tags = "档案管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String")
    })
    @DeleteMapping("/{id}")
    public ResultRespone removeById(@PathVariable String id) {
        long count = yhBjflFbService.count(
                new QueryWrapper<YhBjflFb>()
                        .lambda().eq(YhBjflFb::getZbId, id)
        );
        if (count > 0) {
            throw new FeesException("该用户表分类(总分类表、子母表)主表下有子表，不能删除", FeesErrorCode.BUSINESS_ERROR);
        }
        YhBjflZb yhBjflzb = yhBjflZbService.getById(id);
        String tablename = "yh_bjfl_zb";
        if (yhBjflzb.getTypeId().equals("1")) {
            String remark = String.format("%s-删除总表户号：%s",
                    SecurityUtils.getUser().getRealName(),
                    yhBjflzb.getYhbh());
            syscommlogService.LogSave(tablename, "删除总表户号", "DELETE", remark, "");
        } else {
            String remark = String.format("%s-删除母表户号：%s",
                    SecurityUtils.getUser().getRealName(),
                    yhBjflzb.getYhbh());
            syscommlogService.LogSave(tablename, "删除母表户号", "DELETE", remark, "");
        }
        return ResultRespone.success(yhBjflZbService.removeById(id));
    }


    @ApiOperation(value = "通过ID批量删除用户表分类(总分类表、子母表)主表", tags = "档案管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds")
    public ResultRespone removeByIds(String ids) {
        long count = yhBjflFbService.count(
                new QueryWrapper<YhBjflFb>()
                        .lambda().in(YhBjflFb::getZbId, Arrays.stream(ids.split(",")))
        );
        if (count > 0) {
            throw new FeesException("存在用户表分类(总分类表、子母表)主表下有子表，不能删除", FeesErrorCode.BUSINESS_ERROR);
        }
        List<YhBjflZb> yhBjflzbs = yhBjflZbService.lambdaQuery()
                .in(YhBjflZb::getId, Arrays.asList(ids.split(",")))
                .list();
        if (yhBjflzbs.size() > 0) {
            String tablename = "yh_bjfl_fb";
            count = yhBjflzbs.stream().filter(e -> e.getTypeId().equals("1")).count();
            if (count > 0) {
                String remark = String.format("%s-删除总表户号：%s",
                        SecurityUtils.getUser().getRealName(),
                        Arrays.toString(yhBjflzbs.stream().filter(e -> e.getTypeId().equals("1")).map(YhBjflZb::getYhbh).toArray()));
                syscommlogService.LogSave(tablename, "删除总表户号", "DELETE", remark, "");
            }
            count = yhBjflzbs.stream().filter(e -> e.getTypeId().equals("2")).count();
            if (count > 0) {
                String remark = String.format("%s-删除母表户号：%s",
                        SecurityUtils.getUser().getRealName(),
                        Arrays.toString(yhBjflzbs.stream().filter(e -> e.getTypeId().equals("2")).map(YhBjflZb::getYhbh).toArray()));
                syscommlogService.LogSave(tablename, "删除母表户号", "DELETE", remark, "");
            }
        }

        return ResultRespone.success(yhBjflZbService.removeByIds(Arrays.asList(ids.split(","))));
    }
}
