package com.tofly.feesapi.yhgl.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bjgl.service.YhCbkxxService;
import com.tofly.feesapi.bmgl.entity.BmSj;
import com.tofly.feesapi.bmgl.entity.BmYslx;
import com.tofly.feesapi.bmgl.service.BmSjService;
import com.tofly.feesapi.bmgl.service.BmYslxService;
import com.tofly.feesapi.common.Excel.ExcleFileUtil;
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.config.FilePathBean;
import com.tofly.feesapi.file.service.IFileInfoService;
import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.entity.YhXzbgLog;
import com.tofly.feesapi.yhgl.entity.dto.YhXzbgLogFilter;
import com.tofly.feesapi.yhgl.entity.dto.YhXzbgLogInsert;
import com.tofly.feesapi.yhgl.entity.vo.YhXzbgLogSelect;
import com.tofly.feesapi.yhgl.entity.vo.YhXzbhSjVo;
import com.tofly.feesapi.yhgl.mapper.YhXzbgLogMapper;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import com.tofly.feesapi.yhgl.service.YhXzbgLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("api/yhgl/yhxzbglog")
@Api(tags = "用户管理-用户性质变更记录接口")
public class YhXzbgLogController {

    @Autowired
    private YhXzbgLogService yhXzbgLogService;
    @Autowired
    private IFileInfoService iFileInfoService;
    @Autowired
    private FilePathBean filePathBean;
    @Autowired
    private YhXzbgLogMapper yhXzbgLogMapper;
    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YhCbkxxService yhCbkxxService;
    @Autowired
    private BmSjService bmSjService;
    @Autowired
    private BmYslxService bmYslxService;

    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public ResultRespone getYhXzbgLogPage(Page page, @ModelAttribute YhXzbgLog yhXzbgLog) {
        return ResultRespone.success(yhXzbgLogService.page(page, Wrappers.query(yhXzbgLog)));
    }

    @GetMapping("/{bh}")
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bh", value = "ID", required = true, dataType = "String")
    })
    public ResultRespone getById(@PathVariable("bh") String bh) {
        return ResultRespone.success(yhXzbgLogService.getById(bh));
    }

    @ApiOperation(value = "新增用户性质变更记录")
    @PostMapping(value = "/save", headers = "content-type=multipart/form-data")
    public ResultRespone save(@Valid YhXzbgLog yhxzbgLog,
                              @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList,
                              @RequestParam(value = "htfileList", required = false) List<MultipartFile> htfileList) {
        ResultRespone<Object> rest = new ResultRespone<>();
        yhxzbgLog.setBh(GuidGenerator.getGuid().substring(0, 8));
        if (StringUtil.isNotEmpty(yhxzbgLog.getYhbh())) {
            if (yhXzbgLogService.save(yhxzbgLog)) {
                String path = filePathBean.getHtfile();
                if (fileList.size() > 0) {
                    iFileInfoService.saveFileList(fileList, path, yhxzbgLog.getBh(), "yh_xzbg_log", "性质变更文件");
                }
                if (htfileList.size() > 0) {
                    iFileInfoService.saveFileList(htfileList, path, yhxzbgLog.getBh(), "yh_xzbg_log_ht", "性质变更合同文件");
                }
                rest.setCode(1);
                rest.setMessage("添加成功");
            } else {
                rest.setCode(-1);
                rest.setMessage("添加失败");
            }
        } else {
            rest.setCode(-1);
            rest.setMessage("添加失败，用户编号不能为空");
        }
        return rest;
    }

    @ApiOperation(value = "新增用户性质变更记录(工单)")
    @PostMapping(value = "/save_gd", headers = "content-type=multipart/form-data")
    public ResultRespone save_gd(@Valid YhXzbgLogInsert insert,
                                 @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList,
                                 @RequestParam(value = "htfileList", required = false) List<MultipartFile> htfileList) {
        ResultRespone<Object> rest = new ResultRespone<>();
        if (StringUtil.isEmpty(insert.getYhbh())) {
            throw new FeesException("用户编号不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(insert.getCbkid())) {
            insert.setCbkid(insert.getYhbh() + "1");
        }
        YhKhjbxx yhKhjbxx = yhKhjbxxService.getById(insert.getYhbh());
        if (StringUtil.isNull(yhKhjbxx)) {
            throw new FeesException("用户信息不存在", FeesErrorCode.BUSINESS_ERROR);
        }
        YhCbkxx yhCbkxx = yhCbkxxService.getById(insert.getCbkid());
        if (StringUtil.isNull(yhCbkxx)) {
            throw new FeesException("抄表卡信息不存在", FeesErrorCode.BUSINESS_ERROR);
        }
        YhXzbgLog yhxzbgLog = JSON.parseObject(JSON.toJSONString(insert), YhXzbgLog.class);
        yhxzbgLog.setBh(GuidGenerator.getGuid().substring(0, 8));
        yhxzbgLog.setYhxm(yhKhjbxx.getYhxm());
        yhxzbgLog.setYhdz(yhKhjbxx.getYhdz());
        yhxzbgLog.setLxdh(yhKhjbxx.getLxdh());
        yhxzbgLog.setSsgs(yhKhjbxx.getSsgs());
        yhxzbgLog.setSscbpq(yhKhjbxx.getSscbpq());
        yhxzbgLog.setSscbb(yhKhjbxx.getSscbb());
        yhxzbgLog.setGdzt("1");
        List<BmSj> bmSjList = bmSjService.list();
        List<BmYslx> bmYslxList = bmYslxService.list();
        String yslx = bmSjList.stream().filter(bmSj -> bmSj.getCode().equals(yhCbkxx.getSjbm())).findFirst().get().getYslx();
        yhxzbgLog.setOldYbdjbz(yhCbkxx.getYbdjbz());
        yhxzbgLog.setOldYslx(yslx);
        yhxzbgLog.setOldYslxmc(bmYslxList.stream().filter(bmYslx -> bmYslx.getCode().equals(yslx)).findFirst().get().getName());
        yhxzbgLog.setOldSjbm(yhCbkxx.getSjbm());
        BmSj bmSj = bmSjList.stream().filter(e -> e.getCode().equals(yhCbkxx.getSjbm())).findFirst().get();
        yhxzbgLog.setOldSjmc(bmSj.getName());
        yhxzbgLog.setOldSj(this.getSjstr(bmSj));
        if (StringUtil.isNotEmpty(yhCbkxx.getSjbm1())) {
            bmSj = bmSjList.stream().filter(e -> e.getCode().equals(yhCbkxx.getSjbm1())).findFirst().get();
            yhxzbgLog.setOldSjbm1(yhCbkxx.getSjbm1());
            yhxzbgLog.setOldSjmc1(bmSj.getName());
            yhxzbgLog.setOldSj(this.getSjstr(bmSj));
        }
        if (StringUtil.isNotEmpty(yhCbkxx.getSjbm2())) {
            bmSj = bmSjList.stream().filter(e -> e.getCode().equals(yhCbkxx.getSjbm2())).findFirst().get();
            yhxzbgLog.setOldSjbm2(yhCbkxx.getSjbm2());
            yhxzbgLog.setOldSjmc2(bmSj.getName());
            yhxzbgLog.setOldSj(this.getSjstr(bmSj));
        }
        bmSj = bmSjList.stream().filter(e -> e.getCode().equals(yhxzbgLog.getNewSjbm())).findFirst().get();
        yhxzbgLog.setNewSjmc(bmSj.getName());
        yhxzbgLog.setNewYslxmc(bmYslxList.stream().filter(bmYslx -> bmYslx.getCode().equals(yhxzbgLog.getNewYslx())).findFirst().get().getName());
        yhxzbgLog.setNewSj(this.getSjstr(bmSj));
        if (StringUtil.isNotNull(insert.getSlbl()) && insert.getSlbl().compareTo(BigDecimal.ZERO) > 0) {
            yhxzbgLog.setNewSlbl(insert.getSlbl());
        }
        if (StringUtil.isNotEmpty(yhxzbgLog.getNewSjbm1())) {
            bmSj = bmSjList.stream().filter(e -> e.getCode().equals(yhxzbgLog.getNewSjbm1())).findFirst().get();
            yhxzbgLog.setNewSjmc1(bmSj.getName());
            yhxzbgLog.setNewSj1(this.getSjstr(bmSj));
            yhxzbgLog.setNewSlbl1(insert.getSlbl1());
        }
        if (StringUtil.isNotEmpty(yhxzbgLog.getNewSjbm2())) {
            bmSj = bmSjList.stream().filter(e -> e.getCode().equals(yhxzbgLog.getNewSjbm2())).findFirst().get();
            yhxzbgLog.setNewSjmc2(bmSj.getName());
            yhxzbgLog.setNewSj2(this.getSjstr(bmSj));
            yhxzbgLog.setNewSlbl2(insert.getSlbl2());
        }
        yhxzbgLog.setCzrybm(String.valueOf(SecurityUtils.getUserId()));
        yhxzbgLog.setCzryxm(SecurityUtils.getUser().getRealName());
        yhxzbgLog.setBgfx(getBgfx(
                bmSjList.stream().filter(e -> e.getCode().equals(yhCbkxx.getSjbm())).findFirst().get(),
                bmSjList.stream().filter(e -> e.getCode().equals(yhxzbgLog.getNewSjbm())).findFirst().get()));
        yhxzbgLog.setBgnr(String.format("%s变更为%s", yhxzbgLog.getOldYslxmc(), yhxzbgLog.getNewYslxmc()));
        yhxzbgLog.setBgsj(new Date());
        if (yhXzbgLogService.save(yhxzbgLog)) {
            if (htfileList.size() != 0) {
                String path = filePathBean.getHtfile();
                if (fileList.size() > 0) {
                    iFileInfoService.saveFileList(fileList, path, yhxzbgLog.getBh(), "yh_xzbg_log", "性质变更文件");
                }
                if (htfileList.size() > 0) {
                    iFileInfoService.saveFileList(htfileList, path, yhxzbgLog.getBh(), "yh_xzbg_log_ht", "性质变更合同文件");
                }
            }
            rest.setCode(1);
            rest.setMessage("添加成功");
            rest.setResult(yhxzbgLog.getBh());
        } else {
            rest.setCode(-1);
            rest.setMessage("添加失败");
        }

        return rest;
    }


    @ApiOperation(value = "修改用户性质变更记录")
    @PutMapping
    public ResultRespone updateById(@RequestBody YhXzbgLog yhxzbgLog) {
        return ResultRespone.success(yhXzbgLogService.updateById(yhxzbgLog));
    }


    @ApiOperation(value = "通过ID删除用户性质变更记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bh", value = "ID", required = true, dataType = "String")
    })
    @DeleteMapping("/{bh}")
    public ResultRespone removeById(@PathVariable String bh) {
        return ResultRespone.success(yhXzbgLogService.removeById(bh));
    }


    @ApiOperation(value = "通过ID批量删除用户性质变更记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds")
    public ResultRespone removeByIds(String ids) {
        return ResultRespone.success(yhXzbgLogService.removeByIds(Arrays.asList(ids.split(","))));
    }

    @GetMapping("/getYhsj/{yhbh}")
    @ApiOperation(value = "查看用户水价信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yhbh", value = "用户编号", required = true, dataType = "String")
    })
    public ResultRespone<YhXzbhSjVo> getYhSjById(@PathVariable("yhbh") String yhbh) {
        return ResultRespone.success(yhXzbgLogMapper.selectYhSj(yhbh));
    }

    @GetMapping("/getYhxzbgLogtj")
    @ApiOperation(value = "查询用户性质变更统计")
    public ResultRespone<PageResult<YhXzbgLogSelect>> getYhxzbgLogtj(@ModelAttribute PageDto pageDto, @ModelAttribute YhXzbgLogFilter filter) {
        return ResultRespone.success(yhXzbgLogService.getYhxzbgLogtj(pageDto, filter));
    }

    @GetMapping("/exporYhxzbgLogtj")
    @ApiOperation(value = "导出用户性质变更统计")
    public void exporYhxzbgLogtj(HttpServletResponse response, @ModelAttribute YhXzbgLogFilter filter) throws IOException {
        List<YhXzbgLogSelect> list = yhXzbgLogService.yhxzbgLogtjlist(filter);
        if (!list.isEmpty()) {
            ExcleFileUtil.exportExcel(response, list, YhXzbgLogSelect.class, "用户性质变更统计.xlsx", filter.getExportFields());
        }
    }


    private String getSjstr(BmSj bmSj) {
        String sjstr = String.format("单价：%s元/方", bmSj.getSj());
        if (bmSj.getJtbz().equals("1")) {
            sjstr = String.format("一阶：%s元/方；二阶：%s元/方；三阶：%s元/方", bmSj.getJt1Sj(), bmSj.getJt2Sj(), bmSj.getJt3Sj());
        }
        return sjstr;
    }

    private String getBgfx(BmSj oldbmSj, BmSj newbmSj) {
        BigDecimal oldSj = oldbmSj.getSj();
        BigDecimal newSj = newbmSj.getSj();
        if (oldbmSj.getJtbz().equals("1")) {
            oldSj = oldbmSj.getJt1Sj();
        }
        if (newbmSj.getJtbz().equals("1")) {
            newSj = newbmSj.getJt1Sj();
        }
        if (oldSj.compareTo(newSj) == 0) {
            return "0";
        }
        if (oldSj.compareTo(newSj) > 0) {
            return "2";
        }
        return "1";
    }
}
