package com.tofly.feesapi.bjgl.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.common.core.ResultRespone;

import com.tofly.feesapi.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bjgl.entity.YhCbkxx2;
import com.tofly.feesapi.bjgl.entity.YhDaCbkxxSelect;
import com.tofly.feesapi.bjgl.entity.dto.*;
import com.tofly.feesapi.bjgl.entity.vo.YhCbkxxSelect2;
import com.tofly.feesapi.bjgl.entity.vo.YhCbkxxView;
import com.tofly.feesapi.bjgl.mapper.YhCbkxxMapper;
import com.tofly.feesapi.bjgl.service.YhCbkxxService;
import com.tofly.feesapi.cbgl.entity.YyCblr;
import com.tofly.feesapi.cbgl.service.YyCblrService;
import com.tofly.feesapi.common.constant.CbbzEnum;
import com.tofly.feesapi.common.constant.JsbzEnum;
import com.tofly.feesapi.common.constant.ShbzEnum;
import com.tofly.feesapi.common.core.dto.PageDto;
import com.tofly.feesapi.common.core.vo.PageResult;

import com.tofly.feesapi.xtgl.entity.SysGdcsb;
import com.tofly.feesapi.xtgl.mapper.SysGdcsbMapper;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.mapper.YhKhjbxxMapper;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import com.tofly.feesapi.znbgl.service.ZnbDaLogService;
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.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

@RestController
@AllArgsConstructor
@RequestMapping("api/bjgl/yhcbkxx")
@Api(tags = "水表档案-水表档案")
public class YhCbkxxController {

    @Autowired
    private YhCbkxxService yhCbkxxService;
    @Autowired
    private YhCbkxxMapper yhCbkxxMapper;
    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YhKhjbxxMapper yhKhjbxxMapper;
    @Autowired
    private YyCblrService yyCblrService;
    @Autowired
    private ZnbDaLogService znbDaLogService;
    @Autowired
    private SysGdcsbMapper sysGdcsbMapper;

    @ApiOperationSupport(order = 5)
    @GetMapping("/page")
    @ApiOperation(value = "查询水表档案（分页）", tags = {"抄表序号调整", "批量设置水价", "用户换表"})
    public ResultRespone<PageResult<YhCbkxxSelect2>> getPage(@ModelAttribute PageDto pageDto, @ModelAttribute YhCbkxxFilter filter) {
        List<String> list = new ArrayList<>();
        if (StringUtil.isNotEmpty(filter.getSfspb())) {
            if (filter.getSfspb().equals("0")) {
                list = Arrays.asList("2", "3");
            }
            if (filter.getSfspb().equals("1")) {
                list = Arrays.asList("0");
            }
        }
        return ResultRespone.success(yhCbkxxService.getPage(pageDto, filter, list));
    }

    @GetMapping("/{yhbh}")
    @ApiOperation(value = "查看水表档案", tags = {"综合查询"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "用户编号", required = true, dataType = "String")
    })
    public ResultRespone<YhCbkxxView> getById(@PathVariable("yhbh") String yhbh) {
        return ResultRespone.success(yhCbkxxService.getViewById(yhbh));
    }

    @GetMapping("/{yhbh}/{cbkh}")
    @ApiOperation(value = "水表-用户编号、抄表卡号查看")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "用户编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cbkh", value = "抄表卡号", required = true, dataType = "String")
    })
    public ResultRespone getDaMeter(@PathVariable("yhbh") String yhbh, @PathVariable("cbkh") String cbkh) {
        YhCbkxx2 yhCbkxx2 = yhCbkxxMapper.SelectYhcbkxx(yhbh, cbkh);
        return ResultRespone.success(yhCbkxx2);
    }

    @GetMapping("/hbgl/{yhbh}/{cbkh}")
    @ApiOperation(value = "换表-用户编号、抄表卡号查看")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "用户编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cbkh", value = "抄表卡号", required = true, dataType = "String")
    })
    public ResultRespone getDaMeter2(@PathVariable("yhbh") String yhbh, @PathVariable("cbkh") String cbkh) {

        YhDaCbkxxSelect yhDaCbkxxSelect = yhCbkxxMapper.SelectYhdaSbda(yhbh, cbkh);
        return ResultRespone.success(yhDaCbkxxSelect);
    }

    @GetMapping("/hbgl/page")
    @ApiOperation(value = "换表page分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页显示数据条数", required = true, dataType = "int"),
            @ApiImplicitParam(name = "pages", value = "共几页,输出参数", dataType = "int"),
            @ApiImplicitParam(name = "maxLimit", value = "每页最大显示数据", dataType = "int"),
            @ApiImplicitParam(name = "orders[0].asc", value = "排序,bool类型", dataType = "String"),
            @ApiImplicitParam(name = "orders[0].column", value = "排序,字段名", dataType = "String"),
            @ApiImplicitParam(name = "ssgs", value = "所属公司", dataType = "String"),
            @ApiImplicitParam(name = "sscbpq", value = "片区", dataType = "String"),
            @ApiImplicitParam(name = "sscbb", value = "抄表本", dataType = "String"),
            @ApiImplicitParam(name = "searchText", value = "模糊查询(用户编号、用户姓名、用户地址、联系电话)", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "Date"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "Date")
    })
    public ResultRespone getDaCustomerPage(Page page, String ssgs, String sscbpq, String sscbb, String searchText,
                                           Date startDate, Date endDate) {
        IPage<YhDaCbkxxSelect> yhdaPage = yhCbkxxMapper.getYhdaSbdaPage(page, ssgs, sscbpq, sscbb, searchText, startDate, endDate);
        return ResultRespone.success(yhdaPage);
    }

    @ApiOperation(value = "新增用户表计信息")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping
    public ResultRespone save(@RequestBody YhCbkxx yhCbkxx) {
        if (StrUtil.isEmpty(yhCbkxx.getSbyt())) {
            yhCbkxx.setSbyt("1");
        }

        yhCbkxxService.save(yhCbkxx);

        // 卡表不用添加抄表计划
        if (yhCbkxx.getSblb().equals("1")) {
            return ResultRespone.success(true);
        }

        YhKhjbxx yhKhjbxx = yhKhjbxxService.getById(yhCbkxx.getYhbh());

        YyCblr yyCblr = new YyCblr();
        yyCblr.setYhbh(yhKhjbxx.getYhbh());
        yyCblr.setCbkh(yhCbkxx.getCbkh());
        yyCblr.setCbkid(yhCbkxx.getCbkid());

        LambdaQueryWrapper<SysGdcsb> wrapper = Wrappers.<SysGdcsb>lambdaQuery()
                .eq(SysGdcsb::getGdbz, "0");
        SysGdcsb sysGdcsb = sysGdcsbMapper.selectOne(wrapper);
        String strcwrq = sysGdcsb.getCwrq();

        yyCblr.setCwrq(strcwrq);
        yyCblr.setJsbz(JsbzEnum.未算费);
        yyCblr.setJfzt("1");
        yyCblr.setCbbz(CbbzEnum.未抄表);
        yyCblr.setShbz(ShbzEnum.未审核);
        yyCblr.setSsgs(yhKhjbxx.getSsgs());
        yyCblr.setSscbpq(yhKhjbxx.getSscbpq());
        yyCblr.setSscbb(yhKhjbxx.getSscbb());
        yyCblr.setXbqd(BigDecimal.valueOf(yhCbkxx.getSbqs()));

        yyCblrService.save(yyCblr);

        // 远传表或物联网表生成智能表档案
        if (yhCbkxx.getSblb().equals("2") || yhCbkxx.getSblb().equals("3")) {
            znbDaLogService.addznbDaLog(yhKhjbxx, yhCbkxx, "0");
        }
        return ResultRespone.success(true);
    }

    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "修改水表档案")
    @PutMapping
    public ResultRespone<Boolean> update(@RequestBody YhCbkxx yhCbkxx) {
        if (StringUtils.isBlank(yhCbkxx.getCbkh()) || StringUtils.isBlank(yhCbkxx.getYhbh())) {
            return ResultRespone.failed("修改失败，cbkh或yhbh不能为空！");
        }
        LambdaQueryWrapper<YhCbkxx> queryWrapper = Wrappers.<YhCbkxx>lambdaQuery()
                .eq(YhCbkxx::getYhbh, yhCbkxx.getYhbh())
                .eq(YhCbkxx::getCbkh, yhCbkxx.getCbkh());
        YhCbkxx oldyhCbkxx = yhCbkxxService.getOne(queryWrapper);

        if (!oldyhCbkxx.getSblb().equals(yhCbkxx.getSblb())) {
            return ResultRespone.failed("修改失败，不能修改水表类型！");
        }

        yhCbkxxService.update(yhCbkxx, queryWrapper);
        String sblb = yhCbkxx.getSblb();
        if (StrUtil.isNotEmpty(sblb) && (sblb.equals("2") || sblb.equals("3"))) {
            YhKhjbxx yhKhjbxx = yhKhjbxxService.getById(yhCbkxx.getYhbh());
            // 添加智能表档案
            znbDaLogService.addznbDaLog(yhKhjbxx, yhCbkxx, "1");
        }
        return ResultRespone.success(true);
    }

    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号", required = true)
    })
    @DeleteMapping("/{id}")
    public ResultRespone<Boolean> delById(@PathVariable String id) {
        return ResultRespone.success(yhCbkxxService.delById(id));
    }

    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "批量删除水表档案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "用户编号，多个以逗号隔开", required = true)
    })
    @DeleteMapping("/delByIds")
    public ResultRespone<Boolean> delByIds(@RequestParam String ids) {
        return ResultRespone.success(yhCbkxxService.delByIds(Arrays.asList(ids.split(","))));
    }

    /**
     * 作废水表档案
     */
    @ApiOperationSupport(order = 20)
    @ApiOperation(value = "作废水表档案")
    @PutMapping("/{yhbh}/disable")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "yhbh", required = true, dataType = "String")
    })
    public ResultRespone<Boolean> disable(@PathVariable("yhbh") String yhbh) {
        return ResultRespone.success(yhCbkxxService.disable(yhbh));
    }

    /**
     * 恢复作废水表档案
     */
    @ApiOperationSupport(order = 21)
    @ApiOperation(value = "恢复作废水表档案")
    @PutMapping("/{yhbh}/enable")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "yhbh", required = true, dataType = "String")
    })
    public ResultRespone<Boolean> enable(@PathVariable("yhbh") String yhbh) {
        return ResultRespone.success(yhCbkxxService.enable(yhbh));
    }

    @ApiOperationSupport(order = 26)
    @ApiOperation(value = "批量设置抄表序号", tags = "抄表序号调整")
    @PutMapping("/cbxh")
    public ResultRespone<Boolean> updateCbxh(@RequestBody YhCbkxxCbxhUpdate update) {
        return ResultRespone.success(yhCbkxxService.updateCbxh(update));
    }

    @ApiOperationSupport(order = 27)
    @ApiOperation(value = "批量撤销抄表序号", tags = "抄表序号调整")
    @PutMapping("/cxcbxh")
    public ResultRespone<Boolean> cancelCbxh(@RequestBody YhCbkxxCbxhCancel cancel) {
        return ResultRespone.success(yhCbkxxService.cancelCbxh(cancel));
    }

    @ApiOperationSupport(order = 27)
    @ApiOperation(value = "上下移动/置顶置底抄表序号", tags = "抄表序号调整")
    @PutMapping("/sxydcbxh")
    public ResultRespone<Boolean> sxydCbxh(@RequestBody YhCbkxxCbxhSxyd sxyd) {
        return ResultRespone.success(yhCbkxxService.sxydCbxh(sxyd));
    }
    @ApiOperationSupport(order = 27)
    @ApiOperation(value = "转移跳转抄表序号", tags = "抄表序号调整")
    @PutMapping("/zxtzCbxh")
    public ResultRespone<Boolean> zdzdCbxh(@RequestBody YhCbkxxCbxhZytz zytz) {
        return ResultRespone.success(yhCbkxxService.zxtzCbxh(zytz));
    }

    @ApiOperationSupport(order = 28)
    @ApiOperation(value = "批量设置水价禁用", tags = "批量设置水价禁用")
    @PutMapping("/sj")
    public ResultRespone<Boolean> updateSj(@RequestBody YhCbkxxSjUpdate update) {
        return ResultRespone.success(yhCbkxxService.updateSj(update));
    }

    @ApiOperationSupport(order = 29)
    @ApiOperation(value = "批量设置水价", tags = "批量设置水价")
    @PutMapping("/plsz_sj")
    public ResultRespone<Boolean> updatePlSzSj(@RequestBody YhCbkxxSjUpdate update) {
        return ResultRespone.success(yhCbkxxService.updateSj(update));
    }

    @ApiOperationSupport(order = 31)
    @ApiOperation(value = "水表类别统计", tags = {"抄表统计"})
    @GetMapping("/sblbtj")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ysxz", value = "用水性质", dataType = "String"),
            @ApiImplicitParam(name = "sbkj", value = "水表口径", dataType = "String")
    })
    public ResultRespone sblbtj(String ysxz, String sbkj) {
        return ResultRespone.success(yhCbkxxService.sblbtj(ysxz, sbkj));
    }
}
