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


import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
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.annotation.Query.handle.QueryGenerator;
import com.gci.boot.common.log.annotation.AddSysLog;
import com.gci.boot.common.util.MinioUtils;
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.enums.FileExtension;
import com.gci.boot.modules.projects.entity.TbContract;
import com.gci.boot.modules.projects.entity.TbContractVehicle;
import com.gci.boot.modules.projects.service.ITbContractService;
import com.gci.boot.modules.projects.service.ITbContractVehicleService;
import com.gci.boot.modules.projects.service.ITbVehicleCheckService;
import com.gci.boot.modules.system.vo.LoginUser;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 合同档案 前端控制器
 * </p>
 *
 * @author xushuhan
 * @since 2023-09-01
 */
@Slf4j
@RestController
@RequestMapping("/projects/contract")
public class TbContractController {

	@Autowired
	private ITbContractService tbContractService;
	@Autowired
    private MinioUtils minioUtils;
	@Autowired
	private ITbContractVehicleService contractVehicleService;
	
	@AddSysLog(value = "合同档案-列表查询")
	@GetMapping("/list")
	public Result<?> list(TbContract item) {
		LambdaQueryWrapper<TbContract> queryWrapper = QueryGenerator.initQueryWrapper(TbContract.class, item);
		queryWrapper.orderByDesc(TbContract::getCreateTime);
		List<TbContract> list = tbContractService.list(queryWrapper);
		for(TbContract pro:list) {
			//获取车辆明细
			tbContractService.initVehicleCheckDetail(pro);
			//补充车型明细
			List<TbContractVehicle> vehicleDetails = contractVehicleService.getByContractId(pro.getId());
			pro.setVehicleDetails(vehicleDetails);
			//租赁合同
			if("1".equals(pro.getContractType())&&vehicleDetails!=null) {
				int vehicleCount = 0;
				for (TbContractVehicle vd : vehicleDetails) {
					vehicleCount += vd.getQuantity();
				}
				pro.setVehicleCount(vehicleCount);
			}
			if("1".equals(pro.getContractType())&&pro.getVehicleList()!=null) {
				pro.setVehicleCount(pro.getVehicleList().size());
			}
		}
		return Result.ok(list);
	}

	@AddSysLog(value = "合同档案-分页查询")
	@GetMapping("/page")
	public Result<?> page(TbContract item,@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
						  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

		LambdaQueryWrapper<TbContract> queryWrapper = QueryGenerator.initQueryWrapper(TbContract.class, item);
		queryWrapper.orderByDesc(TbContract::getCreateTime);
		Page<TbContract> page = new Page<TbContract>(pageNo, pageSize);
		IPage<TbContract> pageList = tbContractService.page(page,queryWrapper);
		for(TbContract pro:pageList.getRecords()) {
			//获取车辆明细
			tbContractService.initVehicleCheckDetail(pro);
			//补充车型明细
			List<TbContractVehicle> vehicleDetails = contractVehicleService.getByContractId(pro.getId());
			pro.setVehicleDetails(vehicleDetails);
			//租赁合同
			if("1".equals(pro.getContractType())&&vehicleDetails!=null) {
				int vehicleCount = 0;
				for (TbContractVehicle vd : vehicleDetails) {
					vehicleCount += vd.getQuantity();
				}
				pro.setVehicleCount(vehicleCount);
			}
			//初始化车辆价格、保险
			tbContractService.initItem(pro);
		}
		return Result.ok(pageList);
	}

	@AddSysLog(value = "合同档案-新增")
	@PostMapping("/add")
	public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbContract item){
		tbContractService.saveItem(item);
		return Result.ok();
	}

	@AddSysLog(value = "合同档案-编辑")
	@PutMapping("/edit")
	public Result<?> edit(@RequestBody @Validated(UpdateValidated.class) TbContract item){
		tbContractService.updateItem(item);
		return Result.ok();
	}

	@AddSysLog(value = "合同档案-删除")
	@DeleteMapping("/delete")
	public Result<?> delete(TbContract item){
		tbContractService.removeById(item.getId());
		//同步删除车辆细项
		LambdaQueryWrapper<TbContractVehicle> delWrapper = new LambdaQueryWrapper<>();
		delWrapper.eq(TbContractVehicle::getContractId,item.getId());
		contractVehicleService.remove(delWrapper);
		return Result.ok();
	}

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result<?> upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        if (ObjectUtil.isEmpty(file)) {
            return Result.error("请正确上传文件！");
        }
        return Result.ok(minioUtils.uploadFileValid(file, FileExtension.getCommonFileTypes()));
    }

    /**
     * 根据合同类型获取签约方列表
     * @param contractType
     * @return
     */
	@GetMapping("/getSigningList")
	public Result<?> getSigningList(String contractType) {
		String sysOrgCode = null;
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(sysUser!=null) {
			sysOrgCode = sysUser.getOrgCode();
		}
		List<TbContract> list = tbContractService.getSigningList(contractType, sysOrgCode);
		return Result.ok(list);
	}

	/**
	 *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
	 * @param response
	 */
	@AddSysLog(value = "合同档案-导出")
	@GetMapping("/simple/export")
	public Result<?> export(TbContract item,HttpServletResponse response){
		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);

			Result<?> result = list(item);
			List<TbContract> list = (List<TbContract>)result.getResult();
			EasyExcel.write(output, TbContract.class).sheet("sheet1").doWrite(list);

		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return Result.error("导出错误！");
		}
		return Result.ok();
	}

	@AddSysLog(value = "合同档案-分页导出")
	@GetMapping("/multi/export")
	public Result<?> multiExport(TbContract item,HttpServletResponse response){
		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);

			int pages = 1;
			try (ExcelWriter excelWriter = EasyExcel.write(output, TbContract.class).build()) {
				WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
				for (int i = 0; i < pages; i++) {
					Result<?> result = page(item,i+1, 10);
					IPage<TbContract> page = (IPage<TbContract>)result.getResult();
					List<TbContract> data = page.getRecords();
					int temp = (int)page.getPages();
					if(pages<temp) {
						pages = temp;
					}
					excelWriter.write(data, writeSheet);
				}
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return Result.error("导出错误！");
		}
		return Result.ok();
	}
	
}
