package com.tofly.feesapi.bjgl.controller_easy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tofly.feesapi.bmgl.entity.BmCbb;
import com.tofly.feesapi.bmgl.service.BmCbbService;
import com.tofly.feesapi.cbgl.entity.YyCblrLs;
import com.tofly.feesapi.cbgl.service.YyCblrLsService;
import com.tofly.feesapi.common.constant.ShbzEnum;
import com.tofly.feesapi.common.core.ResultRespone;
import com.tofly.feesapi.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bjgl.entity.YkHbLog;
import com.tofly.feesapi.bjgl.service.YhCbkxxService;
import com.tofly.feesapi.bjgl.service.YkHbLogService;
import com.tofly.feesapi.cbgl.entity.YyCblr;
import com.tofly.feesapi.cbgl.service.YyCblrService;
import com.tofly.feesapi.common.BaseController;
import com.tofly.feesapi.common.constant.CbbzEnum;
import com.tofly.feesapi.common.constant.JsbzEnum;
import com.tofly.feesapi.common.dbhelper.DbHelper;
import com.tofly.feesapi.common.dbhelper.PageSortHelper;
import com.tofly.feesapi.common.enums.SysEnum;
import com.tofly.feesapi.common.model.CollectionData;
import com.tofly.feesapi.common.model.PageLink;

import com.tofly.feesapi.common.util.GuidGenerator;
import com.tofly.feesapi.config.FilePathBean;
import com.tofly.feesapi.file.service.IFileInfoService;
import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.sfgl.service.YyQfmxService;
import com.tofly.feesapi.yhgl.service.YhsjqxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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 org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.tofly.feesapi.common.ControllerConstants.*;
import static com.tofly.feesapi.common.ControllerConstants.SORT_ORDER_ALLOWABLE_VALUES;

@RestController
@AllArgsConstructor
@RequestMapping("/api/meterprofilemgt/ykYhbgHb")
@Api(tags = "水表档案-用户水表更换接口(easy)")
public class ykYhbgHbEasyController extends BaseController {

    @Autowired
    private YhCbkxxService yhCbkxxService;
    @Autowired
    private YkHbLogService ykYhbgLogService;
    @Autowired
    private YyCblrService yyCblrService;
    @Autowired
    private FilePathBean filePathBean;
    @Autowired
    private IFileInfoService iFileInfoService;
    @Autowired
    private YhsjqxService yhsjqxService;
    @Autowired
    private final BmCbbService bmCbbService;
    @Autowired
    private final YyCblrLsService yyCblrLsService;
    @Autowired
    private final YyQfmxService yyQfmxService;
    @ApiOperation(value = "水表更换数据列表接口")
    @PostMapping("/getMeterListForChange")
    public ResultRespone getMeterListForChange(
            @ApiParam(value = "所属公司") @RequestParam(required = false) String ssgs,
            @ApiParam(value = "所属片区") @RequestParam(required = false) String sscbpq,
            @ApiParam(value = "所属表册") @RequestParam(required = false) String sscbb,
            @ApiParam(value = "区域负责人") @RequestParam(required = false) String qyfzr,
            @ApiParam(value = "抄表人员") @RequestParam(required = false) String cby,
            @ApiParam(value = "关键字（用户编号、姓名、地址、电话）") @RequestParam(required = false) String searchText,
            @ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true, defaultValue = "10") @RequestParam(value = PAGE_SIZE_PARA_NAME, required = true) int pageSize,
            @ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true, defaultValue = "1") @RequestParam(value = PAGE_NUMBER_PARA_NAME, required = true) int page,
            @ApiParam(value = SORT_PROPERTY_DESCRIPTION) @RequestParam(required = false) String sortProperty,
            @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(required = false) String sortOrder)
            throws Exception {

        // 当前登录用户数据权限
        List<String> cbbbmList = yhsjqxService.queryByPermission();
        if (CollectionUtil.isEmpty(cbbbmList)) {
            return ResultRespone.success(new CollectionData(new ArrayList(), 0));
        }

        //region 分页、排序
        DbHelper db = DbHelper.getDbHelper();
        PageLink pg = createPageLink(pageSize, page);

        //tring strOrder = StringUtils.isBlank(sortProperty) ? "a.yhbh asc" : sortProperty + " " + sortOrder;

        String[] arrExcludeColumns = {
                "y_sblb", "y_sbccj", "y_sbxh", "y_sbccrq", "y_sbkj"
                , "y_sbbh", "y_sblc", "y_bcds", "y_scds"
        };
        String strOrder = PageSortHelper.setPageSort(sortProperty, sortOrder, arrExcludeColumns);

        //endregion
        if (StringUtils.isBlank(sortProperty)) {
            strOrder = "a.yhbh asc";
        }
        //region 查询条件
        String strWhere = "";
        //所属公司
        if (!StringUtils.isBlank(ssgs)) {
            strWhere += String.format(" and a.ssgs='%s'", ssgs);
        }
        //所属片区
        if (!StringUtils.isBlank(sscbpq)) {
            strWhere += String.format(" and a.sscbpq='%s'", sscbpq);
        }
        //所属表册
        if (!StringUtils.isBlank(sscbb)) {
            strWhere += String.format(" and a.sscbb='%s'", sscbb);
        }
        //区域负责人
        if (!StringUtils.isBlank(qyfzr)) {
            strWhere += String.format(" and a.sscbb in(select cbbbm from bm_cbb where qyfzr='%s')", qyfzr);
        }
        //抄表人员
        if (!StringUtils.isBlank(cby)) {
            strWhere += String.format(" and a.sscbb in(select cbbbm from bm_cbb where cby='%s')", cby);
        }
        //关键字
        if (!StringUtils.isBlank(searchText)) {
            strWhere += MessageFormat.format("and (a.yhbh like ''%{0}%'' or a.yhxm like ''%{0}%'' "
                    + "or a.yhdz like ''%{0}%'' or a.lxdh like ''%{0}%'')", searchText);
        }
        // 数据过滤
        if (CollectionUtil.isNotEmpty(cbbbmList)) {
            StringBuilder builder = new StringBuilder("'");
            cbbbmList.forEach(o -> builder.append(o).append("','"));
            String toString = builder.toString();
            int lastIndexOf = toString.lastIndexOf(StrUtil.COMMA);
            String substring = toString.substring(0, lastIndexOf);

            strWhere += String.format(" and a.sscbb in(%s)", substring);
        }
        //endregion

        //region 查询数据
        String strSql = MessageFormat.format("SELECT\n" +
                "\ta.yhbh,\n" +
                "\tb.cbkh,\n" +
                "\tb.cbkid,\n" +
                "\tyhxm,\n" +
                "\tyhdz,\n" +
                "\tlxdh,\n" +
                "\tsblb AS \"old_sblb\",\n" +
                "\tsbsccj AS \"old_sbsccj\",\n" +
                "\tsbxh AS \"old_sbxh\",\n" +
                "\tsbccrq AS \"old_sbccrq\",\n" +
                "\tsbkj AS \"old_sbkj\",\n" +
                "\tsbbh AS \"old_sbbh\",\n" +
                "\tsblc AS \"old_sblc\",\n" +
                "\tnvl(bcds,0) AS \"old_sbds\",\n" +
                "\tnvl(scds, 0) AS \"old_sbqs\"\n" +
                "FROM\n" +
                "\tYH_CBKXX b\n" +
                "LEFT JOIN YH_KHJBXX a ON\n" +
                "\tb.YHBH = a.YHBH\n" +
                "LEFT JOIN YY_CBLR c ON\n" +
                "\tb.CBKID = c.CBKID\n" +
                "\tWHERE a.YHZT IN(0,1,2)" +
                " {0} order by {1}", strWhere, strOrder);

        Object obj = db.getPage(pg, strSql, SysEnum.MyBatis.getName());
        return ResultRespone.success(obj);
        //endregion
    }

    @ApiOperation(value = "水表更换数据存储")
    @PostMapping(value = "/saveMeterChange", headers = "content-type=multipart/form-data")
    @Transactional(rollbackFor = Exception.class) //声明式事务管理
    public ResultRespone saveMeterChange(@Valid YkHbLog log,
                                         @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList)

            throws Exception {

        //region 必填验证
        String strNewMeterType = log.getNewSblb();
        if (StringUtils.isBlank(strNewMeterType)) {
            return ResultRespone.failed("「新表类别」不能为空！");
        }

        String strNewMeterFactory = log.getNewSbcj();
        if (StringUtils.isBlank(strNewMeterFactory)) {
            return ResultRespone.failed("「新表厂家」不能为空！");
        }

//        String strNewMeterModel = log.getNewSbxh();
//        if (StringUtils.isBlank(strNewMeterModel)) {
//            return ResultRespone.failed("「新表型号」不能为空！");
//        }

        String strNewMeterCaliber = log.getNewSbcj();
        if (StringUtils.isBlank(strNewMeterCaliber)) {
            return ResultRespone.failed("「新表口径」不能为空！");
        }

        String meterCardId = log.getCbkh().toString();
        if (StringUtils.isBlank(meterCardId)) {
            return ResultRespone.failed("「抄表卡号」不能为空！");
        }
        String yhbh = log.getYhbh();
        if (StringUtils.isBlank(yhbh)) {
            return ResultRespone.failed("「用户编号」不能为空！");
        }
        String cbkh = log.getCbkh().toString();
        if (StringUtils.isBlank(cbkh)) {
            return ResultRespone.failed("「抄表卡号」不能为空！");
        }
        //endregion

        //region 数据存储
        Date dtNow = new Date();

        //换表记录，依次为：录入时间
        log.setId(GuidGenerator.getGuid().substring(0, 8));
        log.setLrrq(dtNow);

        //水表档案更新，依次为：水表编号、水表类别、水表厂家、水表型号、水表口径、水表量程、出厂日期
        String cbkid = log.getCbkid();
        YhCbkxx yhCbkxx = yhCbkxxService.getById(cbkid);
        if (yhCbkxx == null)
            return  ResultRespone.failed("抄表卡不存在");

        yhCbkxx.setSbqs(Integer.parseInt(log.getNewSbqs().toString()));
        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 (yyCblr == null) {
         return    ResultRespone.failed("抄表录入不存在");
        }


        if (yyCblr.getCbbz().equals(CbbzEnum.已抄表) && yyCblr.getJsbz().equals(JsbzEnum.已算费)) {
            //对已抄表已算费记录进行结转
            YyCblrLs yyCblrLs = JSONObject.parseObject(JSON.toJSONString(yyCblr), YyCblrLs.class);
//            BmCbb bmCbb = bmCbbService.getById(yyCblr.getSscbb());
//            if (StringUtil.isNotNull(bmCbb)) {
//                yyCblrLs.setQyfzrbm(bmCbb.getQyfzr());
//                yyCblrLs.setQyfzrxm(bmCbb.getQyfzrxm());
//            }
            yyCblrLsService.save(yyCblrLs);
            yyCblr.setCbcs(yyCblr.getCbcs().add(BigDecimal.ONE));
        }


        yyCblr.setScds(log.getOldSbqs());
        yyCblr.setBcds(log.getNewSbqs());
        yyCblr.setJbzd(log.getOldSbds());
        yyCblr.setXbqd(log.getNewSbqs());
        //结算旧表水量
        yyCblr.setSl(log.getOldSbds().subtract(log.getOldSbqs()));


//        yyCblr.setScds(log.getNewSbds());
//        yyCblr.setBcds(log.getNewSbqs());
//        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.setCbrybm(SecurityUtils.getUserId().toString());
        yyCblr.setCbryxm(SecurityUtils.getUser().getRealName());
        yyCblr.setLrrybm(SecurityUtils.getUserId().toString());
        yyCblr.setLrryxm(SecurityUtils.getUser().getRealName());

        yyCblr.setSbzt("17");//换表
        yyCblr.setCblx("-3");//洗换表
        yyCblr.setCbfs("1");//实抄
        yyCblr.setBz("换表处理");
        yyCblr.setShbz(ShbzEnum.审核通过);
        // yyCblr.setSl(ykYhbgHb.gets());
        QueryWrapper<YhCbkxx> queryWrapper = new QueryWrapper<YhCbkxx>();
        queryWrapper.eq("yhbh", log.getYhbh())
                .and(i -> i.eq("cbkh", log.getCbkh()));
        QueryWrapper<YyCblr> queryWrapper_cblr = new QueryWrapper<YyCblr>();
        queryWrapper_cblr.eq("yhbh", log.getYhbh())
                .and(i -> i.eq("cbkh", log.getCbkh()));
        if (ykYhbgLogService.save(log) &&
                yhCbkxxService.update(yhCbkxx, queryWrapper) &&
                yyCblrService.update(yyCblr, queryWrapper_cblr)) {
            String path = filePathBean.getYhdafile();
            if (fileList.size() > 0) {
                iFileInfoService.saveFileList(fileList, path, log.getId(), "yh_hb_log", "用户换表");
            }
            /*算费*/
            yyQfmxService.hbsf(yyCblr, yhCbkxx);
            return ResultRespone.success("操作成功！");
        } else {
            return ResultRespone.failed("操作失败！");
        }
    }

    @ApiOperation(value = "水表更换数据存储(工单申请)")
    @PostMapping(value = "/saveMeterChange_gd", headers = "content-type=multipart/form-data")
    @Transactional(rollbackFor = Exception.class) //声明式事务管理
    public ResultRespone saveMeterChange_gd(@Valid YkHbLog log,
                                            @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList) {
        ResultRespone<Object> rest = new ResultRespone<>();

        //region 必填验证
        String strNewMeterType = log.getNewSblb();
        if (StringUtils.isBlank(strNewMeterType)) {
            rest.setCode(-1);
            rest.setMessage("「新表类别」不能为空！");
            return rest;
        }

        String strNewMeterFactory = log.getNewSbcj();
        if (StringUtils.isBlank(strNewMeterFactory)) {
            rest.setCode(-1);
            rest.setMessage("「新表厂家」不能为空！");
            return rest;
        }


        String strNewMeterCaliber = log.getNewSbcj();
        if (StringUtils.isBlank(strNewMeterCaliber)) {
            rest.setCode(-1);
            rest.setMessage("「新表口径」不能为空！");
            return rest;
        }

        String meterCardId = log.getCbkh().toString();
        if (StringUtils.isBlank(meterCardId)) {
            rest.setCode(-1);
            rest.setMessage("「抄表卡号」不能为空！");
            return rest;
        }
        String yhbh = log.getYhbh();
        if (StringUtils.isBlank(yhbh)) {
            rest.setCode(-1);
            rest.setMessage("「用户编号」不能为空！");
            return rest;
        }
        String cbkh = log.getCbkh().toString();
        if (StringUtils.isBlank(cbkh)) {
            rest.setCode(-1);
            rest.setMessage("「抄表卡号」不能为空！");
            return rest;
        }
        //endregion

        //region 数据存储
        Date dtNow = new Date();

        //换表记录，依次为：录入时间
        log.setId(GuidGenerator.getGuid().substring(0, 8));
        log.setLrrq(dtNow);
        log.setGdzt("1");

        if (ykYhbgLogService.save(log)) {
            if (fileList.size() > 0) {
                String path = filePathBean.getOtherfile();
                iFileInfoService.saveFileList(fileList, path, log.getId(), "yh_hb_log", "恢复用水文件");
            }
            rest.setCode(1);
            rest.setMessage("操作成功！");
            rest.setResult(log.getId());
            return rest;
        } else {
            rest.setCode(-1);
            rest.setMessage("操作失败！");
            return rest;
        }
    }
}

