package com.tofly.feesapi.bjgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.dto.YhBjflFbFilter;
import com.tofly.feesapi.bjgl.entity.vo.YhBjflFbSelect;
import com.tofly.feesapi.bjgl.service.YhBjflFbService;
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 com.tofly.feesapi.yhgl.entity.YhGroupAccounts;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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

    @Autowired
    private YhBjflFbService yhBjflFbService;

    @Autowired
    private ISyscommlogService syscommlogService;

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

    @PostMapping
    @ApiOperation(value = "添加用户表具分类(总分表、子母表)分表")
    @Transactional
    public ResultRespone<Boolean> save(@RequestBody List<YhBjflFb> yhBjflFbList) {
        if (yhBjflFbList.isEmpty()) {
            throw new FeesException("用户表具分类(总分表、子母表)分表不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        //分表
        List<String> fblist = new ArrayList<>();
        //子表
        List<String> zblist = new ArrayList<>();
        for (YhBjflFb yhBjflFb : yhBjflFbList) {
            if (StringUtil.isEmpty(yhBjflFb.getZbId())) {
                throw new FeesException("主表ID不能为空！", FeesErrorCode.BUSINESS_ERROR);
            }
            if (StringUtil.isEmpty(yhBjflFb.getZbYhbh())) {
                throw new FeesException("主表用户编号不能为空！", FeesErrorCode.BUSINESS_ERROR);
            }
            if (StringUtil.isEmpty(yhBjflFb.getZbCbkh())) {
                throw new FeesException("主表抄表卡号不能为空！", FeesErrorCode.BUSINESS_ERROR);
            }
            if (StringUtil.isEmpty(yhBjflFb.getYhbh())) {
                throw new FeesException("用户编号不能为空！", FeesErrorCode.BUSINESS_ERROR);
            }
            if (StringUtil.isEmpty(yhBjflFb.getCbkh())) {
                throw new FeesException("抄表卡号不能为空！", FeesErrorCode.BUSINESS_ERROR);
            }
            if (StringUtil.isEmpty(yhBjflFb.getTypeId())) {
                throw new FeesException("分类1总分分表2子母表不能为空！", FeesErrorCode.BUSINESS_ERROR);
            }
            long count = yhBjflFbService.count(
                    new QueryWrapper<YhBjflFb>()
                            .lambda()
                            .eq(YhBjflFb::getYhbh, yhBjflFb.getYhbh())
                            .eq(YhBjflFb::getCbkh, yhBjflFb.getCbkh())
                            .eq(YhBjflFb::getTypeId, yhBjflFb.getTypeId())
            );
            if (count > 0) {
                if (yhBjflFb.getTypeId().equals("1")) {
                    throw new FeesException("分表已存在，不能重复添加分表！", FeesErrorCode.BUSINESS_ERROR);
                } else {
                    throw new FeesException("子表已存在，不能重复添加子表！", FeesErrorCode.BUSINESS_ERROR);
                }
            }
            yhBjflFb.setId(yhBjflFbService.getMaxid());
            yhBjflFbService.save(yhBjflFb);
            if (yhBjflFb.getTypeId().equals("1")) {
                fblist.add(yhBjflFb.getYhbh());
            } else {
                zblist.add(yhBjflFb.getYhbh());
            }
        }
        String tablename = "yh_bjfl_fb";
        if (fblist.size() > 0) {
            String remark = String.format("%s-添加分表户号：%s",
                    SecurityUtils.getUser().getRealName(),
                    Arrays.toString(fblist.toArray())
            );
            syscommlogService.LogSave(tablename, "添加分表户号", "ADD", remark, "");
        }
        if (zblist.size() > 0) {
            String remark = String.format("%s-添加分表户号：%s",
                    SecurityUtils.getUser().getRealName(),
                    Arrays.toString(zblist.toArray()));
            syscommlogService.LogSave(tablename, "添加子表户号", "ADD", remark, "");
        }
        return ResultRespone.success(true);
    }

    @ApiOperation(value = "通过ID删除用户表具分类(总分表、子母表)分表" ,tags = "档案管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String")
    })
    @DeleteMapping("/{id}")
    public ResultRespone<Boolean> removeById(@PathVariable String id) {
        return ResultRespone.success(yhBjflFbService.removeById(id));
    }

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