package com.tofly.feesapi.yhgl.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.common.Excel.ExcleFileUtil;
import com.tofly.feesapi.common.constant.JfztEnum;
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.entity.File;
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.YhBtLog;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.entity.dto.YhywLogFilter;
import com.tofly.feesapi.yhgl.entity.vo.YhBtLogSelect;
import com.tofly.feesapi.yhgl.entity.vo.YhkhjbxxPhoto;
import com.tofly.feesapi.yhgl.mapper.YhBtLogMapper;
import com.tofly.feesapi.yhgl.service.YhBtLogService;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
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.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/yhgl/yhbtlog")
@Api(tags = "用户管理-用户报停记录接口")
public class YhBtLogController {
    @Autowired
    private YhBtLogService yhBtLogService;
    @Autowired
    private YhBtLogMapper yhBtLogMapper;
    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YhCbkxxService yhCbkxxService;
    @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 getDaBtLogPage(Page page, @ModelAttribute YhywLogFilter filter) {

        PageSortHelper.setPageSort(YhBtLog.class, page);
        // 执行分页查询
        IPage<YhBtLogSelect> yhdaPage = yhBtLogMapper.selectDaCustomerBtPage(page, filter);
        // 遍历查询结果进行赋值
        List<YhBtLogSelect> yhbtList = yhdaPage.getRecords();
        for (YhBtLogSelect yhbt : yhbtList) {
            if (yhbt.getHfysbz() != null && yhbt.getHfysbz().equals("0")) {
                yhbt.setHfysbz("未恢复");
            } else {
                yhbt.setHfysbz("已恢复");
            }
            if (yhbt.getSsgs() != null) {
                Company company = companyService.get(Long.valueOf(yhbt.getSsgs()));
                if (company != null) {
                    yhbt.setSsgsname(company.getCompanyName());
                }
            }

            List<File> files = iFileInfoService.getFileList(new LambdaQueryWrapper<File>().eq(File::getTableBh, yhbt.getBh()));
            if (!CollectionUtils.isEmpty(files) && files.size() > 0) {
                List<YhkhjbxxPhoto> photos = files.stream().map(dto -> {
                    YhkhjbxxPhoto photo = new YhkhjbxxPhoto();
                    photo.fileName = dto.getFileOldFn();
                    photo.fileUrl = dto.getFileNewFn();
                    return photo;
                }).collect(Collectors.toList());

                YhkhjbxxPhoto[] photoArray = photos.toArray(new YhkhjbxxPhoto[photos.size()]);
                yhbt.setFiles(photoArray);
            }

        }
        return ResultRespone.success(yhdaPage);
    }

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

    @ApiOperation(value = "新增用户报停记录")
    @PostMapping(headers = "content-type=multipart/form-data")
    public ResultRespone save(@Valid YhBtLog daBtLog,
                              @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList,
                              @RequestParam(value = "htfileList", required = false) List<MultipartFile> htfileList) {
        ResultRespone<Object> rest = new ResultRespone<>();

        String yhbh = daBtLog.getYhbh();
        String cbkid = daBtLog.getCbkid();

        if (StringUtil.isNotEmpty(yhbh)) {
            if (daBtLog != null && "1".equals(daBtLog.getSfyzqf())) {
                //判断用户是否存在欠费
                int count = yyQfmxMapper.selectExistQf(yhbh);
                if (count > 0) {
                    rest.setCode(-1);
                    rest.setMessage("操作失败,用户存在欠费:" + count + "笔");
                    return rest;
                }
            }
            daBtLog.setBh(GuidGenerator.getGuid().substring(0, 8));
            if (yhBtLogService.save(daBtLog)) {
                String path = filePathBean.getHtfile();
                if (fileList.size() > 0) {
                    iFileInfoService.saveFileList(fileList, path, daBtLog.getBh(), "yh_bt_log", "报停文件");
                }
                if (htfileList.size() > 0) {
                    iFileInfoService.saveFileList(htfileList, path, daBtLog.getBh(), "yh_bt_log_ht", "报停合同文件");
                }
                // 修改用户状态及水表停用状态
                YhKhjbxx yhKhjbxx = yhKhjbxxService.getById(yhbh);
                if (ObjectUtil.isNotNull(yhKhjbxx)) {
                    yhKhjbxx.setYhzt(YhztEnum.报停用户);
                    yhKhjbxxService.updateById(yhKhjbxx);
                }

                YhCbkxx yhCbkxx = yhCbkxxService.getById(cbkid);
                if (ObjectUtil.isNotNull(yhCbkxx)) {
                    yhCbkxx.setJfzt(String.valueOf(JfztEnum.停用.getValue()));
                    yhCbkxxService.updateById(yhCbkxx);
                }

                rest.setCode(1);
                rest.setMessage("添加成功");
                rest.setResult(daBtLog.getBh());
            } else {
                rest.setCode(-1);
                rest.setMessage("添加失败");
            }
        } else {
            rest.setCode(-1);
            rest.setMessage("添加失败，用户编号不能为空");
        }
        return rest;
    }


    @ApiOperation(value = "修改用户报停记录")
    @PutMapping
    public ResultRespone updateById(@RequestBody YhBtLog yhBtLog) {
        return ResultRespone.success(yhBtLogService.updateById(yhBtLog));
    }

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

    @GetMapping("/export")
    @ApiOperation(value = "export导出")
    public void export(HttpServletResponse response, @ModelAttribute YhywLogFilter filter) throws IOException {
        // 遍历查询结果进行赋值
        List<YhBtLogSelect> list = yhBtLogMapper.selectDaCustomerBtPage(filter);
        for (YhBtLogSelect yhbt : list) {
            if (yhbt.getSsgs() != null) {
                Company company = companyService.get(Long.valueOf(yhbt.getSsgs()));
                if (company != null) {
                    yhbt.setSsgsname(company.getCompanyName());
                }
            }
        }
        //导出excle
        ExcleFileUtil.exportExcel(response, list, YhBtLogSelect.class, "用户报停记录.xlsx", filter.getExportFields());
    }
}
