package com.tofly.feesapi.yhgl.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bjgl.entity.YhCbkxxLog;
import com.tofly.feesapi.bjgl.entity.YkHbLog;
import com.tofly.feesapi.bjgl.entity.vo.YhCbkxxSelect;
import com.tofly.feesapi.bjgl.service.YhCbkxxLogService;
import com.tofly.feesapi.bjgl.service.YhCbkxxService;
import com.tofly.feesapi.bjgl.service.YkHbLogService;
import com.tofly.feesapi.bmgl.entity.BmCbb;
import com.tofly.feesapi.bmgl.service.BmCbbService;
import com.tofly.feesapi.cbgl.entity.YyCblr;
import com.tofly.feesapi.cbgl.service.YyCblrService;
import com.tofly.feesapi.common.Excel.ExcleFileUtil;
import com.tofly.feesapi.common.constant.*;
import com.tofly.feesapi.common.core.ResultRespone;
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.common.util.GuidGenerator;
import com.tofly.feesapi.common.util.ToolsUtils;
import com.tofly.feesapi.common.znj.ZnjCal;
import com.tofly.feesapi.file.entity.File;
import com.tofly.feesapi.mxcx.entity.YyBgLog;
import com.tofly.feesapi.mxcx.service.YyBgLogService;
import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.sfgl.entity.YyQfmx;
import com.tofly.feesapi.sfgl.entity.YyQfmxGd;
import com.tofly.feesapi.sfgl.entity.YyWyjtz;
import com.tofly.feesapi.sfgl.service.YyQfmxGdService;
import com.tofly.feesapi.sfgl.service.YyQfmxService;
import com.tofly.feesapi.sfgl.service.YyWyjtzService;
import com.tofly.feesapi.udb.entity.User;
import com.tofly.feesapi.udb.service.IUserService;
import com.tofly.feesapi.yhgl.entity.*;
import com.tofly.feesapi.yhgl.entity.dto.*;
import com.tofly.feesapi.yhgl.entity.vo.*;
import com.tofly.feesapi.yhgl.mapper.YhKhjbxxMapper;
import com.tofly.feesapi.yhgl.service.*;
import com.tofly.feesapi.znbgl.entity.dto.ZnbYhdaFilter;
import com.tofly.feesapi.znbgl.entity.vo.ZnbYhdaSelect;
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.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("api/yhgl/yhkhjbxx")
@Api(tags = "用户管理-用户档案")
public class YhKhjbxxController {

    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YhKhjbxxMapper yhKhjbxxMapper;
    @Autowired
    private YhCbkxxService yhCbkxxService;
    @Autowired
    private YyCblrService yyCblrService;
    @Autowired
    private YhCbkxxLogService yhCbkxxLogService;
    @Autowired
    private YhKhjbxxLogService yhKhjbxxLogService;
    @Autowired
    private IYyZjzhService zjzhService;
    @Autowired
    private ZnbDaLogService znbDaLogService;
    @Autowired
    private YhhLogService yhhLogService;
    @Autowired
    private YhBtLogService yhBtLogService;
    @Autowired
    private YkHbLogService ykHbLogService;
    @Autowired
    private YhHfysLogService yhHfysLogService;
    @Autowired
    private YhXzbgLogService yhXzbgLogService;
    @Autowired
    private YyWyjtzService wyjtzService;
    @Autowired
    private YyQfmxService yyQfmxService;
    @Autowired
    private YyQfmxGdService yyQfmxGdService;
    @Autowired
    private ZnjCal znjCal;
    @Autowired
    private BmCbbService bmCbbService;
    @Autowired
    private IUserService userService;
    @Autowired
    private YyBgLogService yyBgLogService;
    @Autowired
    private YhsjqxService yhsjqxService;

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "批量建档-下载Excel模板")
    @GetMapping("/template")
    public void getTemplate(HttpServletResponse response) throws IOException {
        ExcleFileUtil.exportExcel(response, data(), YhkhjbxxTpl.class, "用户批量建档模板.xlsx", null);
    }

    private List<YhkhjbxxTpl> data() {
        List<YhkhjbxxTpl> list = ListUtils.newArrayList();
        for (int i = 0; i < 5; i++) {
            YhkhjbxxTpl data = new YhkhjbxxTpl();
            data.setXh(String.valueOf(i));
            //data.setYhbh("20231" + i); // 用户编号 setDate(new Date());
            data.setYhxm("李四" + i); // 用户姓名 setDoubleData(0.56);
            data.setYhdz("用户地址" + i); //用户地址
            data.setLxdh("1860821173" + i); //联系电话
            data.setZjhm("51050418880223336" + i); //证件号码
            data.setSqrq(LocalDate.now()); //申请日期
            data.setSbbh("20230677" + i); //水表编号
            data.setSbkj("20"); //水表口径
            data.setCcrq(LocalDate.now()); //水表出厂日期
            data.setSbqs("0");
            list.add(data);
        }
        return list;
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "批量建档")
    @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultRespone<Boolean> importExcel(@RequestParam("file") MultipartFile file,
                                              @ModelAttribute YhkhjbxxImport importDto
    ) throws IOException {
        List<YhkhjbxxTpl> userList = EasyExcel.read(file.getInputStream()).head(YhkhjbxxTpl.class).sheet().doReadSync();
        if (userList != null && !userList.isEmpty()) {
            LocalDateTime now = LocalDateTime.now();
            List<YhKhjbxxInsert> inserts = userList.stream()
                    .map(e -> getYhKhjbxxInsert(importDto, now, e))
                    .collect(Collectors.toList());
            yhKhjbxxService.batchSave(inserts);
            return ResultRespone.success(true, "操作成功");
        } else {
            return ResultRespone.failed(false, "操作失败，导入用户资料为空");
        }
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "检测批量建档")
    @PostMapping(value = "/checkImport", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultRespone checkExcel(@RequestParam("file") MultipartFile file,
                                    @ModelAttribute YhkhjbxxImport importDto
    ) throws IOException {
        ResultRespone<Object> rest = new ResultRespone<>();
        List<YhkhjbxxTpl> userList = EasyExcel.read(file.getInputStream()).head(YhkhjbxxTpl.class).sheet().doReadSync();
        if (userList != null && !userList.isEmpty()) {
            LocalDateTime now = LocalDateTime.now();
            List<YhKhjbxxInsert> inserts = userList.stream()
                    .map(e -> getYhKhjbxxInsert(importDto, now, e))
                    .collect(Collectors.toList());

            List<String> msgList = new ArrayList<>();

            int su = 0;
            int fa = 0;

            List<String> lstYhbh = new ArrayList<>();

            if (!CollectionUtil.isEmpty(inserts)) {
                String msg = "";
                for (int i = 0; i < inserts.size(); i++) {
                    if (StringUtil.isEmpty(inserts.get(i).getSscbb())) {
                        msg = String.format("第%s行,抄表册为空.", (i + 1));
                        msgList.add(msg);
                        continue;
                    }

                    if (StringUtil.isEmpty(inserts.get(i).getYhbh())) {
                        msg = String.format("第%s行,用户编号为空.", (i + 1));
                        msgList.add(msg);
                        continue;
                    }

                    if (StringUtil.isEmpty(inserts.get(i).getYhdz())) {
                        msg = String.format("第%s行,用户地址为空.", (i + 1));
                        msgList.add(msg);
                        continue;
                    }

                    if (StringUtil.isEmpty(inserts.get(i).getYhxm())) {
                        msg = String.format("第%s行,用户姓名为空.", (i + 1));
                        msgList.add(msg);
                        continue;
                    }

                    if (!inserts.get(i).getSscbb().equals(inserts.get(i).getYhbh().substring(0, 4))) {
                        msg = String.format("第%s行,用户编号【%s】与抄表册【%s】不匹配.", (i + 1), inserts.get(i).getYhbh(), inserts.get(i).getSscbb());
                        msgList.add(msg);
                        continue;
                    }
                    su += 1;

                    lstYhbh.add((inserts.get(i).getYhbh()));
                }

                List<YhKhjbxx> lstKhjbxx = yhKhjbxxService.getListByYhbh(lstYhbh);
                if (!CollectionUtil.isEmpty(lstKhjbxx)) {
                    String yhbhs = lstKhjbxx.stream().map(YhKhjbxx::getYhbh).collect(Collectors.joining(","));
                    msg = String.format("系统用户编号【%s】已存在", yhbhs);
                    msgList.add(msg);
                }

                rest.setCode(1);
                rest.setMessage("检测到成功" + su + "行,异常" + msgList.size() + "行");
                rest.setResult(msgList);
            } else {
                rest.setCode(-1);
                rest.setMessage("检测到成功" + su + "行,异常" + msgList.size() + "行");
                rest.setResult(msgList);
            }
            return rest;
        } else {
            rest.setCode(-1);
            rest.setMessage("操作失败，导入用户资料为空");
            return rest;
        }
    }


    /**
     * Excle上传文件
     */
    @ApiOperation(value = "Excel2上传文件,批量建档")
    @PostMapping("/import2")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ssgs", value = "所属公司", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sscbpq", value = "片区", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sscbb", value = "抄表本", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sblb", value = "水表类别", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sbsccj", value = "水表厂家", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sbxh", value = "水表型号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sjbm", value = "水价", required = true, dataType = "String"),
            @ApiImplicitParam(name = "wsfbz", value = "是否污水费", required = true, dataType = "String"),
            @ApiImplicitParam(name = "ljfbz", value = "是否垃圾费", required = true, dataType = "String"),
            @ApiImplicitParam(name = "ljffs", value = "垃圾费收取方式", required = true, dataType = "String"),
            @ApiImplicitParam(name = "ljfje", value = "垃圾费金额", required = true, dataType = "String"),
            @ApiImplicitParam(name = "czrybm", value = "创建人员编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "czrymc", value = "操作人员名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "jfzt", value = "表计状态", required = true, dataType = "String"),
            @ApiImplicitParam(name = "yhzt", value = "用户状态", required = true, dataType = "String"),
            @ApiImplicitParam(name = "tsbz", value = "通水状态", required = true, dataType = "String"),
            @ApiImplicitParam(name = "tsrq", value = "通水日期", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cbpl", value = "抄表频率", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sblc", value = "水表量程", required = true, dataType = "String"),
            @ApiImplicitParam(name = "bjwz", value = "水表位置", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sbyt", value = "水表用途", required = true, dataType = "String")
    })
    @Transactional(rollbackFor = Exception.class) //声明式事务管理
    public ResultRespone importExcel(
            @RequestParam("file") MultipartFile file, String ssgs, String sscbpq, String sscbb, String sblb, String sbsccj,
            String sbxh, String sjbm, String wsfbz, String ljfbz, String czrybm, String czrymc, String jfzt, String yhzt, String tsbz,
            @RequestParam String tsrq, String cbpl, String sblc, String bjwz, String ljffs, String ljfje, String sbyt) {
        //传入参数校验
        ResultRespone<Object> rest = checkImportExcel(ssgs, sscbpq, sscbb, sblb, sbsccj, sbxh, sjbm, wsfbz, ljfbz, czrybm, czrymc);

        if (StrUtil.isEmpty(file.toString())) {
            return ResultRespone.failed("请上传Excel文件");
        }

        if (rest.getCode() == -1) {
            return ResultRespone.failed(rest.getCode(), rest.getMessage());
        }

        try {
            ImportDto importDto = new ImportDto(ssgs, sscbpq, sscbb, sblb, sbsccj, sbxh, sjbm, wsfbz, ljfbz, czrybm, czrymc, jfzt, yhzt, tsbz, tsrq, cbpl, sblc, bjwz, ljffs, ljfje, sbyt);
            rest = yhKhjbxxService.pldr(file, importDto);
        } catch (Exception e) {
            log.error("批量建档导入失败: ======================> ", e);
            rest.setCode(-1);
            rest.setMessage("导入失败:" + e.getMessage());
        }

        return rest;
    }

    public ResultRespone<Object> checkImportExcel(String ssgs, String sscbpq, String sscbb, String sblb, String sbsccj, String sbxh, String sjbm, String wsfbz, String ljfbz, String czrybm, String czrymc) {
        ResultRespone<Object> rest = new ResultRespone<>();
        rest.setCode(1);
        rest.setMessage("操作成功");

        if (StringUtils.isEmpty(ssgs)) {
            return createErrorResponse(rest, -1, "所属公司不能为空");
        }
        if (StringUtils.isEmpty(sscbpq)) {
            return createErrorResponse(rest, -1, "所属片区参数不能为空");
        }
        if (StringUtils.isEmpty(sbsccj)) {
            return createErrorResponse(rest, -1, "水表厂家参数不能为空");
        }
        return rest;
    }

    private ResultRespone<Object> createErrorResponse(ResultRespone<Object> rest, int code, String message) {
        rest.setCode(code);
        rest.setMessage(message);
        return rest;
    }

    private YhKhjbxxInsert getYhKhjbxxInsert(YhkhjbxxImport importDto, LocalDateTime now, YhkhjbxxTpl e) {
        YhKhjbxxInsert insert = new YhKhjbxxInsert();
        BeanUtils.copyProperties(importDto, insert);
        BeanUtils.copyProperties(e, insert);

        YhKhjbxxInsert.YhCbkxxInsert yhCbkxx = insert.getYhCbkxx();
        BeanUtils.copyProperties(importDto.getYhCbkxx(), yhCbkxx);
        BeanUtils.copyProperties(e, yhCbkxx);
        if (insert.getCzsj() == null) {
            insert.setCzsj(new Date());
        }
        return insert;
    }

    @ApiOperationSupport(order = 5)
    @GetMapping("/page")
    @ApiOperation(value = "查询用户档案（分页）", tags = {"营业厅收费"})
    public ResultRespone<PageResult<YhkhjbxxSelect>> getPage(@ModelAttribute PageDto pageDto, @ModelAttribute YhkhjbxxFilter filter) {
        return ResultRespone.success(yhKhjbxxService.getPage(pageDto, filter));
    }

    @ApiOperationSupport(order = 5)
    @GetMapping("/page2")
    @ApiOperation(value = "查询用户档案2（分页）")
    public ResultRespone<PageResult<YhkhjbxxSelect2>> getPage2(@ModelAttribute PageDto pageDto, @ModelAttribute YhkhjbxxFilter filter) {

        if (StringUtil.isEmpty(filter.getUserId())) {
            filter.setUserId(SecurityUtils.getUserId().toString());
        }
        // 如果是大户查询,添加客户编码
        String khbm = filter.getKhbm();
        if (StrUtil.isNotEmpty(khbm)) {
            // 传参未截取
            if (khbm.length() > 7) {
                khbm = khbm.substring(0, 7).toUpperCase();
            }
            filter.setKhbm(khbm.toUpperCase());
            if(!StringUtil.isEmpty(filter.getMkbm())&& filter.getMkbm().equals("yhzhcx"))
            {
                filter.setUserId(null);
            }
        }

        PageResult<YhkhjbxxSelect2> yhdaPage = yhKhjbxxService.getPage2(pageDto, filter);
        // 遍历查询结果进行赋值
        List<YhkhjbxxSelect2> yhdaList = yhdaPage.getRecords();

        for (YhkhjbxxSelect2 yhda : yhdaList) {
            //用户状态（0:申请用户,1:正式用户,2:报停用户,3:销户用户,4:作废用户）
            int cbsl = yhKhjbxxMapper.selectExistCbkxx(yhda.getYhbh());
            if (cbsl > 0) {
                List<CbkxxDto> list = yhKhjbxxMapper.selectCbkh(yhda.getYhbh());
                StringBuilder strcbkh = new StringBuilder();
                StringBuilder strid = new StringBuilder();
                List<String> zccbkhs = new ArrayList<>();
                for (CbkxxDto cbkxxDto : list) {
                    strcbkh.append(cbkxxDto.getCbkh()).append(",");
                    strid.append(cbkxxDto.getCbkid()).append(",");
                    String jfzt = cbkxxDto.getJfzt();
                    if (StrUtil.isNotEmpty(jfzt) && jfzt.equalsIgnoreCase("1")) {
                        String cbkh = cbkxxDto.getCbkh();
                        if (StrUtil.isNotEmpty(cbkh)) {
                            zccbkhs.add(cbkh);
                        }
                    }
                }
                yhda.setCbkhList(strcbkh.substring(0, strcbkh.length() - 1));
                yhda.setCbkid(strid.substring(0, strid.length() - 1));
                yhda.setSbsl(cbsl);
                yhda.setZccbkhs(zccbkhs);
            }
        }

        return ResultRespone.success(yhdaPage);
    }

    @GetMapping("/page3")
    @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 = "searchText", value = "模糊查询(用户编号、用户姓名、用户地址、联系电话)", dataType = "String"),
            @ApiImplicitParam(name = "ssgs", value = "公司", dataType = "String"),
            @ApiImplicitParam(name = "sscbpq", value = "片区", dataType = "String"),
            @ApiImplicitParam(name = "sscbb", value = "抄表本", dataType = "String"),
            @ApiImplicitParam(name = "sblb", value = "水表类别", dataType = "String"),
            @ApiImplicitParam(name = "sjbm", value = "用水性质", dataType = "String"),
            @ApiImplicitParam(name = "yhzt", value = "用户状态", dataType = "String"),
            @ApiImplicitParam(name = "cbry", value = "抄表人员", dataType = "String"),
            @ApiImplicitParam(name = "ljfbz", value = "是否垃圾费", dataType = "String"),
            @ApiImplicitParam(name = "ksrq", value = "开始建档日期", dataType = "String"),
            @ApiImplicitParam(name = "jsrq", value = "结束建档日期", dataType = "String"),
    })
    public ResultRespone getDaCustomerPage(Page page, String searchText, String ssgs, String sscbpq, String sscbb, String sblb, String sjbm, String cbry, String yhzt, String ljfbz, String ksrq, String jsrq) {
        //用户编号、用户姓名、用户地址、联系电话
        //片区、抄表本、水表型号、用水性质、用户状态、是否垃圾费、建档日期、抄表人员
        IPage<YhkhjbxxSelect2> yhdaPage = yhKhjbxxMapper.selectDaCustomerPage(page, searchText, ssgs, sscbpq, sscbb, sblb, sjbm, cbry, yhzt, ljfbz, ksrq, jsrq);
        // 遍历查询结果进行赋值
        List<YhkhjbxxSelect2> yhdaList = yhdaPage.getRecords();

        for (YhkhjbxxSelect2 yhda : yhdaList) {

            int cbsl = yhKhjbxxMapper.selectExistCbkxx(yhda.getYhbh());
            if (cbsl > 0) {
                //用户状态（0:申请用户, 1:正式用户, 2:报停用户, 3:销户用户, 4:作废用户）
                customerStateSearch(yhda);
                List<CbkxxDto> list = yhKhjbxxMapper.selectCbkh(yhda.getYhbh());
                //循环遍历，重新赋值
                StringBuilder strcbkh = new StringBuilder();
                StringBuilder strid = new StringBuilder();
                for (CbkxxDto cbkxxdto : list) {
                    strcbkh.append(cbkxxdto.getCbkh()).append(",");
                    strid.append(cbkxxdto.getCbkid()).append(",");
                }

                yhda.setCbkhList(strcbkh.substring(0, strcbkh.length() - 1));
                yhda.setCbkid(strid.substring(0, strid.length() - 1));
                yhda.setSbsl(cbsl);

            }
        }
        return ResultRespone.success(yhdaPage);
    }

    @GetMapping("/export3")
    @ApiOperation(value = "export导出-用户档案")
    @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 = "searchText", value = "模糊查询(用户编号、用户姓名、用户地址、联系电话)", dataType = "String"),
            @ApiImplicitParam(name = "ssgs", value = "公司", dataType = "String"),
            @ApiImplicitParam(name = "sscbpq", value = "片区", dataType = "String"),
            @ApiImplicitParam(name = "sscbb", value = "抄表本", dataType = "String"),
            @ApiImplicitParam(name = "sblb", value = "水表型号", dataType = "String"),
            @ApiImplicitParam(name = "sjbm", value = "用水性质", dataType = "String"),
            @ApiImplicitParam(name = "yhzt", value = "用户状态", dataType = "String"),
            @ApiImplicitParam(name = "ljfbz", value = "是否垃圾费", dataType = "String"),
            @ApiImplicitParam(name = "ksrq", value = "开始建档日期", dataType = "String"),
            @ApiImplicitParam(name = "jsrq", value = "结束建档日期", dataType = "String"),
            @ApiImplicitParam(name = "cbry", value = "抄表人员", dataType = "String"),
            @ApiImplicitParam(name = "exportFields", value = "Excel导出字段", dataType = "String", example = "yhbh,yhxm")
    })
    public void export(HttpServletResponse response, String searchText, String ssgs, String sscbpq, String sscbb, String sblb, String sjbm, String cbry, String yhzt, String ljfbz, String ksrq, String jsrq, String exportFields) throws IOException {
        List<YhkhjbxxSelect2> yhdaList = yhKhjbxxMapper.selectDaCustomerPage(searchText, ssgs, sscbpq, sscbb, sblb, sjbm, cbry, yhzt, ljfbz, ksrq, jsrq);
        // 遍历查询结果进行赋值
        // 对 obj 进行一些操作    yhdaList.set(i, obj); // 将 obj 的新值重新赋给 yhdaList}
        for (YhkhjbxxSelect2 yhda : yhdaList) {
            //用户状态（0:申请用户,1:正式用户,2:报停用户,3:销户用户,4:作废用户）
            customerStateSearch(yhda);
        }
        ExcleFileUtil.exportExcel(response, yhdaList, YhkhjbxxSelect2.class, "用户档案.xlsx", exportFields);
    }

    private void customerStateSearch(YhkhjbxxSelect2 yhda) {
        if (yhda.getYhzt().equals("0")) {
            yhda.setYhzt(YhztEnum.申请用户);
        }
        if (yhda.getYhzt().equals("1")) {
            yhda.setYhzt(YhztEnum.正式用户);
        }
        if (yhda.getYhzt().equals("2")) {
            yhda.setYhzt(YhztEnum.报停用户);
        }
        if (yhda.getYhzt().equals("3")) {
            yhda.setYhzt(YhztEnum.销户用户);
        }
        if (yhda.getYhzt().equals("4")) {
            yhda.setYhzt(YhztEnum.作废用户);
        }
    }

    /**
     * 通过id查询用户档案
     */
    @ApiOperationSupport(order = 6)
    @GetMapping("/{yhbh}")
    @ApiOperation(value = "查看用户档案", tags = {"水费补差", "营业厅收费", "综合查询", "预开发票"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "用户编号", required = true, dataType = "String")
    })
    public ResultRespone<Yhkhjbxx2> getById(@PathVariable("yhbh") String yhbh) {
        return ResultRespone.success(yhKhjbxxMapper.selectYhDa(yhbh));
    }


    @ApiOperation(value = "查看账户余额信息", tags = {"余额转存", "综合查询"})
    @GetMapping("/{yhbh}/zjzh")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "用户编号", required = true, dataType = "String")
    })
    public ResultRespone<YyZjzhView> getZjzh(@PathVariable("yhbh") String yhbh) {
        return ResultRespone.success(zjzhService.get(yhbh));
    }


    @ApiOperation(value = "(新增、修改)用户、水表基本信息")
    @PostMapping("/saveDaCustomerAndMeter")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "operationType", value = "save、saveUpate", required = true, dataType = "String")
    })
    @DSTransactional
    public ResultRespone saveYhda(@RequestBody DaCustomerAndMeter daCustomerAndMeter, @RequestParam String operationType) throws Exception {

        YhKhjbxx yhkhJbxxReq = daCustomerAndMeter.getYhKhjbxx();
        YhCbkxx yhCbkxxReq = daCustomerAndMeter.getYhCbkxx();

        ResultRespone resultRespone = sjjy(yhkhJbxxReq, yhCbkxxReq, operationType);
        if (ObjUtil.isNotNull(resultRespone)) {
            return resultRespone;
        }

        String reqYhxm = yhkhJbxxReq.getYhxm();
        //用户档案基础信息添加
        YhKhjbxx yhKhjbxx = JSONObject.parseObject(JSON.toJSONString(yhkhJbxxReq), YhKhjbxx.class);
        //水表档案基础信息添加
        YhCbkxx yhCbkxx = JSONObject.parseObject(JSON.toJSONString(yhCbkxxReq), YhCbkxx.class);

        if (StringUtils.isEmpty(yhKhjbxx.getZjlb())) {
            yhKhjbxx.setZjlb("1");
            yhKhjbxx.setZjhm("0");
        }
        if (StringUtils.isEmpty(yhKhjbxx.getFffs())) {
            yhKhjbxx.setFffs("1");
        }

        //抄表计划添加
        YyCblr yyCblr = new YyCblr();
        String yhzt = yhKhjbxx.getYhzt().toString();
        String jfzt = yhCbkxx.getJfzt();
        if (yhzt == "0" || yhzt == "申请用户") {
            yhKhjbxx.setYhzt(YhztEnum.申请用户);//正式用户状态
            yhCbkxx.setJfzt(JfztEnum.停用.toString());//计费状态（1正常，2停用）
            yyCblr.setJfzt(JfztEnum.停用.getValue().toString());//正常状态
        }
        if (yhzt == "1" || yhzt == "正式用户") {
            yhKhjbxx.setYhzt(YhztEnum.正式用户);//正式用户状态
            yhCbkxx.setJfzt(JfztEnum.正常.toString());//计费状态（1正常，2停用）
            yyCblr.setJfzt(JfztEnum.正常.getValue().toString());//正常状态
        }
        if (yhzt == "2" || yhzt == "报停用户") {
            yhKhjbxx.setYhzt(YhztEnum.报停用户);//正式用户状态
        }
        if (yhzt == "3" || yhzt == "销户用户") {
            yhKhjbxx.setYhzt(YhztEnum.销户用户);//正式用户状态
        }
        if (yhzt == "4" || yhzt == "作废用户") {
            yhKhjbxx.setYhzt(YhztEnum.作废用户);//正式用户状态
        }
        if (Arrays.asList("1", "正常").contains(jfzt)) {
            yhCbkxx.setJfzt("1");//计费状态（1正常，2停用）
            yyCblr.setJfzt("1");//正常状态（1正常，2停用）
        } else {
            yhCbkxx.setJfzt("2");//计费状态（1正常，2停用）
            yyCblr.setJfzt("2");//正常状态（1正常，2停用）
        }

        if (StringUtil.isEmpty(yhKhjbxx.getHtbh())) {
            yhKhjbxx.setHtbh(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        }
        String yhbh = yhKhjbxx.getYhbh();
        yhKhjbxx.setPyjm(getChineseInitial(yhKhjbxx.getYhxm()));

        ResultRespone<Object> rest = new ResultRespone<>();
        if (operationType.equals("save")) {
            String maxyhbh = "";
            Boolean exisYh = yhKhjbxxMapper.exists(new QueryWrapper<YhKhjbxx>().eq("yhbh", yhbh));
            if (exisYh) {
                rest.setCode(-1);
                rest.setMessage("系统已存在此用户编号");
                return rest;
            }

            String khbm = yhKhjbxx.getKhbm();
            // 账户初始化(大户默认主户标记)
            zhcsh(yhKhjbxx);

            maxyhbh = yhbh;
            // 用户档案
            yhKhjbxx.setYhbh(String.valueOf(maxyhbh));
            yhKhjbxx.setYkhbh(String.valueOf(maxyhbh));
            yhKhjbxx.setJdrybm(yhKhjbxx.getCzrybm());
            yhKhjbxx.setJdryxm(yhKhjbxx.getCzryxm());
            yhKhjbxx.setCzsj(new Date());
            yhKhjbxx.setKhbm(khbm);

            // 水表档案
            yhCbkxx.setYhbh(String.valueOf(maxyhbh));
            yhCbkxx.setCbkh("1");

            long yhsbsl = yhCbkxxService.getCountByYhbh(yhbh);
            yhCbkxx.setSbbh(yhbh + (yhsbsl + 1));

            String strcbkh = String.valueOf(maxyhbh) + 1;
            yhCbkxx.setCbkid(strcbkh);
            yhCbkxx.setFmzt(FmztEnum.开阀);
            yhCbkxx.setCzsj(new Date());
            yhCbkxx.setXfsf(yhCbkxx.getXfsf());
            yhCbkxx.setFjf(yhCbkxx.getFjf());
            yhCbkxx.setSzyfbz("1");
            yhCbkxx.setLjfbz("0");
            String ecjyf = "0";
            if (yhCbkxx.getEcjybz() != null) {
                ecjyf = yhCbkxx.getEcjybz();
            }

            yhCbkxx.setEcjybz(ecjyf);

            if (StringUtil.isEmpty(yhCbkxx.getCzrybm())) {
                yhCbkxx.setCzrybm(yhKhjbxx.getCzrybm());
            }

            if (StringUtil.isEmpty(yhCbkxx.getCzryxm())) {
                yhCbkxx.setCzryxm(yhKhjbxx.getCzryxm());
            }

            //抄表计划
            yyCblr.setYhbh(String.valueOf(maxyhbh));//用户编号
            yyCblr.setCbkh("1");//抄表卡号
            yyCblr.setCbkid(strcbkh);//抄表卡ID

            Map<String, Object> mapcwrq = yhKhjbxxMapper.selectCwrq();
            String strcwrq = mapcwrq.get("cwrq").toString();
            yyCblr.setCwrq(strcwrq);
            yyCblr.setJsbz(JsbzEnum.未算费);
            yyCblr.setCbbz(CbbzEnum.未抄表);
            yyCblr.setShbz(ShbzEnum.未审核);
            yyCblr.setSsgs(yhKhjbxx.getSsgs());
            yyCblr.setSscbpq(yhKhjbxx.getSscbpq());
            yyCblr.setSscbb(yhKhjbxx.getSscbb());
            BmCbb bmCbb = bmCbbService.getById(yhKhjbxx.getSscbb());
            yyCblr.setCbrybm(bmCbb.getCby());
            User user = userService.get(Long.valueOf(bmCbb.getCby()));
            if (StringUtil.isNotNull(user)) {
                yyCblr.setCbryxm(user.getRealName());
            }

            yyCblr.setScds(BigDecimal.valueOf(yhCbkxx.getSbqs()));
            yyCblr.setBcds(BigDecimal.valueOf(yhCbkxx.getSbqs()));
            //默认清除月份
            yhKhjbxx.setJtljlqcsj(strcwrq.substring(strcwrq.length() - 2));
            //检查主户客户编号是否重复
            checkZhbzByUpdate(yhKhjbxx);
            //用户档案添加
            if (!yhKhjbxxService.save(yhKhjbxx)) {
                throw new FeesException("用户档案添加失败！", FeesErrorCode.BUSINESS_ERROR);
            }
            //用户水表档案添加
            if (!yhCbkxxService.save(yhCbkxx)) {
                throw new FeesException("用户水表档案添加失败！", FeesErrorCode.BUSINESS_ERROR);
            }
            // 抄表计划、智能表档案
            if (yhCbkxx.getSblb().equals("0") ||
                    yhCbkxx.getSblb().equals("2") ||
                    yhCbkxx.getSblb().equals("3") ||
                    yhCbkxx.getSblb().equals("4")) {
                if (!yyCblrService.save(yyCblr)) {
                    throw new FeesException("用户抄表计划添加失败！", FeesErrorCode.BUSINESS_ERROR);
                }
            }
            if (yhCbkxx.getSblb().equals("2") || yhCbkxx.getSblb().equals("3")) {
                //智能表档案日志添加
                if (!znbDaLogService.addznbDaLog(yhKhjbxx, yhCbkxx, "0")) {
                    throw new FeesException("智能表档案日志添加失败！", FeesErrorCode.BUSINESS_ERROR);
                }
            }
            yhKhjbxxService.saveLog(yhKhjbxx, null, "添加");//添加用户档案日志
            yhCbkxxService.saveLog(yhCbkxx, null, "添加");//添加水表档案日志
        } else {
            // 修改时添加用户曾用名字段
            YhKhjbxx oldyhKhjbxx = yhKhjbxxService.getById(yhbh);
            YhCbkxx oldyhCbkxx = yhCbkxxService.getById(yhCbkxx.getCbkid());
//            if (ObjUtil.isNotNull(oldyhCbkxx)) {
//                daCustomerAndMeter.setCbkOldJson(JSONUtil.toJsonStr(oldyhCbkxx));
//            }
//            if (ObjUtil.isNotNull(oldyhKhjbxx)) {
//                daCustomerAndMeter.setKhOldJson(JSONUtil.toJsonStr(oldyhKhjbxx));
//            }
            if (!oldyhCbkxx.getSblb().equals(yhCbkxx.getSblb())) {
                return ResultRespone.failed("修改水表档案失败，不能修改水表类型！");
            }


            String originalDataYhxm = oldyhKhjbxx.getYhxm();
            String cym = oldyhKhjbxx.getCym();

            if (originalDataYhxm != null && !originalDataYhxm.equalsIgnoreCase(reqYhxm)) {
                if (StrUtil.isEmpty(cym)) {
                    yhKhjbxx.setCym("");
                } else {
                    cym = cym + StrUtil.COMMA + originalDataYhxm;
                    yhKhjbxx.setCym(cym);
                }
            }
            checkZhbzByUpdate(yhKhjbxx);
            YhKhjbxx newyhKhjbxx = new YhKhjbxx();
            BeanUtils.copyProperties(oldyhKhjbxx, newyhKhjbxx);
            //复制修改对象值到新对象并排除修改对象中为空的属性
            BeanUtils.copyProperties(yhKhjbxx, newyhKhjbxx, ToolsUtils.getnullFields(yhKhjbxx));
            //用户档案修改执行成功
            if (!yhKhjbxxService.updateById(yhKhjbxx)) {
                throw new FeesException("用户档案修改失败！", FeesErrorCode.BUSINESS_ERROR);
            }

            YhCbkxx newyhCbkxx = new YhCbkxx();
            BeanUtils.copyProperties(oldyhCbkxx, newyhCbkxx);
            BeanUtils.copyProperties(yhCbkxx, newyhCbkxx, ToolsUtils.getnullFields(yhCbkxx));
            if (!yhCbkxxService.updateById(yhCbkxx)) {
                throw new FeesException("用户水表档案修改失败！", FeesErrorCode.BUSINESS_ERROR);
            }

            if (!yyCblrService.lambdaUpdate()
                    .set(YyCblr::getJfzt, yyCblr.getJfzt())
                    .set(YyCblr::getSscbpq, yhKhjbxx.getSscbpq())
                    .set(YyCblr::getSscbb, yhKhjbxx.getSscbb())
                    .eq(YyCblr::getCbkid, yhCbkxx.getCbkid())
                    .update()) {
                throw new FeesException("用户抄表计划修改失败！", FeesErrorCode.BUSINESS_ERROR);
            }

            if (yhCbkxx.getSblb().equals("2") || yhCbkxx.getSblb().equals("3")) {
                if (!znbDaLogService.addznbDaLog(yhKhjbxx, yhCbkxx, "1")) {
                    throw new FeesException("智能表档案日志添加失败！", FeesErrorCode.BUSINESS_ERROR);
                }
            }
            yhKhjbxxService.saveLog(newyhKhjbxx, oldyhKhjbxx, "修改");//添加用户档案日志
            yhCbkxxService.saveLog(newyhCbkxx, oldyhCbkxx, "修改");//添加水表档案日志
        }

        // 操作日志添加
        //daCustomerAndMeter.setYhKhjbxx(yhKhjbxx);
        //daCustomerAndMeter.setYhCbkxx(yhCbkxx);
        //rest = addDaCustomerAndMeterLog(daCustomerAndMeter, operationType);
        rest.setCode(1);
        rest.setMessage("操作成功");
        return rest;
    }

    /**
     * 数据校验
     */
    private ResultRespone sjjy(YhKhjbxx yhkhJbxxReq, YhCbkxx yhCbkxxReq, String operationType) {
        if (StringUtils.isEmpty(operationType)) {
            return ResultRespone.failed(false, "操作类型不能为空");
        }

        if (!operationType.equals("save") && !operationType.equals("saveUpdate")) {
            return ResultRespone.failed(false, "操作类型参数不等于save或saveUpdate");
        }

        if (StringUtils.isEmpty(yhkhJbxxReq.getSsgs())) {
            return ResultRespone.failed(false, "所属公司不能为空");
        }

        if (StringUtils.isEmpty(yhkhJbxxReq.getSscbpq())) {
            return ResultRespone.failed(false, "片区不能为空");
        }

        if (StringUtils.isEmpty(yhkhJbxxReq.getSscbb())) {
            return ResultRespone.failed(false, "抄表本不能为空");
        }

        String reqYhxm = yhkhJbxxReq.getYhxm();
        if (StringUtils.isEmpty(reqYhxm.toString())) {
            return ResultRespone.failed(false, "用户姓名不能为空");
        }

//        if (StringUtils.isEmpty(yhkhJbxxReq.getYhdz().toString())) {
//            return ResultRespone.failed(false, "用户地址不能为空");
//        }

        if (StringUtils.isEmpty(yhCbkxxReq.getSblb())) {
            return ResultRespone.failed(false, "水表类别不能为空");
        }

        if (StringUtils.isEmpty(yhCbkxxReq.getSbsccj())) {
            return ResultRespone.failed(false, "水表厂家不能为空");
        }

        if (StringUtils.isEmpty(yhCbkxxReq.getSbxh())) {
            return ResultRespone.failed(false, "水表型号不能为空");
        }

        if (StringUtils.isEmpty(yhCbkxxReq.getSbkj())) {
            return ResultRespone.failed(false, "水表口径不能为空");
        }

        if (StringUtils.isEmpty(yhkhJbxxReq.getCzrybm())) {
            return ResultRespone.failed(false, "操作人员编码不能为空");
        }

        if (StringUtils.isEmpty(yhkhJbxxReq.getCzryxm())) {
            return ResultRespone.failed(false, "操作人员姓名不能为空");
        }

        return null;
    }

    @ApiOperation(value = "报装用户建档用户、水表基本信息")
    @PostMapping("/saveBZCustomerAndMeter")
    @Transactional(rollbackFor = Exception.class) //声明式事务管理
    public ResultRespone saveBzYhda(@RequestBody DaCustomerAndMeter daCustomerAndMeter) throws Exception {
        ResultRespone<Object> rest = new ResultRespone<>();
        if (StringUtils.isEmpty(daCustomerAndMeter.getYhKhjbxx().getSsgs())) {
            return ResultRespone.failed(false, "所属公司不能为空");
        }

        if (StringUtils.isEmpty(daCustomerAndMeter.getYhKhjbxx().getSscbpq())) {
            return ResultRespone.failed(false, "片区不能为空");
        }

        if (StringUtils.isEmpty(daCustomerAndMeter.getYhKhjbxx().getSscbb())) {
            return ResultRespone.failed(false, "抄表本不能为空");
        }

        if (StringUtils.isEmpty(daCustomerAndMeter.getYhKhjbxx().getYhxm().toString())) {
            return ResultRespone.failed(false, "用户姓名不能为空");
        }

        if (StringUtils.isEmpty(daCustomerAndMeter.getYhKhjbxx().getYhdz().toString())) {
            return ResultRespone.failed(false, "用户地址不能为空");
        }

        if (StringUtils.isEmpty(daCustomerAndMeter.getYhKhjbxx().getCzrybm())) {
            return ResultRespone.failed(false, "操作人员编码不能为空");
        }

        if (StringUtils.isEmpty(daCustomerAndMeter.getYhKhjbxx().getCzryxm())) {
            return ResultRespone.failed(false, "操作人员姓名不能为空");
        }

        //用户档案基础信息添加
        YhKhjbxx yhKhjbxx = daCustomerAndMeter.getYhKhjbxx();
        String yhzt = daCustomerAndMeter.getYhKhjbxx().getYhzt().getValue().toString();

        if (yhzt.equals("0")) {
            //获取用户编号
            int maxyhbh = 0;
            if (daCustomerAndMeter.getYhCbkxx().getSbyt().equals("5")) {
                maxyhbh = yhKhjbxxMapper.selectMaxYhbh_jk() + 1;
            } else {
                maxyhbh = yhKhjbxxMapper.selectMaxYhbh_fjk() + 1;
            }
            //用户档案
            yhKhjbxx.setYhbh(String.valueOf(maxyhbh));
            yhKhjbxx.setYkhbh(String.valueOf(maxyhbh));
            yhKhjbxx.setJdrybm(daCustomerAndMeter.getYhKhjbxx().getCzrybm());
            yhKhjbxx.setJdryxm(daCustomerAndMeter.getYhKhjbxx().getCzryxm());

            yhKhjbxx.setJdrq(new Date());
            yhKhjbxx.setCzsj(new Date());
            //用户档案添加执行成功
            if (yhKhjbxxService.save(yhKhjbxx)) {
                rest.setResult(maxyhbh);
                rest.setCode(1);
                rest.setMessage("新增用户档案成功");
            } else {
                rest.setCode(-1);
                rest.setMessage("新增用户档案失败");
            }
            yhKhjbxxService.saveLog(yhKhjbxx, null, "添加");//添加用户档案日志
        } else if (yhzt.equals("1")) {
            if (StringUtils.isEmpty(daCustomerAndMeter.getYhKhjbxx().getYhbh())) {
                return ResultRespone.failed(false, "用户编号不能为空");
            }
            if (StringUtils.isEmpty(daCustomerAndMeter.getYhCbkxx().getSbbh())) {
                return ResultRespone.failed(false, "水表编号不能为空");
            }
            if (StringUtils.isEmpty(daCustomerAndMeter.getYhCbkxx().getSblb())) {
                return ResultRespone.failed(false, "水表类别不能为空");
            }
            if (StringUtils.isEmpty(daCustomerAndMeter.getYhCbkxx().getSbsccj())) {
                return ResultRespone.failed(false, "水表厂家不能为空");
            }
            if (StringUtils.isEmpty(daCustomerAndMeter.getYhCbkxx().getSbxh())) {
                return ResultRespone.failed(false, "水表型号不能为空");
            }
            if (StringUtils.isEmpty(daCustomerAndMeter.getYhCbkxx().getSbkj())) {
                return ResultRespone.failed(false, "水表口径不能为空");
            }
            Date date = new Date();
            if (StringUtil.isEmpty(yhKhjbxx.getTsbz())) {
                yhKhjbxx.setTsrq(date);
                yhKhjbxx.setTsbz("0");
            }
            if (StringUtil.isEmpty(yhKhjbxx.getHtqd())) {
                yhKhjbxx.setHtqdrq(date);
                yhKhjbxx.setHtqd("0");
            }
            if (StringUtil.isEmpty(yhKhjbxx.getZjlb())) {
                yhKhjbxx.setZjlb("1");
                yhKhjbxx.setZjhm("0");
            }
            if (StringUtil.isEmpty(yhKhjbxx.getFffs())) {
                yhKhjbxx.setFffs("1");
            }
            yhKhjbxx.setYhzt(YhztEnum.正式用户);//正式用户状态
            YhKhjbxx oldyhKhjbxx = yhKhjbxxService.getById(daCustomerAndMeter.getYhKhjbxx().getYhbh());
            YhKhjbxx newYhKhjbxx = new YhKhjbxx();
            BeanUtils.copyProperties(oldyhKhjbxx, newYhKhjbxx);
            BeanUtils.copyProperties(yhKhjbxx, newYhKhjbxx, ToolsUtils.getnullFields(yhKhjbxx));
            //用户档案修改
            if (!yhKhjbxxService.updateById(newYhKhjbxx)) {
                throw new FeesException("用户档案修改失败！", FeesErrorCode.BUSINESS_ERROR);
            }
            yhKhjbxxService.saveLog(newYhKhjbxx, oldyhKhjbxx, "修改");//添加用户档案日志
            YhCbkxx yhCbkxx = daCustomerAndMeter.getYhCbkxx();
            QueryWrapper<YhCbkxx> queryWrapper = new QueryWrapper<YhCbkxx>().
                    eq("yhbh", daCustomerAndMeter.getYhKhjbxx().getYhbh()).
                    eq("jfzt", "1");
            YhCbkxx oldyhCbkxx = yhCbkxxService.getOne(queryWrapper);
            String isadd = "0";
            String cbkh = "1";
            if (null != oldyhCbkxx) {
                //水表编号是否一致
                if (oldyhCbkxx.getSbbh().equals(yhCbkxx.getSbbh())) {
                    //和原水表号一致，更新水表信息
                    //存在 更新水表信息
                    yhCbkxx.setCzryxm(daCustomerAndMeter.getYhCbkxx().getCzryxm());
                    yhCbkxx.setCzrybm(daCustomerAndMeter.getYhCbkxx().getCzrybm());
                    yhCbkxx.setCzsj(new Date());//操作时间
                    YhCbkxx newyhCbkxx = new YhCbkxx();
                    BeanUtils.copyProperties(oldyhCbkxx, newyhCbkxx);
                    BeanUtils.copyProperties(yhCbkxx, newyhCbkxx, ToolsUtils.getnullFields(yhCbkxx));
                    if (!yhCbkxxService.update(newyhCbkxx, queryWrapper)) {
                        throw new FeesException("水表信息修改失败！", FeesErrorCode.BUSINESS_ERROR);
                    }
                    yhCbkxxService.saveLog(newyhCbkxx, oldyhCbkxx, "修改");//添加水表档案日志
                    //addDaCustomerAndMeterLog(daCustomerAndMeter, "update_bz");//操作日志添加
                    return rest;
                } else {
                    //水表编号不一致 作废原水表
                    if (null != oldyhCbkxx.getCbkid()) {
                        //和原表水表号不一致，删除原水表信息 新增水表信息
                        yhCbkxxService.remove(new QueryWrapper<YhCbkxx>().lambda()
                                .eq(YhCbkxx::getYhbh, daCustomerAndMeter.getYhKhjbxx().getYhbh()));
                        yyCblrService.remove(new QueryWrapper<YyCblr>().
                                eq("yhbh", daCustomerAndMeter.getYhKhjbxx().getYhbh()).
                                eq("cbkh", cbkh));
                        isadd = "1";
                    }
                }
            }
            if (null == oldyhCbkxx || isadd.equals("1")) {
                //没有水表信息 新增水表信息
                //抄表计划添加
                YyCblr yyCblr = new YyCblr();
                String jfzt = daCustomerAndMeter.getYhCbkxx().getJfzt();
                if (yhzt == "0" || yhzt == "申请用户") {
                    yhKhjbxx.setYhzt(YhztEnum.申请用户);//正式用户状态
                    yhCbkxx.setJfzt(JfztEnum.停用.toString());//计费状态（1正常，2停用）
                    yyCblr.setJfzt(JfztEnum.停用.getValue().toString());//正常状态
                }
                if (yhzt == "1" || yhzt == "正式用户") {
                    yhKhjbxx.setYhzt(YhztEnum.正式用户);//正式用户状态
                    yhCbkxx.setJfzt(JfztEnum.正常.toString());//计费状态（1正常，2停用）
                    yyCblr.setJfzt(JfztEnum.正常.getValue().toString());//正常状态
                }
                if (Arrays.asList("1", "正常").contains(jfzt)) {
                    yhCbkxx.setJfzt("1");//计费状态（1正常，2停用）
                    yyCblr.setJfzt("1");//正常状态（1正常，2停用）
                } else {
                    yhCbkxx.setJfzt("2");//计费状态（1正常，2停用）
                    yyCblr.setJfzt("2");//正常状态（1正常，2停用）
                }
                //申请户 创建用户档案和水表档案
                //水表档案
                yhCbkxx.setYhbh(String.valueOf(yhKhjbxx.getYhbh()));//用户编号
                yhCbkxx.setCbkh(cbkh);//抄表卡号
                String strcbkh = String.valueOf(yhKhjbxx.getYhbh()) + 1;
                yhCbkxx.setCbkid(strcbkh);//抄表卡ID
                yhCbkxx.setFmzt(FmztEnum.开阀);
                yhCbkxx.setCzryxm(daCustomerAndMeter.getYhCbkxx().getCzryxm());
                yhCbkxx.setCzrybm(daCustomerAndMeter.getYhCbkxx().getCzrybm());
                yhCbkxx.setCzsj(new Date());//操作时间
                //抄表计划
                yyCblr.setYhbh(String.valueOf(yhKhjbxx.getYhbh()));//用户编号
                yyCblr.setCbkh(cbkh);//抄表卡号
                yyCblr.setCbkid(strcbkh);//抄表卡ID

                Map<String, Object> mapcwrq = yhKhjbxxMapper.selectCwrq();//获取财务日期
                String strcwrq = mapcwrq.get("cwrq").toString();//202305
                yyCblr.setCwrq(strcwrq);//财务日期
                yyCblr.setJsbz(JsbzEnum.未算费);//计算标志

                yyCblr.setCbbz(CbbzEnum.未抄表);//未抄表状态
                yyCblr.setShbz(ShbzEnum.未审核);//未审核标志
                yyCblr.setSsgs(daCustomerAndMeter.getYhKhjbxx().getSsgs());//公司
                yyCblr.setSscbpq(daCustomerAndMeter.getYhKhjbxx().getSscbpq());//片区
                yyCblr.setSscbb(daCustomerAndMeter.getYhKhjbxx().getSscbb());//抄表本

                yyCblr.setScds(BigDecimal.valueOf(yhCbkxx.getSbqs()));
                yyCblr.setBcds(BigDecimal.valueOf(yhCbkxx.getSbqs()));

                //用户水表档案执行功
                if (!yhCbkxxService.save(yhCbkxx)) {
                    throw new FeesException("水表信息添加失败！", FeesErrorCode.BUSINESS_ERROR);
                }
                //执行抄表计划（0普表、1IC卡表、2远传表、3NB表、4流量计）
                if (daCustomerAndMeter.getYhCbkxx().getSblb().equals("0")
                        || daCustomerAndMeter.getYhCbkxx().getSblb().equals("2")
                        || daCustomerAndMeter.getYhCbkxx().getSblb().equals("3")
                        || daCustomerAndMeter.getYhCbkxx().getSblb().equals("4")) {
                    if (!yyCblrService.save(yyCblr)) {
                        throw new FeesException("抄表计划信息添加失败！", FeesErrorCode.BUSINESS_ERROR);
                    }
                }
                if (daCustomerAndMeter.getYhCbkxx().getSblb().equals("2")
                        || daCustomerAndMeter.getYhCbkxx().getSblb().equals("3")) {
                    //执行智能表档案添加
                    if (!znbDaLogService.addznbDaLog(yhKhjbxx, yhCbkxx, "0")) {
                        throw new FeesException("智能表档案日志信息失败！", FeesErrorCode.BUSINESS_ERROR);
                    }
                }
                yhCbkxxService.saveLog(yhCbkxx, null, "添加");//添加水表档案日志
                //addDaCustomerAndMeterLog(daCustomerAndMeter, "insert_bz");//操作日志添加
            }
            //判断是否有报装附件关联
//            List<BzFileInfo> fileInfos = daCustomerAndMeter.getFileInfos();
//            if (StringUtil.isNotEmpty(fileInfos) && fileInfos.size() > 0) {
//                for (BzFileInfo fileInfo : fileInfos) {
//                    File file = new File();
//                    file.setTableName("yh_khjbxx");
//                    file.setTableBh(newYhKhjbxx.getYhbh());
//                    file.setFileXh(String.valueOf(fileInfos.indexOf(fileInfo)));
//                    file.setFileNote(fileInfo.getFilenote());
//                    file.setFileOldFn(fileInfo.getFilename());
//                    file.setFileNewFn(fileInfo.getFilepath());
//                    file.setCzsj(new Date());
//                    file.setFilely("1");
//                    iFileInfoService.save(file);
//                }
//            }
            rest.setResult(yhKhjbxx.getYhbh());
            rest.setCode(1);
            rest.setMessage("操作成功");
        }
        return rest;
    }

    @ApiOperation(value = "报装用户建档用户、水表基本信息（批量）")
    @PostMapping("/batchSaveBZCustomerAndMeter")
    @Transactional(rollbackFor = Exception.class) //声明式事务管理
    public List<Map> batchSaveBzYhda(@RequestBody List<DaCustomerAndMeter> list) throws Exception {
        List<Map> restData = new ArrayList<>();
        for (DaCustomerAndMeter daCustomerAndMeter : list) {
            Map<String, Object> objectMap = new HashMap<>();
            ResultRespone respone = saveBzYhda(daCustomerAndMeter);
            if (respone.getCode().equals(1)) {
                objectMap.put("batid", daCustomerAndMeter.getBatid());
                objectMap.put("yhbh", respone.getResult());
                objectMap.put("message", "成功");
            } else {
                objectMap.put("batid", daCustomerAndMeter.getBatid());
                objectMap.put("message", "创建失败，失败原因：" + respone.getMessage());
            }
            restData.add(objectMap);
        }
        return restData;
    }

    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "修改用户档案")
    @PutMapping
    public ResultRespone<Boolean> update(@RequestBody YhKhjbxxUpdate update) {
        return ResultRespone.success(yhKhjbxxService.update(update));
    }

    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "用户编号", required = true, dataType = "String")
    })
    @DeleteMapping("/{yhbh}")
    public ResultRespone<Boolean> delById(@PathVariable String yhbh) {
        return ResultRespone.success(yhKhjbxxService.delById(yhbh));
    }

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

    @ApiOperationSupport(order = 15)
    @GetMapping("/export")
    @ApiOperation(value = "导出用户档案")
    public void export(HttpServletResponse response, @ModelAttribute YhkhjbxxFilter filter) throws IOException {
        List<YhkhjbxxSelect2> list = yhKhjbxxService.getList(filter);
        ExcleFileUtil.exportExcel(response, list, YhkhjbxxSelect2.class, "用户档案.xlsx", filter.getExportFields());
    }

    @ApiOperationSupport(order = 17)
    @GetMapping("/{yhbh}/yhcbkxx")
    @ApiOperation(value = "查询水表档案", response = YhCbkxxSelect.class, responseContainer = "List")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "yhbh", required = true, dataType = "String")
    })
    public ResultRespone<List<YhCbkxxSelect>> getCbkxxById(@PathVariable("yhbh") String yhbh) {
        return ResultRespone.success(yhKhjbxxService.getCbkxxById(yhbh));
    }

    @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(yhKhjbxxService.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(yhKhjbxxService.enable(yhbh));
    }

    @ApiOperationSupport(order = 26)
    @ApiOperation(value = "批量配置(撤销)抄表本(册)")
    @PutMapping("/sscbb")
    public ResultRespone<Boolean> update(@RequestBody YhKhjbxxSscbbUpdate update) {
        return ResultRespone.success(yhKhjbxxService.updateSscbb(update));
    }

    @ApiOperationSupport(order = 27)
    @ApiOperation(value = "智能表档案分页查询")
    @GetMapping("/znbda")
    public ResultRespone<PageResult<ZnbYhdaSelect>> getZnbDaPage(PageDto pageDto, @ModelAttribute ZnbYhdaFilter query) {
        PageResult<ZnbYhdaSelect> pageResult = yhKhjbxxService.getZnbDaPage(pageDto, query);
        return ResultRespone.success(pageResult);
    }

    @ApiOperationSupport(order = 28)
    @ApiOperation(value = "用户抄表本未分配分页查询")
    @GetMapping("/cbbwfp/page")
    public ResultRespone<PageResult<YhkhjbxxSelect>> getCbbWfpPage(PageDto pageDto, @ModelAttribute YhkhjbxxCbbWfpFilter filter) {
        PageResult<YhkhjbxxSelect> pageResult = yhKhjbxxService.getPage_cbbwfp(pageDto, filter).toVo();
        return ResultRespone.success(pageResult);
    }

    @ApiOperationSupport(order = 29)
    @ApiOperation(value = "用户抄表本已分配分页查询")
    @GetMapping("/cbbyfp/page")
    public ResultRespone<PageResult<YhkhjbxxSelect>> getCbbYfpPage(PageDto pageDto, @ModelAttribute YhkhjbxxCbbWfpFilter filter) {
        if (StringUtils.isEmpty(filter.getSsgs()))
            throw new FeesException("所属公司不能为空", FeesErrorCode.BUSINESS_ERROR);
        if (StringUtils.isEmpty(filter.getSscbpq()))
            throw new FeesException("所属抄表片区不能为空", FeesErrorCode.BUSINESS_ERROR);
        PageResult<YhkhjbxxSelect> pageResult = yhKhjbxxService.getPage_cbbyfp(pageDto, filter).toVo();
        return ResultRespone.success(pageResult);
    }

    @ApiOperationSupport(order = 30)
    @ApiOperation(value = "用户档案联系电话修改")
    @PutMapping("updatephone")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "用户编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "phone", value = "联系电话", required = true, dataType = "String")
    })
    public ResultRespone<Boolean> updatePhone(String yhbh, String phone) {
        if (StringUtil.isEmpty(yhbh)) {
            throw new FeesException("用户编号不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(phone)) {
            throw new FeesException("联系电话不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        return ResultRespone.success(yhKhjbxxService.lambdaUpdate()
                .set(YhKhjbxx::getLxdh, phone)
                .eq(YhKhjbxx::getYhbh, yhbh)
                .update());
    }

    @ApiOperationSupport(order = 31)
    @ApiOperation(value = "工单完成接口")
    @PutMapping("/gdwc")
    @Transactional(rollbackFor = Exception.class) //声明式事务管理
    public ResultRespone gdwc(@RequestBody GdwcUpdate update) {
        System.out.println("工单完成参数接受：" + JSON.toJSONString(update));
        if (StringUtil.isEmpty(update.getGdbh()))
            throw new FeesException("工单编号不能为空", FeesErrorCode.BUSINESS_ERROR);
        if (StringUtil.isEmpty(update.getGdzt()))
            throw new FeesException("工单状态不能为空", FeesErrorCode.BUSINESS_ERROR);
        if (StringUtil.isEmpty(Collections.singleton(update.getYwlx())))
            throw new FeesException("业务类型不能为空", FeesErrorCode.BUSINESS_ERROR);
        if (StringUtil.isEmpty(update.getBh()))
            throw new FeesException("业务编号不能为空", FeesErrorCode.BUSINESS_ERROR);
        ResultRespone<Object> rest = new ResultRespone<>();
        rest.setCode(1);
        rest.setMessage("操作成功");
        switch (update.getYwlx()) {
            case 销户:
                YhhLog yhhLog = yhhLogService.getById(update.getBh());
                if (StringUtil.isNull(yhhLog)) {
                    throw new FeesException("参数错误，用户销户记录不存在", FeesErrorCode.BUSINESS_ERROR);
                }
                yhhLog.setGdzt(update.getGdzt());
                yhhLog.setGdbh(update.getGdbh());
                if (!yhhLogService.updateById(yhhLog)) {
                    throw new FeesException("用户销户记录更新失败", FeesErrorCode.BUSINESS_ERROR);
                }
                if (update.getGdzt().equals("2")) {
                    //同步用户档案状态
                    YhKhjbxx yhKhjbxx = new YhKhjbxx();
                    yhKhjbxx.setYhbh(yhhLog.getYhbh());//用户编号
                    yhKhjbxx.setYhzt(YhztEnum.销户用户);
                    if (!yhKhjbxxService.updateById(yhKhjbxx)) {
                        throw new FeesException("用户档案更新失败", FeesErrorCode.BUSINESS_ERROR);
                    }
                }
                break;
            case 停水:
                YhBtLog yhBtLog = yhBtLogService.getById(update.getBh());
                if (StringUtil.isNull(yhBtLog)) {
                    throw new FeesException("参数错误，用户报停记录不存在", FeesErrorCode.BUSINESS_ERROR);
                }

                yhBtLog.setGdzt(update.getGdzt());
                yhBtLog.setGdbh(update.getGdbh());
                if (!yhBtLogService.updateById(yhBtLog)) {
                    throw new FeesException("用户报停记录更新失败", FeesErrorCode.BUSINESS_ERROR);
                }

                if (update.getGdzt().equals("2")) {
                    //同步用户档案状态
                    YhKhjbxx yhKhjbxx = new YhKhjbxx();
                    yhKhjbxx.setYhbh(yhBtLog.getYhbh());//用户编号
                    yhKhjbxx.setYhzt(YhztEnum.报停用户);
                    if (!yhKhjbxxService.updateById(yhKhjbxx)) {
                        throw new FeesException("修改用户档案失败", FeesErrorCode.BUSINESS_ERROR);
                    }
                    //抄表卡信息
                    YhCbkxx yhCbkxx = new YhCbkxx();
                    yhCbkxx.setCbkid(yhBtLog.getCbkid());
                    yhCbkxx.setYhbh(yhBtLog.getYhbh());
                    yhCbkxx.setJfzt("2");//1正常2停用
                    if (!yhCbkxxService.updateById(yhCbkxx)) {
                        throw new FeesException("修改用户抄表卡信息失败", FeesErrorCode.BUSINESS_ERROR);
                    }
                    //抄表计划添加
                    YyCblr yyCblr = new YyCblr();
                    yyCblr.setCbkid(yhBtLog.getCbkid());
                    yyCblr.setJfzt("2");
                    yyCblr.setYhbh(yhBtLog.getYhbh());
                    if (!yyCblrService.updateById(yyCblr)) {
                        throw new FeesException("修改抄表计划失败", FeesErrorCode.BUSINESS_ERROR);
                    }
                }
                break;
            case 换表:
                YkHbLog log = ykHbLogService.getById(update.getBh());
                log.setGdzt(update.getGdzt());
                log.setGdbh(update.getGdbh());
                if (!ykHbLogService.updateById(log)) {
                    throw new FeesException("用户换表记录更新失败", FeesErrorCode.BUSINESS_ERROR);
                }
                if (update.getGdzt().equals("2")) {
                    Date dtNow = new Date();
                    //水表档案更新，依次为：水表编号、水表类别、水表厂家、水表型号、水表口径、水表量程、出厂日期
                    String cbkid = log.getCbkid();
                    YhCbkxx yhCbkxx = yhCbkxxService.getById(cbkid);
                    if (yhCbkxx == null) {
                        throw new FeesException("抄表卡不存在", FeesErrorCode.BUSINESS_ERROR);
                    }
                    yhCbkxx.setSbbh(log.getNewSbbh());
                    yhCbkxx.setSblb(log.getNewSblb());
                    yhCbkxx.setSbsccj(log.getNewSbcj());
                    yhCbkxx.setSbxh(log.getNewSbxh());
                    yhCbkxx.setSbkj(log.getNewSbkj());
                    yhCbkxx.setSblc(log.getNewSblc());
                    yhCbkxx.setSbccrq(log.getNewSbccrq());

                    //更新抄表计划
                    YyCblr yyCblr = yyCblrService.getById(cbkid);
                    if (yhCbkxx == null) {
                        throw new FeesException("抄表录入不存在", FeesErrorCode.BUSINESS_ERROR);
                    }
                    yyCblr.setScds(log.getNewSbqs());
                    yyCblr.setBcds(log.getNewSbds());
                    yyCblr.setJbzd(log.getOldSbds());
                    yyCblr.setXbqd(log.getNewSbqs());
                    yyCblr.setSl(BigDecimal.ZERO);
                    //yyCblr.setSl(log.getNewSbds().subtract(log.getNewSbqs()).add(log.getOldSbds().subtract(log.getOldSbqs())));
                    yyCblr.setCbbz(CbbzEnum.已抄表);
                    yyCblr.setJsbz(JsbzEnum.未算费);
                    yyCblr.setCbrq(dtNow);
                    yyCblr.setLrrq(dtNow);
                    yyCblr.setSbzt("17");//换表
                    yyCblr.setCblx("-3");//洗换表
                    yyCblr.setCbfs("1");//实抄
                    yyCblr.setLrrybm(log.getLrry());
                    yyCblr.setLrryxm(log.getLrryxm());
                    yyCblr.setBz("换表处理");
                    //水表档案查询条件
                    LambdaQueryWrapper<YhCbkxx> queryWrapper = new QueryWrapper<YhCbkxx>().lambda();
                    queryWrapper.eq(YhCbkxx::getCbkid, cbkid);
                    //抄表计划查询条件
                    LambdaQueryWrapper<YyCblr> queryWrapper_cblr = new QueryWrapper<YyCblr>().lambda();
                    queryWrapper_cblr.eq(YyCblr::getCbkid, cbkid);
                    //换表日志查询条件
                    LambdaQueryWrapper<YkHbLog> queryWrapper_ykhb = new QueryWrapper<YkHbLog>().lambda();
                    queryWrapper_ykhb.eq(YkHbLog::getId, log.getId());
                    if (ykHbLogService.update(log, queryWrapper_ykhb) &&
                            yhCbkxxService.update(yhCbkxx, queryWrapper) &&
                            yyCblrService.update(yyCblr, queryWrapper_cblr)) {
                        rest.setResult(update.getGdbh());
                    } else {
                        throw new FeesException("换表失败", FeesErrorCode.BUSINESS_ERROR);
                    }
                }
                break;
            case 恢复用水申请:
                YhHfysLog yhHfysLog = yhHfysLogService.getById(update.getBh());
                yhHfysLog.setGdzt(update.getGdzt());
                yhHfysLog.setGdbh(update.getGdbh());
                if (!yhHfysLogService.updateById(yhHfysLog)) {
                    throw new FeesException("恢复用水记录更新失败", FeesErrorCode.BUSINESS_ERROR);
                }
                if (update.getGdzt().equals("2")) {
                    YhCbkxx yhCbkxx1 = new YhCbkxx();
                    yhCbkxx1.setCbkid(yhHfysLog.getCbkid());
                    yhCbkxx1.setJfzt("1");//1正常2停用

                    //抄表录入
                    //抄表计划添加
                    YyCblr yyCblr1 = new YyCblr();
                    yyCblr1.setCbkid(yhHfysLog.getCbkid());
                    yyCblr1.setJfzt("1");
                    yyCblr1.setYhbh(yhHfysLog.getYhbh());

                    YhKhjbxx yhKhjbxx1 = new YhKhjbxx();
                    yhKhjbxx1.setYhbh(yhHfysLog.getYhbh());//用户编号
                    yhKhjbxx1.setYhzt(YhztEnum.正式用户);//用户状态

                    if (yhKhjbxxService.updateById(yhKhjbxx1) &&
                            yhCbkxxService.updateById(yhCbkxx1) &&
                            yyCblrService.updateById(yyCblr1)) {

                    } else {
                        throw new FeesException("操作失败", FeesErrorCode.BUSINESS_ERROR);
                    }
                }
                break;
            case 用水性质变更申请:
                YhXzbgLog yhXzbgLog = yhXzbgLogService.getById(update.getBh());
                yhXzbgLog.setGdzt(update.getGdzt());
                yhXzbgLog.setGdbh(update.getGdbh());
                if (!yhXzbgLogService.updateById(yhXzbgLog)) {
                    throw new FeesException("用户性质变更记录更新失败", FeesErrorCode.BUSINESS_ERROR);
                }
                if (update.getGdzt().equals("2")) {
                    YhCbkxx yhCbkxx2 = new YhCbkxx();
                    yhCbkxx2.setYbdjbz(yhXzbgLog.getNewYbdjbz());
                    yhCbkxx2.setSjbm(yhXzbgLog.getNewSjbm());
                    yhCbkxx2.setSlbl(yhXzbgLog.getNewSlbl());
                    yhCbkxx2.setSjbm1(yhXzbgLog.getNewSjbm1());
                    yhCbkxx2.setSlbl1(yhXzbgLog.getNewSlbl1());
                    yhCbkxx2.setSjbm2(yhXzbgLog.getNewSjbm2());
                    yhCbkxx2.setSlbl2(yhXzbgLog.getNewSlbl2());
                    yhCbkxx2.setCbkid(yhXzbgLog.getCbkid());

                    if (yhCbkxxService.updateById(yhCbkxx2)) {

                    } else {
                        throw new FeesException("操作失败", FeesErrorCode.BUSINESS_ERROR);
                    }
                }
                break;
            case 用户违约金金额减免:
                boolean tf = wyjtzService.lambdaUpdate()
                        .set(YyWyjtz::getGdbh, update.getGdbh())
                        .set(YyWyjtz::getGdzt, update.getGdzt())
                        .eq(YyWyjtz::getGdlsbh, update.getBh())
                        .update();
                if (!tf) {
                    throw new FeesException("操作失败", FeesErrorCode.BUSINESS_ERROR);
                }
//                if (update.getGdzt().equals("2")) {
//                    //计算违约金
//                    List<YyQfmx> list = yyQfmxService.lambdaQuery()
//                            .eq(YyQfmx::getSfbz, "0")
//                            .eq(YyQfmx::getChbz, "0")
//                            .eq(YyQfmx::getSfbc, "0")
//                            .apply(String.format("id in (select qfid from yy_wyjtz where gdlsbh='%s')", update.getBh()))
//                            .list();
//                    znjCal.YyQfmxZnj(list.get(0).getYhbh(), list);
//                }
                break;
            case 欠费明细变更:
                YyQfmxGd yyQfmxGd = yyQfmxGdService.getById(update.getBh());
                if (StringUtil.isNull(yyQfmxGd)) {
                    throw new FeesException("欠费明细变更工单不存在", FeesErrorCode.BUSINESS_ERROR);
                }
                tf = yyQfmxService.lambdaUpdate()
                        .set(YyQfmx::getGdzt, update.getGdzt())
                        .set(YyQfmx::getGdshrybm, update.getGdshrybm())
                        .set(YyQfmx::getGdshryxm, update.getGdshryxm())
                        .set(YyQfmx::getJyType, yyQfmxGd.getJyType())
                        .eq(YyQfmx::getGdlsbh, update.getBh())
                        .update();

                if (!tf) {
                    throw new FeesException("操作失败", FeesErrorCode.BUSINESS_ERROR);
                }
                if (update.getGdzt().equals("2")) {
                    yyQfmxService.qfmxbgPlcj(update.getBh());
                }
                break;
            case 费用录入:
                YyBgLog yyBgLog = new YyBgLog();
                yyBgLog.setGdzt(update.getGdzt());
                yyBgLog.setGdbh(update.getGdbh());
                yyBgLog.setId(update.getBh());
                if (!yyBgLogService.save(yyBgLog)) {
                    throw new FeesException("费用录入记录保存失败", FeesErrorCode.BUSINESS_ERROR);
                }
                break;
            default:
                rest.setCode(0);
                rest.setMessage("业务类型错误，没有对应的业务类型！");
                break;
        }
        return rest;
    }

    @ApiOperationSupport(order = 32)
    @ApiOperation(value = "新增用户统计", response = YhkhjbxxXzyhSelect.class, responseContainer = "List")
    @PostMapping("/xzyhtj")
    public ResultRespone<List<YhkhjbxxXzyhSelect>> xzyhtj(@RequestBody YhkhjbxxXzyhFilter filter) {
        return ResultRespone.success(yhKhjbxxService.xzyhtj(filter));
    }

    @ApiOperationSupport(order = 33)
    @ApiOperation(value = "获取最大的用户编号")
    @PostMapping("/getMaxyhbh")
    @ApiImplicitParam(name = "sbyt", value = "水表用途", required = true, dataType = "String")
    public ResultRespone<String> getMaxyhbh(String sbyt) {
        Integer maxyhbh = 0;
        if (sbyt.equals("5")) {
            maxyhbh = yhKhjbxxMapper.selectMaxYhbh_jk();
        } else {
            maxyhbh = yhKhjbxxMapper.selectMaxYhbh_fjk();
        }
        return ResultRespone.success(maxyhbh.toString());
    }

    @GetMapping("/dbh/page")
    @ApiOperation(value = "低保户page分页查询")
    public ResultRespone getYhDbhxxPage(Page page, @ModelAttribute YhkhjbxxDbhlsFilter filter) {
        // 执行分页查询
        Page yhDbhxxPage = yhKhjbxxMapper.getYhDbhxxPage(page, filter);

        return ResultRespone.success(yhDbhxxPage);
    }

    @GetMapping("/dbh/export")
    @ApiOperation(value = "export导出-低保户")
    public void export(HttpServletResponse response, @ModelAttribute YhkhjbxxDbhlsFilter filter) throws IOException {
        // 执行分页查询
        List<YhkhjbxxDbhSelect> list = yhKhjbxxMapper.getYhDbhxxPage(filter);

        ExcleFileUtil.exportExcel(response, list, YhkhjbxxDbhSelect.class, "低保户导出.xlsx", filter.getExportFields());
    }

    @GetMapping("getYhxx")
    @ApiOperation(value = "获取用户信息")
    public ResultRespone<Yhkhqbxx> getYhxx(String yhbh) {
        return ResultRespone.success(yhKhjbxxMapper.getYhxx(yhbh));
    }

    /**
     * 用户档案水表档案日志添加
     */
    public ResultRespone<Object> addDaCustomerAndMeterLog(DaCustomerAndMeter daCustomerAndMeter, String operationType) throws Exception {
        // 用户档案操作日志
        YhKhjbxx yhKhjbxx = daCustomerAndMeter.getYhKhjbxx();
        YhKhjbxxLog daCustomerLog = new YhKhjbxxLog();
        BeanUtils.copyProperties(yhKhjbxx, daCustomerLog);
        daCustomerLog.setLogCzsj(new Date());
        daCustomerLog.setCzsj(new Date());
        daCustomerLog.setLogCzryxm(yhKhjbxx.getCzryxm());
        daCustomerLog.setLogCzrybm(yhKhjbxx.getCzrybm());
        daCustomerLog.setCzryxm(yhKhjbxx.getCzryxm());
        daCustomerLog.setCzrybm(yhKhjbxx.getCzrybm());
        daCustomerLog.setLogId(GuidGenerator.getGuid());
        daCustomerLog.setNewJson(JSONUtil.toJsonStr(yhKhjbxx));
        if (operationType.equals("save")) {
            daCustomerLog.setLogCzlx("添加");
            daCustomerLog.setLogCllx("添加");
        } else {
            daCustomerLog.setLogCzlx("修改");
            daCustomerLog.setLogCllx("修改");
            daCustomerLog.setOldJson(daCustomerAndMeter.getKhOldJson());
        }
        yhKhjbxxLogService.save(daCustomerLog);

        // 水表档案操作日志记录
        YhCbkxx yhCbkxx = daCustomerAndMeter.getYhCbkxx();
        YhCbkxxLog daMeterLog = new YhCbkxxLog();
        BeanUtils.copyProperties(yhCbkxx, daMeterLog);
        daMeterLog.setLogId(GuidGenerator.getGuid());
        daMeterLog.setLogLsh("");
        daMeterLog.setLogCzsj(new Date());
        daMeterLog.setLogCzryxm(yhCbkxx.getCzryxm());
        daMeterLog.setLogCzrybm(yhCbkxx.getCzrybm());
        daMeterLog.setBz("");
        daMeterLog.setNewJson(JSONUtil.toJsonStr(yhCbkxx));
        if (operationType.equals("save")) {
            daMeterLog.setLogCzlx("添加");
            daMeterLog.setLogCllx("添加");
        } else {
            daMeterLog.setLogCzlx("修改");
            daMeterLog.setLogCllx("修改");
            daMeterLog.setOldJson(daCustomerAndMeter.getCbkOldJson());
        }
        yhCbkxxLogService.save(daMeterLog);
        return ResultRespone.success("操作成功");
    }

    public String getChineseInitial(String chinese) {
        StringBuilder initials = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
            if (pinyinArray != null) {
                initials.append(pinyinArray[0].charAt(0));
            } else {
                initials.append(c);
            }
        }
        return initials.toString();
    }

    private void zhcsh(YhKhjbxx yhKhjbxx) {
        String yhid;
        String khbm = yhKhjbxx.getKhbm();

        // 大户账户初始化
        if (StrUtil.isNotEmpty(khbm)) {
            Integer zhbz = yhKhjbxx.getZhbz();
            YhKhjbxx dhzhxx = yhKhjbxxService.selectByKhbm(khbm);

            // 如果添加大户时没有选主户标志,第一个默认为主户
            if (ObjUtil.isNull(zhbz)) {
                if (ObjUtil.isNull(dhzhxx)) {
                    yhKhjbxx.setZhbz(1);
                } else {
                    yhKhjbxx.setZhbz(0);
                }
            }

            if (yhKhjbxx.getZhbz() == 1 && ObjUtil.isNotNull(dhzhxx)) {
                throw new FeesException("客户编码:" + khbm + "下已存在主户", FeesErrorCode.BUSINESS_ERROR);
            }

            yhid = khbm;
        } else {
            yhid = yhKhjbxx.getYhbh();
        }

        LambdaQueryWrapper<YyZjzh> queryWrapper = Wrappers.<YyZjzh>lambdaQuery().eq(YyZjzh::getYhbh, yhid);
        long count = zjzhService.count(queryWrapper);
        if (count < 1) {
            YyZjzh zjzh = new YyZjzh();
            zjzh.setYhbh(yhid);
            zjzh.setYfje(BigDecimal.ZERO);
            zjzh.setKjje(BigDecimal.ZERO);
            zjzh.setSyje(BigDecimal.ZERO);
            zjzh.setNbsyje(BigDecimal.ZERO);
            zjzhService.save(zjzh);
        }
    }

    // 添加与修改时检查主户客户编号是否重复
    private void checkZhbzByUpdate(YhKhjbxx yhKhjbxx) {
        Integer dxh = yhKhjbxx.getDxh();
        Integer zhbz = yhKhjbxx.getZhbz();

        if (ObjUtil.isNotNull(dxh) && dxh == 1) {
            if (ObjUtil.isNull(zhbz)) {
                throw new FeesException("请选择主户标志", FeesErrorCode.BUSINESS_ERROR);
            }

            String khbm = yhKhjbxx.getKhbm();
            YhKhjbxx dhzhxx = yhKhjbxxService.selectByKhbm(khbm);
            //判断用户编码是否是同一个
            if (ObjUtil.isNotNull(dhzhxx) && !dhzhxx.getYhbh().equals(yhKhjbxx.getYhbh()) && zhbz == 1) {
                throw new FeesException("该客户编号下已存在主户信息", FeesErrorCode.BUSINESS_ERROR);
            }
        }
    }
}
