package com.gci.boot.modules.basedata.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
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.gci.boot.common.log.annotation.AddSysLog;
import com.gci.boot.common.validated.SaveValidated;
import com.gci.boot.common.validated.UpdateValidated;
import com.gci.boot.common.vo.Result;
import com.gci.boot.modules.basedata.entity.TbInsuranceCompanyArchives;
import com.gci.boot.modules.basedata.service.ITbInsuranceCompanyArchivesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

@Api(tags="保险公司档案表")
@RestController
@RequestMapping("/base/insuranceCompany")
@Slf4j
public class TbInsuranceCompanyArchivesController {
    @Autowired
    private ITbInsuranceCompanyArchivesService tbInsuranceCompanyArchivesService;

    /**
     * 分页列表查询
     *
     * @param archives
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AddSysLog(value = "保险公司-分页列表查询")
    @ApiOperation(value="保险公司档案表-分页列表查询", notes="保险公司档案表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(TbInsuranceCompanyArchives archives,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req ) {
        Page<TbInsuranceCompanyArchives> page = new Page<TbInsuranceCompanyArchives>(pageNo, pageSize);
        LambdaQueryWrapper<TbInsuranceCompanyArchives> queryWrapper = new LambdaQueryWrapper<TbInsuranceCompanyArchives>()
                .like(StrUtil.isNotBlank(archives.getName()), TbInsuranceCompanyArchives::getName,archives.getName())
                .like(StrUtil.isNotBlank(archives.getShortened()), TbInsuranceCompanyArchives::getShortened,archives.getShortened())
                .like(StrUtil.isNotBlank(archives.getContact()), TbInsuranceCompanyArchives::getContact,archives.getContact())
                .like(StrUtil.isNotBlank(archives.getPhone()), TbInsuranceCompanyArchives::getPhone,archives.getPhone())
                .eq(archives.getCancelFlag()!=null, TbInsuranceCompanyArchives::getCancelFlag, archives.getCancelFlag())
                .orderByDesc(TbInsuranceCompanyArchives::getCreateTime);
        IPage<TbInsuranceCompanyArchives> pageList = tbInsuranceCompanyArchivesService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     *   添加
     */
    @AddSysLog(value = "保险公司-添加")
    @ApiOperation(value="保险公司档案表-添加", notes="保险公司档案表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody @Validated(SaveValidated.class)TbInsuranceCompanyArchives archives) {
        archives.setType("2");
        boolean check = tbInsuranceCompanyArchivesService.check(archives);
        if (!check) {
            return Result.error(101,"全称、简称信息不能重复！");
        }
        tbInsuranceCompanyArchivesService.save(archives);
        return Result.ok("添加成功！");
    }

    /**
     *   编辑
     */
    @AddSysLog(value = "保险公司-编辑")
    @ApiOperation(value="保险公司档案表-编辑", notes="保险公司档案表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody  @Validated(UpdateValidated.class) TbInsuranceCompanyArchives archives) {
        archives.setType("2");
        boolean check = tbInsuranceCompanyArchivesService.check(archives);
        if (!check) {
            return Result.error(101,"全称、简称信息不能重复！");
        }
        TbInsuranceCompanyArchives one = tbInsuranceCompanyArchivesService.getById(archives.getId());
        if(Objects.isNull(one)){
            return Result.error(101,"该数据不存在，请刷新！");
        }
        if(one.getCancelFlag() == 1){
            return Result.error(101,"该数据已作废，不可编辑！");
        }
        tbInsuranceCompanyArchivesService.updateById(archives);
        return Result.ok("编辑成功！");
    }

    /**
     *   根据id作废（删除）
     */
    @AddSysLog(value = "保险公司-根据id作废")
    @ApiOperation(value="保险公司档案表-根据id作废（删除）", notes="保险公司档案表-根据id作废（删除）")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        TbInsuranceCompanyArchives one = tbInsuranceCompanyArchivesService.getById(id);
        if(Objects.isNull(one)){
            return Result.error(101,"该数据不存在，请刷新！");
        }
        if(one.getCancelFlag() == 1){
            return Result.error(101,"该数据已作废，不可再次作废！");
        }
        one.setCancelFlag(1);
        tbInsuranceCompanyArchivesService.updateById(one);
        return Result.ok("作废成功！");
    }

    /**
     *   根据id恢复作废数据
     */
    @AddSysLog(value = "保险公司-根据id恢复作废数据")
    @ApiOperation(value="保险公司档案表-根据id恢复作废数据", notes="保险公司档案表-根据id恢复作废数据")
    @GetMapping(value = "/unDelete")
    public Result<?> undelete(@RequestParam(name="id",required=true) String id) {
        TbInsuranceCompanyArchives one = tbInsuranceCompanyArchivesService.getById(id);
        if(Objects.isNull(one)){
            return Result.error(101,"该数据不存在，请刷新！");
        }
        if(one.getCancelFlag() == 0){
            return Result.error(101,"该数据状态正常，无需恢复！");
        }
        one.setCancelFlag(0);
        tbInsuranceCompanyArchivesService.updateById(one);
        return Result.ok("恢复成功！");
    }

    /**
     *   根据id删除（物理删除）
     */
    @AddSysLog(value = "保险公司-根据id删除")
    @ApiOperation(value="保险公司档案表-根据id删除（物理删除）", notes="保险公司档案表-根据id删除（物理删除）")
    @DeleteMapping(value = "/realDelete")
    public Result<?> realDelete(@RequestParam(name="id",required=true) String id) {
        TbInsuranceCompanyArchives one = tbInsuranceCompanyArchivesService.getById(id);
        if(Objects.isNull(one)){
            return Result.error(101,"该数据不存在，请刷新！");
        }
        tbInsuranceCompanyArchivesService.removeById(one);
        return Result.ok("删除成功！");
    }

    /**
     *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
     * @param response
     * @param archives
     */
    @AddSysLog(value = "保险公司-导出")
    @GetMapping("/simple/export")
    public Result<?> export(HttpServletResponse response, TbInsuranceCompanyArchives archives){
        try (OutputStream output = response.getOutputStream()){
            String fileName = "保险公司档案表.xlsx";
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
            LambdaQueryWrapper<TbInsuranceCompanyArchives> queryWrapper = new LambdaQueryWrapper<TbInsuranceCompanyArchives>()
                    .like(StrUtil.isNotBlank(archives.getName()), TbInsuranceCompanyArchives::getName,archives.getName())
                    .like(StrUtil.isNotBlank(archives.getShortened()), TbInsuranceCompanyArchives::getShortened,archives.getShortened())
                    .like(StrUtil.isNotBlank(archives.getContact()), TbInsuranceCompanyArchives::getContact,archives.getContact())
                    .like(StrUtil.isNotBlank(archives.getPhone()), TbInsuranceCompanyArchives::getPhone,archives.getPhone())
                    .orderByDesc(TbInsuranceCompanyArchives::getCreateTime);
            List<TbInsuranceCompanyArchives> list = tbInsuranceCompanyArchivesService.list(queryWrapper);
            EasyExcel.write(output, TbInsuranceCompanyArchives.class).sheet("保险公司档案表").doWrite(list);
        } catch (IOException e) {
            return Result.error("导出错误！");
        }
        return Result.ok();
    }
}
