package com.tofly.feesapi.yhgl.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.feesapi.common.Excel.ExcleFileUtil;
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.common.util.ToolsUtils;
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.YhGhLog;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.entity.dto.YhywLogFilter;
import com.tofly.feesapi.yhgl.entity.vo.YhGhLogSelect;
import com.tofly.feesapi.yhgl.entity.vo.YhkhjbxxPhoto;
import com.tofly.feesapi.yhgl.mapper.YhGhLogMapper;
import com.tofly.feesapi.yhgl.service.YhGhLogService;
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 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.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/yhgl/yhghlog")
@Api(tags = "用户管理-用户过户日志接口")
public class YhGhLogController {

    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YhGhLogService yhGhLogService;
    @Autowired
    private YhGhLogMapper yhGhLogMapper;
    @Autowired
    private YyQfmxMapper yyQfmxMapper;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IFileInfoService iFileInfoService;
    @Autowired
    private FilePathBean filePathBean;

    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    @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 getDaGhLogPage(Page page, @ModelAttribute YhywLogFilter filter) {
        PageSortHelper.setPageSort(YhGhLog.class, page);
        IPage<YhGhLogSelect> daGhLogIPage = yhGhLogMapper.selectDaCustomerGhPage(page, filter);

        List<YhGhLogSelect> yhghList = daGhLogIPage.getRecords();
        if (CollUtil.isEmpty(yhghList)) {
            return ResultRespone.success(daGhLogIPage);
        }

        for (YhGhLogSelect yhgh : yhghList) {

            Company company = companyService.get(Long.valueOf(yhgh.getSsgs()));
            if (company != null) {
                yhgh.setSsgsname(company.getCompanyName());
            }

            List<File> files = iFileInfoService.getFileList(new LambdaQueryWrapper<File>().eq(File::getTableBh, yhgh.getBh()));
            if (CollUtil.isNotEmpty(files)) {
                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()]);
                yhgh.setFiles(photoArray);
            }

            String oldJson = yhgh.getOldJson();
            String newJson = yhgh.getNewJson();
            if (StrUtil.isNotEmpty(oldJson) && StrUtil.isNotEmpty(newJson)) {
                YhKhjbxx yhKhjbxx1 = JSONUtil.toBean(oldJson, YhKhjbxx.class);
                YhKhjbxx yhKhjbxx2 = JSONUtil.toBean(newJson, YhKhjbxx.class);
                yhgh.setDifferentFields(ToolsUtils.compareObjects(yhKhjbxx1, yhKhjbxx2, false));
            }
        }

        return ResultRespone.success(daGhLogIPage);
    }

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

    @ApiOperation(value = "新增用户过户日志")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yzqf", value = "是否验证欠费（1：需验证；0：不验证）", required = false, dataType = "String")
    })
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone save(@ModelAttribute YhGhLog yhGhLog, @RequestParam(required = false) String yzqf,
                              @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList,
                              @RequestParam(value = "htfileList", required = false) List<MultipartFile> htfileList) {
        String yhbh = yhGhLog.getYhbh();
        if (StrUtil.isEmpty(yhbh)) {
            return ResultRespone.failed(false, "操作失败,用户编号不能为空");
        }

        if (yzqf != null && yzqf.equals("1")) {
            //判断用户是否存在欠费
            int count = yyQfmxMapper.selectExistQf(yhbh);
            if (count > 0) {
                return ResultRespone.failed(false, "操作失败,用户存在欠费:" + count + "笔");
            }
        }

        YhKhjbxx yhInfo = yhKhjbxxService.getById(yhbh);
        yhGhLog.setBh(GuidGenerator.getGuid().substring(0, 8));
        yhGhLog.setGhsj(new Date());
        yhGhLog.setOldFpNsrsbh(yhInfo.getFpNsrsbh());
        yhGhLog.setOldFpDz(yhInfo.getFpDz());
        yhGhLog.setOldFpBz(yhInfo.getFpBz());
        yhGhLog.setOldFpBankcode(yhInfo.getFpBankcode());
        yhGhLog.setOldFpLxdh(yhInfo.getFpLxdh());
        yhGhLog.setOldFpBankname(yhInfo.getFpBankname());
        yhGhLog.setOldJson(JSONUtil.toJsonStr(yhInfo));

        // 同步用户档案状态
        YhKhjbxx yhKhjbxx = szkhxx(yhGhLog, yhbh);
        yhKhjbxxService.updateById(yhKhjbxx);

        YhKhjbxx newKhxx = yhKhjbxxService.getById(yhbh);
        yhGhLog.setNewJson(JSONUtil.toJsonStr(newKhxx));
        yhGhLogService.save(yhGhLog);

        String path = filePathBean.getHtfile();
        if (fileList.size() > 0) {
            iFileInfoService.saveFileList(fileList, path, yhGhLog.getBh(), "yh_gh_log", "过户文件");
        }

        if (htfileList.size() > 0) {
            iFileInfoService.saveFileList(htfileList, path, yhGhLog.getBh(), "yh_gh_log_ht", "过户合同文件");
        }

        return ResultRespone.success(true, "操作成功");
    }

    @ApiOperation(value = "修改用户过户日志")
    @PutMapping
    public ResultRespone updateById(@RequestBody YhGhLog yhGhLog) {
        return ResultRespone.success(yhGhLogService.updateById(yhGhLog));
    }

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

    @GetMapping("/export")
    @ApiOperation(value = "export导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ssgs", value = "公司", dataType = "String"),
            @ApiImplicitParam(name = "sscbpq", value = "片区", dataType = "String"),
            @ApiImplicitParam(name = "sscbb", value = "抄表本", dataType = "String"),
            @ApiImplicitParam(name = "ksrq", value = "开始时间", dataType = "String"),
            @ApiImplicitParam(name = "jsrq", value = "结束时间", dataType = "String"),
            @ApiImplicitParam(name = "searchText", value = "模糊查询(编号、姓名、电话、地址)", dataType = "String"),
            @ApiImplicitParam(name = "exportFields", value = "Excel导出字段", dataType = "String", example = "yhbh,yhxm")
    })
    public void export(HttpServletResponse response, @ModelAttribute YhywLogFilter filter) throws IOException {
        List<YhGhLogSelect> list = yhGhLogMapper.selectDaCustomerGhPage(filter);
        for (YhGhLogSelect yhgh : list) {
            if (yhgh.getSsgs() != null) {
                Company company = companyService.get(Long.valueOf(yhgh.getSsgs()));
                if (company != null) {
                    yhgh.setSsgsname(company.getCompanyName());
                }
            }
        }
        ExcleFileUtil.exportExcel(response, list, YhGhLogSelect.class, "用户过户记录.xlsx", filter.getExportFields());
    }

    private YhKhjbxx szkhxx(YhGhLog yhGhLog, String yhbh) {
        YhKhjbxx yhKhjbxx = new YhKhjbxx();
        yhKhjbxx.setYhbh(yhbh);//用户编号
        yhKhjbxx.setYhxm(yhGhLog.getNewYhxm());//姓名
        yhKhjbxx.setLxdh(yhGhLog.getNewLxdh());//电话


        if (StringUtils.isNotBlank(yhGhLog.getBz())) {
            yhKhjbxx.setBz(yhGhLog.getBz());//备注
        } else {
            yhKhjbxx.setBz("");
        }

        if (StringUtils.isNotBlank(yhGhLog.getNewYhdz())) {
            yhKhjbxx.setYhdz(yhGhLog.getNewYhdz());//地址
        } else {
            yhKhjbxx.setYhdz("");
        }
        if (StringUtils.isNotBlank(yhGhLog.getNewZjlb())) {
            yhKhjbxx.setZjlb(yhGhLog.getNewZjlb());//证件类型
        }
        else {
            yhKhjbxx.setZjlb("");
        }
        if (StringUtils.isNotBlank(yhbh)) {
            yhKhjbxx.setZjhm(yhGhLog.getNewZjhm());//证件号码
        }
        else {
            yhKhjbxx.setZjhm("");
        }
        // 发票信息
        if (StringUtils.isNotBlank(yhGhLog.getNewFplx())) {
            yhKhjbxx.setFplx(yhGhLog.getNewFplx()); //发票类型
        }
        else {
            yhKhjbxx.setFplx("");
        }
        if (StringUtils.isNotBlank(yhGhLog.getNewFpName())) {
            yhKhjbxx.setFpName(yhGhLog.getNewFpName());//购方名称
        }
        else {
            yhKhjbxx.setFpName("");
        }
        if (StringUtils.isNotBlank(yhGhLog.getNewFpNsrsbh())) {
            yhKhjbxx.setFpNsrsbh(yhGhLog.getNewFpNsrsbh());
        }
        else {
            yhKhjbxx.setFpNsrsbh("");
        }
        if (StringUtils.isNotBlank(yhGhLog.getNewFpDz())) {
            yhKhjbxx.setFpDz(yhGhLog.getNewFpDz());
        }
        else {
            yhKhjbxx.setFpDz("");
        }
        if (StringUtils.isNotBlank(yhGhLog.getNewFpLxdh())) {
            yhKhjbxx.setFpLxdh(yhGhLog.getNewFpLxdh());
        }
        else {
            yhKhjbxx.setFpLxdh("");
        }
        if (StringUtils.isNotBlank(yhGhLog.getNewFpBankname())) {
            yhKhjbxx.setFpBankname(yhGhLog.getNewFpBankname());
        }
        else {
            yhKhjbxx.setFpBankname("");
        }
        if (StringUtils.isNotBlank(yhGhLog.getNewFpBankcode())) {
            yhKhjbxx.setFpBankcode(yhGhLog.getNewFpBankcode());
        }
        else {
            yhKhjbxx.setFpBankcode("");
        }
        if (StringUtils.isNotBlank(yhGhLog.getNewFpBz())) {
            yhKhjbxx.setFpBz(yhGhLog.getNewFpBz());
        }
        else {
            yhKhjbxx.setFpBz("");
        }
        return yhKhjbxx;
    }

}
