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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.entity.TbRepairShopArchives;
import com.gci.boot.modules.basedata.entity.TbVehicleSupplierArchives;
import com.gci.boot.modules.basedata.service.ITbInsuranceCompanyArchivesService;
import com.gci.boot.modules.basedata.service.ITbRepairShopArchivesService;
import com.gci.boot.modules.basedata.service.ITbVehicleSupplierArchivesService;
import com.gci.boot.modules.basedata.vo.SupplierPageVO;
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/vehicleSupplier")
@Slf4j
public class TbVehicleSupplierArchivesController {

    /*对于租赁公司，外部只有供应商和客户两种类型，因此供应商可以增加类型字段，
    如车辆/零配件/金融等；还需增加备注，方便填写品牌信息。就不用分维修厂、保险单位这样细分*/

    @Autowired
    private ITbVehicleSupplierArchivesService tbVehicleSupplierArchivesService;
    @Autowired
    private ITbInsuranceCompanyArchivesService tbInsuranceCompanyArchivesService;
    @Autowired
    private ITbRepairShopArchivesService tbRepairShopArchivesService;

    /**
     * 分页列表查询
     *
     */
    @AddSysLog(value = "供应商档案-分页列表查询")
    @ApiOperation(value="车辆供应商档案表对象-分页列表查询", notes="车辆供应商档案表对象-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(SupplierPageVO vo,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req ) {
        Page<SupplierPageVO> page = new Page<SupplierPageVO>(pageNo, pageSize);
//        LambdaQueryWrapper<TbVehicleSupplierArchives> queryWrapper = new LambdaQueryWrapper<TbVehicleSupplierArchives>()
//                .like(StrUtil.isNotBlank(archives.getName()), TbVehicleSupplierArchives::getName,archives.getName())
//                .like(StrUtil.isNotBlank(archives.getShortened()), TbVehicleSupplierArchives::getShortened,archives.getShortened())
//                .like(StrUtil.isNotBlank(archives.getContact()), TbVehicleSupplierArchives::getContact,archives.getContact())
//                .like(StrUtil.isNotBlank(archives.getPhone()), TbVehicleSupplierArchives::getPhone,archives.getPhone())
//                .orderByDesc(TbVehicleSupplierArchives::getCreateTime);
//        IPage<TbVehicleSupplierArchives> pageList = tbVehicleSupplierArchivesService.page(page, queryWrapper);

        IPage<SupplierPageVO> pageList = tbVehicleSupplierArchivesService.getSupplierPage(page, vo);
        return Result.ok(pageList);
    }

    /**
     *   添加
     */
    @AddSysLog(value = "供应商档案-添加")
    @ApiOperation(value="车辆供应商档案表对象-添加", notes="车辆供应商档案表对象-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbVehicleSupplierArchives archives) {
        //1、维修厂，2、保险公司，其它存供应商表
        if("1".equals(archives.getType())){
            TbRepairShopArchives repairShopArchives = new TbRepairShopArchives();
            BeanUtil.copyProperties(archives,repairShopArchives);
            tbRepairShopArchivesService.save(repairShopArchives);
        } else if("2".equals(archives.getType())){
            TbInsuranceCompanyArchives insuranceCompanyArchives = new TbInsuranceCompanyArchives();
            BeanUtil.copyProperties(archives,insuranceCompanyArchives);
            boolean check = tbInsuranceCompanyArchivesService.check(insuranceCompanyArchives);
            if (!check) {
                return Result.error(101,"全称、简称信息不能重复！");
            }
            tbInsuranceCompanyArchivesService.save(insuranceCompanyArchives);
        } else{
            boolean check = tbVehicleSupplierArchivesService.check(archives);
            if (!check) {
                return Result.error(101,"全称、简称信息不能重复！");
            }
            tbVehicleSupplierArchivesService.save(archives);
        }
        return Result.ok("添加成功！");
    }

    /**
     *   编辑
     */
    @AddSysLog(value = "供应商档案-编辑")
    @ApiOperation(value="车辆供应商档案表对象-编辑", notes="车辆供应商档案表对象-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody  @Validated(UpdateValidated.class) TbVehicleSupplierArchives archives) {
        //1、维修厂，2、保险公司，其它存供应商表
        if("1".equals(archives.getType())){
            TbRepairShopArchives repairShopArchives = new TbRepairShopArchives();
            BeanUtil.copyProperties(archives,repairShopArchives);
            tbRepairShopArchivesService.updateById(repairShopArchives);

        } else if("2".equals(archives.getType())){
            TbInsuranceCompanyArchives insuranceCompanyArchives = new TbInsuranceCompanyArchives();
            BeanUtil.copyProperties(archives,insuranceCompanyArchives);
            boolean check = tbInsuranceCompanyArchivesService.check(insuranceCompanyArchives);
            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(insuranceCompanyArchives);
        } else{
            boolean check = tbVehicleSupplierArchivesService.check(archives);
            if (!check) {
                return Result.error(101,"全称、简称信息不能重复！");
            }
            TbVehicleSupplierArchives one = tbVehicleSupplierArchivesService.getById(archives.getId());
            if(Objects.isNull(one)){
                return Result.error(101,"该数据不存在，请刷新！");
            }
            if(one.getCancelFlag() == 1){
                return Result.error(101,"该数据已作废，不可编辑！");
            }
            tbVehicleSupplierArchivesService.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,
                            @RequestParam(name="type",required=true) String type) {
        //1、维修厂，2、保险公司，其它存供应商表
        if("1".equals(type)){
            tbRepairShopArchivesService.update(new LambdaUpdateWrapper<TbRepairShopArchives>().eq(TbRepairShopArchives::getId,id).set(TbRepairShopArchives::getCancelFlag,1));
        }else if("2".equals(type)){
            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);
        }else{
            TbVehicleSupplierArchives one = tbVehicleSupplierArchivesService.getById(id);
            if(Objects.isNull(one)){
                return Result.error(101,"该数据不存在，请刷新！");
            }
            if(one.getCancelFlag() == 1){
                return Result.error(101,"该数据已作废，不可再次作废！");
            }
            one.setCancelFlag(1);
            tbVehicleSupplierArchivesService.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,
                              @RequestParam(name="type",required=true) String type) {
        //1、维修厂，2、保险公司，其它存供应商表
        if("1".equals(type)){
            tbRepairShopArchivesService.update(new LambdaUpdateWrapper<TbRepairShopArchives>().eq(TbRepairShopArchives::getId,id).set(TbRepairShopArchives::getCancelFlag,0));
        }else if("2".equals(type)){
            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);
        }else{
            TbVehicleSupplierArchives one = tbVehicleSupplierArchivesService.getById(id);
            if(Objects.isNull(one)){
                return Result.error(101,"该数据不存在，请刷新！");
            }
            if(one.getCancelFlag() == 0){
                return Result.error(101,"该数据状态正常，无需恢复！");
            }
            one.setCancelFlag(0);
            tbVehicleSupplierArchivesService.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) {
        TbVehicleSupplierArchives one = tbVehicleSupplierArchivesService.getById(id);
        if(Objects.isNull(one)){
            return Result.error(101,"该数据不存在，请刷新！");
        }
        tbVehicleSupplierArchivesService.removeById(one);
        return Result.ok("删除成功！");
    }

    /**
     *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
     */
    @AddSysLog(value = "供应商档案-导出")
    @GetMapping("/simple/export")
    public Result<?> export(HttpServletResponse response, SupplierPageVO vo){
        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<TbVehicleSupplierArchives> queryWrapper = new LambdaQueryWrapper<TbVehicleSupplierArchives>()
//                    .like(StrUtil.isNotBlank(archives.getName()), TbVehicleSupplierArchives::getName,archives.getName())
//                    .like(StrUtil.isNotBlank(archives.getShortened()), TbVehicleSupplierArchives::getShortened,archives.getShortened())
//                    .like(StrUtil.isNotBlank(archives.getContact()), TbVehicleSupplierArchives::getContact,archives.getContact())
//                    .like(StrUtil.isNotBlank(archives.getPhone()), TbVehicleSupplierArchives::getPhone,archives.getPhone())
//                    .orderByDesc(TbVehicleSupplierArchives::getCreateTime);
//            List<TbVehicleSupplierArchives> list = tbVehicleSupplierArchivesService.list(queryWrapper);
            Page<SupplierPageVO> page = new Page<SupplierPageVO>(1, -1);
            IPage<SupplierPageVO> pageList = tbVehicleSupplierArchivesService.getSupplierPage(page, vo);
            EasyExcel.write(output, SupplierPageVO.class).sheet("车辆供应商档案表").doWrite(pageList.getRecords());
        } catch (IOException e) {
            return Result.error("导出错误！");
        }
        return Result.ok();
    }
}
