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.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.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.YhKhjbxx;
import com.tofly.feesapi.yhgl.entity.YhhLog;
import com.tofly.feesapi.yhgl.entity.dto.YhywLogFilter;
import com.tofly.feesapi.yhgl.entity.vo.YhhLogSelect;
import com.tofly.feesapi.yhgl.entity.vo.YhkhjbxxPhoto;
import com.tofly.feesapi.yhgl.mapper.YhKhjbxxMapper;
import com.tofly.feesapi.yhgl.mapper.YhhLogMapper;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import com.tofly.feesapi.yhgl.service.YhhLogService;
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/yhhlog")
@Api(tags = "用户管理-用户销户记录接口")
public class YhhLogController {

    @Autowired
    private YhhLogService yhhLogService;
    @Autowired
    private YhhLogMapper yhhLogMapper;
    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YyQfmxMapper yyQfmxMapper;
    @Autowired
    private YhCbkxxService yhCbkxxService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IFileInfoService iFileInfoService;
    @Autowired
    private FilePathBean filePathBean;

    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public ResultRespone getDahLogPage(Page page,@ModelAttribute YhywLogFilter filter) {
        PageSortHelper.setPageSort(YhhLog.class, page);
        IPage<YhhLogSelect> dahLogIPage = yhhLogMapper.SelectDaxhPage(page, filter);
        List<YhhLogSelect> yhxhList = dahLogIPage.getRecords();
        for (YhhLogSelect yhxh : yhxhList) {
            if (yhxh.getSsgs() != null) {
                Company company = companyService.get(Long.valueOf(yhxh.getSsgs()));
                if (company != null) {
                    yhxh.setSsgsname(company.getCompanyName());
                }
            }

            List<File> files=iFileInfoService.getFileList(new LambdaQueryWrapper<File>().eq(File::getTableBh,yhxh.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[0]);
                yhxh.setFiles(photoArray);
            }

        }
        return ResultRespone.success(dahLogIPage);
    }


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

    /**
     * 新增用户销户记录
     */
    @ApiOperation(value = "新增用户销户记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yzqf", value = "是否验证欠费（1：需验证；0：不验证）", required = false, dataType = "String")
    })
    @PostMapping(headers = "content-type=multipart/form-data")
    public ResultRespone save(@Valid YhhLog yhhLog, @RequestParam(required = false) String yzqf,
                              @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList) {
        ResultRespone<Object> rest = new ResultRespone<>();
        String yhbh = yhhLog.getYhbh();

        yhhLog.setBh(GuidGenerator.getGuid().substring(0, 8));
        yhhLog.setSfyzqf(yzqf);
        if (StringUtil.isNotEmpty(yhbh)) {
            if (yzqf.equals("1")) {
                //判断用户是否存在欠费
                int count = yyQfmxMapper.selectExistQf(yhbh);
                if (count > 0) {
                    rest.setCode(-1);
                    rest.setMessage("操作失败,用户存在欠费:" + count + "笔");
                    return rest;
                }
            }
            if (yhhLogService.save(yhhLog)) {
                String path = filePathBean.getHtfile();
                if (fileList.size() > 0) {
                    iFileInfoService.saveFileList(fileList, path, yhhLog.getBh(), "yh_xh_log", "销户文件");
                }

                // 修改用户状态及水表停用状态
                YhKhjbxx yhKhjbxx = yhKhjbxxService.getById(yhbh);
                if (ObjectUtil.isNotNull(yhKhjbxx)) {
                    yhKhjbxx.setYhzt(YhztEnum.销户用户);
                    yhKhjbxxService.updateById(yhKhjbxx);
                }

                LambdaQueryWrapper<YhCbkxx> queryWrapper = Wrappers.<YhCbkxx>lambdaQuery().eq(YhCbkxx::getYhbh, yhbh);
                YhCbkxx yhCbkxx = yhCbkxxService.getOne(queryWrapper);
                if (ObjectUtil.isNotNull(yhCbkxx)) {
                    yhCbkxx.setJfzt(String.valueOf(JfztEnum.停用.getValue()));
                    yhCbkxxService.updateById(yhCbkxx);
                }

                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")
    public ResultRespone save_gd(@Valid YhhLog yhhLog, @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<>();
        yhhLog.setSfyzqf(yzqf);
        yhhLog.setGdzt("1");
        yhhLog.setBh(GuidGenerator.getGuid().substring(0, 8));
        if (StringUtil.isNotEmpty(yhhLog.getYhbh())) {
            if (yzqf.equals("1")) {
                //判断用户是否存在欠费
                int count = yyQfmxMapper.selectExistQf(yhhLog.getYhbh());
                if (count > 0) {
                    rest.setCode(-1);
                    rest.setMessage("操作失败,用户存在欠费:" + count + "笔");
                    return rest;
                }
            }
            if (yhhLogService.save(yhhLog)) {
                String path = filePathBean.getHtfile();
                if (fileList.size() > 0) {
                    iFileInfoService.saveFileList(fileList, path, yhhLog.getBh(), "yh_xh_log", "销户文件");
                }
                if (htfileList.size() > 0) {
                    iFileInfoService.saveFileList(htfileList, path, yhhLog.getBh(), "yh_xh_log_ht", "销户合同文件");
                }
                rest.setCode(1);
                rest.setMessage("添加成功");
                rest.setResult(yhhLog.getBh());
            } else {
                rest.setCode(-1);
                rest.setMessage("添加失败");
            }
        } else {
            rest.setCode(-1);
            rest.setMessage("添加失败，用户编号不能为空");
        }
        return rest;
    }

    @ApiOperation(value = "修改用户销户记录")
    @PutMapping
    public ResultRespone updateById(@RequestBody YhhLog yhhLog) {
        return ResultRespone.success(yhhLogService.updateById(yhhLog));
    }


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

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