package com.tofly.feesapi.yhgl.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.feesapi.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bjgl.service.YhCbkxxService;
import com.tofly.feesapi.cbgl.entity.YyCblr;
import com.tofly.feesapi.cbgl.service.YyCblrService;
import com.tofly.feesapi.common.Excel.ExcleFileUtil;
import com.tofly.feesapi.common.constant.YhztEnum;
import com.tofly.feesapi.common.core.ResultRespone;

import com.tofly.feesapi.common.dbhelper.PageSortHelper;
import com.tofly.feesapi.common.util.GuidGenerator;
import com.tofly.feesapi.config.FilePathBean;
import com.tofly.feesapi.file.service.IFileInfoService;
import com.tofly.feesapi.sfgl.mapper.YyQfmxMapper;
import com.tofly.feesapi.udb.entity.Company;
import com.tofly.feesapi.udb.service.ICompanyService;
import com.tofly.feesapi.yhgl.entity.YhHfysLog;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.entity.dto.YhywLogFilter;
import com.tofly.feesapi.yhgl.entity.vo.YhHfysLogSelect;
import com.tofly.feesapi.yhgl.mapper.YhHfysLogMapper;
import com.tofly.feesapi.yhgl.mapper.YhKhjbxxMapper;
import com.tofly.feesapi.yhgl.service.YhHfysLogService;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("api/yhgl/yhhfyslog")
@Api(tags = "用户管理-用户恢复用水日志接口")
public class YhHfysLogController {

    @Autowired
    private YhHfysLogService yhHfysLogService;
    @Autowired
    private YhHfysLogMapper yhHfysLogMapper;
    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YhCbkxxService yhCbkxxService;
    @Autowired
    private YyCblrService yyCblrService;
    @Autowired
    private YyQfmxMapper yyQfmxMapper;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IFileInfoService iFileInfoService;
    @Autowired
    private FilePathBean filePathBean;

    @GetMapping("/page")
    @ApiOperation(value = "page分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页显示数据条数", required = true, dataType = "int"),
            @ApiImplicitParam(name = "pages", value = "共几页,输出参数", dataType = "int"),
            @ApiImplicitParam(name = "maxLimit", value = "每页最大显示数据", dataType = "int"),
            @ApiImplicitParam(name = "orders[0].asc", value = "排序,bool类型", dataType = "String"),
            @ApiImplicitParam(name = "orders[0].column", value = "排序,字段名", dataType = "String")
    })
    public ResultRespone getDaHfysLogPage(Page page, @ModelAttribute YhywLogFilter filter) {
        PageSortHelper.setPageSort(YhHfysLog.class, page);
        // 执行分页查询
        IPage<YhHfysLogSelect> yhhfysPage = yhHfysLogMapper.selectDaCustomerBtPage(page, filter);
        List<YhHfysLogSelect> yhhfysList = yhhfysPage.getRecords();
        // 遍历查询结果进行赋值
        for (YhHfysLogSelect yhhfys : yhhfysList) {
            if (yhhfys.getSsgs() != null) {
                Company company = companyService.get(Long.valueOf(yhhfys.getSsgs()));
                if (company != null) {
                    yhhfys.setSsgsname(company.getCompanyName());
                }
            }
        }
        return ResultRespone.success(yhhfysPage);
    }

    @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(yhHfysLogService.getById(bh));
    }


    @ApiOperation(value = "新增用户恢复用水日志")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yzqf", value = "是否验证欠费（1：需验证；0：不验证）", required = false, dataType = "String")
    })
    @PostMapping
    @Transactional(rollbackFor = Exception.class) //声明式事务管理
    public ResultRespone save(@RequestBody YhHfysLog yhHfysLog, @RequestParam(required = false) String yzqf) {

        ResultRespone<Object> rest = new ResultRespone<>();
        if (StringUtils.isNotBlank(yhHfysLog.getYhbh())) {
            if (yzqf != null && yzqf.equals("1")){
                //判断用户是否存在欠费
                int count = yyQfmxMapper.selectExistQf(yhHfysLog.getYhbh());

                if (count > 0) {
                    rest.setCode(-1);
                    rest.setMessage("操作失败,用户存在欠费:" + count + "笔");
                    return rest;
                }
            }

            yhHfysLog.setBh(GuidGenerator.getGuid().substring(0, 8));//id
            yhHfysLog.setCzrq(new Date()); //操作时间
            if (yhHfysLogService.save(yhHfysLog)) {
                YhCbkxx yhCbkxx = new YhCbkxx();
                yhCbkxx.setCbkid(yhHfysLog.getCbkid());
                yhCbkxx.setJfzt("1");//1正常2停用

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

                YhKhjbxx yhKhjbxx = new YhKhjbxx();
                yhKhjbxx.setYhbh(yhHfysLog.getYhbh());//用户编号
                yhKhjbxx.setYhzt(YhztEnum.正式用户);//用户状态
                if (yhKhjbxxService.updateById(yhKhjbxx) && yhCbkxxService.updateById(yhCbkxx) && yyCblrService.updateById(yyCblr)) {
                    rest.setCode(1);
                    rest.setMessage("操作成功");
                } else {
                    rest.setCode(-1);
                    rest.setMessage("操作失败");
                }
            } else {
                rest.setCode(-1);
                rest.setMessage("操作失败");
            }
        } else {
            rest.setCode(-1);
            rest.setMessage("操作失败,用户编号不存在");
        }
        return rest;
    }

    @ApiOperation(value = "新增用户恢复用水日志（工单）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yzqf", value = "是否验证欠费（1：需验证；0：不验证）", required = false, dataType = "String")
    })
    @PostMapping(value = "/save_gd", headers = "content-type=multipart/form-data")
    @Transactional(rollbackFor = Exception.class) //声明式事务管理
    public ResultRespone save_gd(@Valid YhHfysLog yhHfysLog, @RequestParam(required = false) String yzqf,
                                 @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList,
                                 @RequestParam(value = "htfileList", required = false) List<MultipartFile> htfileList) {

        ResultRespone<Object> rest = new ResultRespone<>();
        if (StringUtils.isNotBlank(yhHfysLog.getYhbh())) {
            if (yzqf.equals("1")) {
                //判断用户是否存在欠费
                int count = yyQfmxMapper.selectExistQf(yhHfysLog.getYhbh());

                if (count > 0) {
                    rest.setCode(-1);
                    rest.setMessage("操作失败,用户存在欠费:" + count + "笔");
                    return rest;
                }
            }

            yhHfysLog.setBh(GuidGenerator.getGuid().substring(0, 8));//id
            yhHfysLog.setCzrq(new Date()); //操作时间
            yhHfysLog.setGdzt("1");
            if (yhHfysLogService.save(yhHfysLog)) {
                String path = filePathBean.getHtfile();
                if (fileList.size() > 0) {
                    iFileInfoService.saveFileList(fileList, path, yhHfysLog.getBh(), "yh_hfys_log", "恢复用水文件");
                }
                if (htfileList.size() > 0) {
                    iFileInfoService.saveFileList(htfileList, path, yhHfysLog.getBh(), "yh_hfys_log_ht", "恢复用水合同文件");
                }
                rest.setCode(1);
                rest.setResult(yhHfysLog.getBh());
                rest.setMessage("操作成功");
            } else {
                rest.setCode(-1);
                rest.setMessage("操作失败");
            }
        } else {
            rest.setCode(-1);
            rest.setMessage("操作失败,用户编号不存在");
        }
        return rest;
    }


    @ApiOperation(value = "修改用户恢复用水日志")
    @PutMapping
    public ResultRespone updateById(@RequestBody YhHfysLog yhHfysLog) {
        return ResultRespone.success(yhHfysLogService.updateById(yhHfysLog));
    }

    @ApiOperation(value = "通过ID删除用户恢复用水日志")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bh", value = "ID", required = true, dataType = "String")
    })
    @DeleteMapping("/{bh}")
    public ResultRespone removeById(@PathVariable String bh) {
        return ResultRespone.success(yhHfysLogService.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(yhHfysLogService.removeByIds(Arrays.asList(ids.split(","))));
    }

    @GetMapping("/export")
    @ApiOperation(value = "export导出")
    public void export(HttpServletResponse response, @ModelAttribute YhywLogFilter filter) throws IOException {
        // 遍历查询结果进行赋值
        List<YhHfysLogSelect> list = yhHfysLogMapper.selectDaCustomerBtPage(filter);
        for (YhHfysLogSelect yhhfys : list) {
            if (yhhfys.getSsgs() != null) {
                Company company = companyService.get(Long.valueOf(yhhfys.getSsgs()));
                if (company != null) {
                    yhhfys.setSsgsname(company.getCompanyName());
                }
            }
        }
        //导出Excel
        ExcleFileUtil.exportExcel(response, list, YhHfysLog.class, "恢复用水列表.xlsx", filter.getExportFields());
    }
}
