package com.tofly.watermeter.custom.controller.meterRead;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.watermeter.entity.Cbqybm;
import com.tofly.watermeter.entity.Cbqydbm;
import com.tofly.watermeter.entity.Readmeterhis;
import com.tofly.watermeter.entity.Yhbingqy;
import com.tofly.watermeter.service.CbqybmService;
import com.tofly.watermeter.service.CbqydbmService;
import com.tofly.watermeter.service.ReadmeterhisService;
import com.tofly.watermeter.service.YhbingqyService;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author FlashWJL
 * @date 2021/6/1 9:51
 */
@RestController
@AllArgsConstructor
@RequestMapping("/readRegion")
@Api(tags = "抄表--抄表区域（段）管理")
public class ReadAreaController {

    private final CbqybmService cbqybmService;
    private final CbqydbmService cbqydbmService;
    private final YhbingqyService yhbingqyService;
    private final ReadmeterhisService readmeterhisService;

    /**
     * 获取区域与区域段
     * @return
     */
    @GetMapping("/getQyAndQd")
    @ApiOperation(value = "获取区域与区域段(树形结构)")
    public ResultRespone getQyAndQd(String isState) {
        return ResultRespone.success(cbqybmService.getQyAndQd(isState));
    }

    /**
     * 抄表区域分页查询
     *
     * @param page   分页对象
     * @param qybm 抄表区域编码
     * @return
     */
    @GetMapping("/readArea")
    @ApiOperation(value = "区域--抄表区域分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "qybm", value = "输入框内容搜索查询", required = true, dataType = "Long")
    })
    public ResultRespone getCbqybmPage(Page page, String qybm) {
        return ResultRespone.success(cbqybmService.page(page, Wrappers.<Cbqybm>lambdaQuery()
                .like(StringUtil.isNotEmpty(qybm),Cbqybm::getQybm , qybm)
                .or()
                .like(StringUtil.isNotEmpty(qybm) , Cbqybm::getQymc , qybm)
                .orderByAsc(Cbqybm::getQymc)));
    }

    /**
     * 通过id查询抄表区域编码
     *
     * @param qybm id
     * @return ResultRespone
     */
    @GetMapping("/readArea/{qybm}")
    @ApiOperation(value = "区域--通过区域编码查询抄表区域详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "qybm", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone getById(@PathVariable("qybm") String qybm) {
        return ResultRespone.success(cbqybmService.getOne(Wrappers.<Cbqybm>lambdaQuery().eq(Cbqybm::getQybm, qybm)));
    }

    /**
     * 新增抄表区域编码
     *
     * @param cbqybm 抄表区域编码
     * @return ResultRespone
     */
    @ApiOperation(value = "区域--新增抄表区域")
    @PostMapping("/readArea")
    public ResultRespone saveCbqy(@RequestBody Cbqybm cbqybm) {

        //保存前查询区域编码是否有重复情况
        String qybm = cbqybm.getQybm();
        if (StringUtil.isEmpty(qybm)) {
            throw new ToflyDeniedException("请输入区域编码");
        }
        Cbqybm qy = cbqybmService.getOne(Wrappers.<Cbqybm>lambdaQuery().eq(Cbqybm::getQybm, qybm));
        if (StringUtil.isNotNull(qy)) {
            throw new ToflyDeniedException("请勿输入重复区域编码");
        }
        if (StringUtil.isEmpty(cbqybm.getYxbz())) {
            cbqybm.setYxbz("0");
        }
        cbqybm.setUpdateFlag("1");
        return ResultRespone.success(cbqybmService.save(cbqybm));
    }

    /**
     * 修改抄表区域编码
     *
     * @param cbqybm 抄表区域编码
     * @return ResultRespone
     */
    @ApiOperation(value = "区域--修改抄表区域")
    @PostMapping("/updateArea")
    public ResultRespone updateCbqyById(@RequestBody Cbqybm cbqybm) {
        String qymc = cbqybm.getQymc();
        String yxbz = cbqybm.getYxbz();
        String qybm = cbqybm.getQybm();
        String bz = cbqybm.getBz();
        yhbingqyService.update(Wrappers.<Yhbingqy>lambdaUpdate().eq(Yhbingqy::getQybm , qybm).set(Yhbingqy::getUpdateFlag , "1"));
        return ResultRespone.success(cbqybmService.update(Wrappers.<Cbqybm>lambdaUpdate()
                .eq(Cbqybm::getQybm, qybm).set(StringUtil.isNotEmpty(qymc), Cbqybm::getQymc, qymc)
                .set(Cbqybm::getUpdateFlag , "1")
                .set(StringUtil.isNotEmpty(yxbz), Cbqybm::getYxbz, yxbz)
                .set(StringUtil.isNotEmpty(bz) , Cbqybm::getBz , bz)));
    }

    /**
     * 通过id批量删除抄表区域编码
     *
     * @param qybms ids
     * @return ResultRespone
     */
    @ApiOperation(value = "区域--通过区域编码批量删除抄表区域")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "qybms", value = "批量删除，多个qybm以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteAreaByIds")
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone removeByIds(String qybms) {
        List<String> qybmList = Arrays.asList(qybms.split(","));
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder qyStr = new StringBuilder();
        StringBuilder qyPlanStr = new StringBuilder();
        //批量删除，但是删除的区域个数不是很多，差不多几个几个的删除
        qybmList.forEach(k -> {
            int i = yhbingqyService.count(Wrappers.<Yhbingqy>lambdaQuery().eq(Yhbingqy::getQybm , k).select(Yhbingqy::getQybm));
            int q = cbqydbmService.count(Wrappers.<Cbqydbm>lambdaQuery().eq(Cbqydbm::getQybm , k).select(Cbqydbm::getQybm));
            //如果存在了抄表计划，就不能删除
            Readmeterhis readmeterhis = readmeterhisService.getOne(Wrappers.<Readmeterhis>lambdaQuery().eq(Readmeterhis::getCbqyBm , k)
                    .select(Readmeterhis::getYhbh , Readmeterhis::getCbqyBm).apply("ROWNUM = 1"));
            if (i > 0) {
                stringBuilder.append(k + ",");
            }
            if (q > 0){
                qyStr.append(k+",");
            }
            if (StringUtil.isNotNull(readmeterhis)){
                qyPlanStr.append(k+",");
            }
        });
        if (stringBuilder.length() > 0) {
            throw new ToflyDeniedException("以下区域编码：" + stringBuilder + "已经绑定用户，无法删除");
        }
        if (qyStr.length() > 0) {
            throw new ToflyDeniedException("以下区域编码：" + qyStr + "绑定了区域段，无法删除");
        }
        if (qyPlanStr.length() > 0) {
            throw new ToflyDeniedException("以下区域编码：" + qyPlanStr + "已经生成抄表计划，无法删除");
        }
        cbqybmService.remove(Wrappers.<Cbqybm>lambdaQuery().in(Cbqybm::getQybm, qybmList));
        return ResultRespone.success("成功");
    }



    /**
     * 区域段分页查询
     *
     * @param page    分页对象
     * @return
     */
    @GetMapping("/paragraph")
    @ApiOperation(value = "区域段--分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "input", value = "输入框内容搜索查询", required = true, dataType = "String"),
            @ApiImplicitParam(name = "qybm", value = "所属区域编码", required = true, dataType = "Long")
    })
    public ResultRespone getCbqydbmPage(Page page, String input , String qybm) {

        return ResultRespone.success(cbqydbmService.list(Wrappers.<Cbqydbm>lambdaQuery()
                .eq(StringUtil.isNotEmpty(qybm) , Cbqydbm::getQybm , qybm)
                .like(StringUtil.isNotEmpty(input) , Cbqydbm::getQydmc , input )
                .orderByAsc(Cbqydbm::getQydmc)));
    }

    @GetMapping("/period")
    @ApiOperation(value = "区域段--得到抄表周期")
    public ResultRespone allocationPeriod() {
        List<Integer> cbzq = new ArrayList<>();
        for(int i =0 ; i<25 ; i++){
            Integer zq = 1 + i;
            cbzq.add(zq);
        }
        return ResultRespone.success(cbzq);
    }


    /**
     * 通过id查询抄表区域段编码
     *
     * @param qydbm 区域段编码
     * @return ResultRespone
     */
    @GetMapping("/paragraph/{qydbm}")
    @ApiOperation(value = "区域段--通过区域段编码查询区域段")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "qydbm", value = "区域段编码", required = true, dataType = "String")
    })
    public ResultRespone getParaById(@PathVariable("qydbm") String qydbm) {
        return ResultRespone.success(cbqydbmService.getOne(Wrappers.<Cbqydbm>lambdaQuery().eq(Cbqydbm::getQydbm, qydbm)));
    }

    /**
     * 新增抄表区域段编码
     *
     * @param cbqydbm 抄表区域段编码
     * @return ResultRespone
     */
    @ApiOperation(value = "区域段--新增抄表区域段编码")
    @PostMapping("/paragraph")
    public ResultRespone saveCbqyd(@RequestBody Cbqydbm cbqydbm) {

        String qybm = cbqydbm.getQybm();
        String yxbz = cbqydbm.getYxbz();
        String qydmc= cbqydbm.getQydmc();
        if (StringUtil.isEmpty(qydmc)) {
            throw new ToflyDeniedException("请输入区域段名称");
        }
        if (StringUtil.isEmpty(qybm)) {
            throw new ToflyDeniedException("请选择区域");
        }
        if (StringUtil.isEmpty(yxbz)) {
            cbqydbm.setYxbz("0");
        }
        Cbqydbm serviceOne = cbqydbmService.getOne(Wrappers.<Cbqydbm>lambdaQuery().eq(Cbqydbm::getQydmc, qydmc).eq(Cbqydbm::getQybm , qybm));
        if (StringUtil.isNotNull(serviceOne)) {
            throw new ToflyDeniedException("该区域下已有抄表段："+qydmc);
        }
        Long qydbm = cbqydbmService.getMaxId();
        cbqydbm.setQydbm(qydbm.toString());
        cbqydbm.setUpdateFlag("1");
        return ResultRespone.success(cbqydbmService.save(cbqydbm));
    }

    /**
     * 修改抄表区域段编码
     *
     * @param cbqydbm 抄表区域段编码
     * @return ResultRespone
     */
    @ApiOperation(value = "区域段--修改抄表区域段编码")
    @PostMapping("/updateParagraph")
    public ResultRespone updateCbqydById(@RequestBody Cbqydbm cbqydbm) {
        String qydbm = cbqydbm.getQydbm();
        String qybm = cbqydbm.getQybm();
        String yxbz = cbqydbm.getYxbz();
        String qydmc = cbqydbm.getQydmc();
        String bz = cbqydbm.getBz();
        String yhdqh = cbqydbm.getYhdqh();
        if (StringUtil.isEmpty(qydbm)){
            throw new ToflyDeniedException("请传递区域段编码");
        }
        //判断区域段的名称是否在这下面有重复的
        Cbqydbm queryQyd = cbqydbmService.getOne(Wrappers.<Cbqydbm>lambdaQuery()
                .eq(Cbqydbm::getQybm , qybm).ne(Cbqydbm::getQydbm , qydbm).eq(Cbqydbm::getQydmc , qydmc));
        if (StringUtil.isNotNull(queryQyd)){
            throw new ToflyDeniedException("区域："+queryQyd.getQymc()+"已存在抄表段："+qydmc);
        }
        yhbingqyService.update(Wrappers.<Yhbingqy>lambdaUpdate().eq(Yhbingqy::getQydbm , qydbm).set(Yhbingqy::getUpdateFlag , "1"));
        return ResultRespone.success(cbqydbmService.update(Wrappers.<Cbqydbm>lambdaUpdate()
                .eq(Cbqydbm::getQydbm, qydbm).set(Cbqydbm::getUpdateFlag , "1")
                .set(StringUtil.isNotEmpty(qydmc) , Cbqydbm::getQydmc , qydmc)
                .set(StringUtil.isNotNull(qybm), Cbqydbm::getQybm, qybm)
                .set(StringUtil.isNotEmpty(yxbz), Cbqydbm::getYxbz, yxbz)
                .set(StringUtil.isNotEmpty(bz), Cbqydbm::getBz, bz)
                .set(StringUtil.isNotNull(yhdqh) , Cbqydbm::getYhdqh , yhdqh)));
    }

    /**
     * 通过id批量删除抄表区域段编码
     *
     * @param ids id
     * @return ResultRespone
     */
    @ApiOperation(value = "区域段--通过区域段编码批量删除抄表区域段")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个区域段编码以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/paragraph")
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone removeCbqydByIds(String ids) {
        List<String> qydbmList = Arrays.asList(ids.split(","));
        List<String> stringBuilder = new ArrayList<>();
        List<String> qyPlanStr = new ArrayList<>();
        //批量删除，但是删除的区域个数不是很多，差不多几个几个的删除
        qydbmList.forEach(k -> {
            int i = yhbingqyService.count(Wrappers.<Yhbingqy>lambdaQuery().eq(Yhbingqy::getQydbm , k).select(Yhbingqy::getQydbm));
            Readmeterhis readmeterhis = readmeterhisService.getOne(Wrappers.<Readmeterhis>lambdaQuery().eq(Readmeterhis::getCbqydBm , k)
                    .select(Readmeterhis::getYhbh , Readmeterhis::getCbqydBm).apply("ROWNUM = 1"));
            if (i > 0) {
                stringBuilder.add(k);
            }
            else if (StringUtil.isNotNull(readmeterhis)){
                qyPlanStr.add(k);
            }
            else {
                //删除区域段
                cbqydbmService.remove(Wrappers.<Cbqydbm>lambdaQuery().eq(Cbqydbm::getQydbm, k));
            }
        });
        if (stringBuilder.size() > 0) {
            List<Cbqydbm> qydmcList = cbqydbmService.list(Wrappers.<Cbqydbm>lambdaQuery().in(Cbqydbm::getQydbm , stringBuilder).select(Cbqydbm::getQydmc));
            throw new ToflyDeniedException("以下区域段：" + qydmcList.stream().map(Cbqydbm::getQydmc).collect(Collectors.joining(",")) + "已经绑定用户，无法删除");
        }
        if (qyPlanStr.size() > 0) {
            List<Cbqydbm> qydmcList = cbqydbmService.list(Wrappers.<Cbqydbm>lambdaQuery().in(Cbqydbm::getQydbm , qyPlanStr).select(Cbqydbm::getQydmc));
            throw new ToflyDeniedException("以下区域段：" + qydmcList.stream().map(Cbqydbm::getQydmc).collect(Collectors.joining(",")) + "已经生成抄表计划，无法删除");
        }
        return ResultRespone.success("成功");
    }

    @GetMapping("/qydCollect")
    @ApiOperation(value = "区域段--区域和区域段汇总数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "inputcontent", value = "搜索内容", required = false, dataType = "String")
    })
    public ResultRespone getQydCollect(Page page , String inputcontent) {
        return ResultRespone.success(cbqydbmService.getQydCollect(page , inputcontent));
    }


    @PostMapping("/importCbqydFile")
    @ApiOperation(value = "区域段--批量导入")
    public ResultRespone importCbqydFile(@RequestParam("file") MultipartFile file) {
        return ResultRespone.success(cbqydbmService.importCbqydFile(file));
    }


}
