package org.springblade.business.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springblade.business.entity.DatumPoint;
import org.springblade.business.service.impl.DatumPointService;
import org.springblade.business.vo.DatumPointVo;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author yangyj
 * @Date 2022/6/7 16:11
 * @description TODO
 */
@RestController
@AllArgsConstructor
@RequestMapping("/dap")
@Api(tags = "基准点信息")
public class DatumPointController {
    private final DatumPointService service;


    @GetMapping("/list")
    public R<IPage<DatumPoint>>  list( String contractId, Query page, String type, String name){
        Map<String, Object> param = new HashMap<>(10);
        if(StringUtil.isNotBlank(contractId)){
            param.put("contractId",contractId);
        }
        if(StringUtil.isNotBlank(type)){
            param.put("type",type);
        }
        if(StringUtil.isNotBlank(contractId)){
            param.put("name",name);
            param.put("remark",name);
        }
        return R.data(service.page(Condition.getPage(page),Condition.getQueryWrapper(param,DatumPoint.class)));
    }

    @PostMapping("/add")
    public R<String> add (@RequestBody DatumPoint datumPoint, HttpSession session){
        if(StringUtil.isEmpty(datumPoint.getContractId())){
            return R.fail("合同id为空！，无法添加数据");
        }

        LambdaQueryWrapper<DatumPoint> queryWrapper=  Wrappers.<DatumPoint>lambdaQuery().eq(DatumPoint::getContractId,datumPoint.getContractId()).eq(DatumPoint::getType,datumPoint.getType()).eq(DatumPoint::getName,datumPoint.getName());
        if(this.service.count(queryWrapper)>0){
            return R.fail("同一合同段下，不能重复添加");
        }
        return R.status(this.service.save(datumPoint));
    }


    @PostMapping("/del")
    public R del(String ids){
          if(StringUtil.isNotBlank(ids)){
              return R.status(this.service.removeByIds(Func.toLongList(ids)));
          }
          return R.status(false);
    }


    @PostMapping("/update")
    public R<Boolean> upDate (@RequestBody DatumPointVo vo){
        DatumPoint old = this.service.getById(vo.getId());
        BeanUtils.copyProperties(vo,old);
        return R.status(this.service.updateById(old));
    }

    @ResponseBody
    @GetMapping("/queryData")
    public R<DatumPointVo> queryData(String queryName,String contractId ,Integer type){
        if(StringUtil.isEmpty(queryName)||StringUtil.isEmpty(contractId)||StringUtil.isEmpty(type)){
            return R.fail("缺少参数");
        }
       LambdaQueryWrapper<DatumPoint> wrapper = Wrappers.<DatumPoint>lambdaQuery().eq(DatumPoint::getName,queryName).eq(DatumPoint::getContractId,contractId).eq(DatumPoint::getType,type);
        DatumPoint dap = this.service.getOne(wrapper);
        DatumPointVo vo = new DatumPointVo();
        if(dap!=null) {
            BeanUtils.copyProperties(dap, vo);
        }
        return R.data(vo);
    }


    @PostMapping("/import")
    public R importXy(@RequestParam("file") MultipartFile file, Integer type , Long contractId, Long projectId) throws Exception {
        if(file != null&& type!=null && contractId!=null&&projectId!=null) {
            String fileName = Objects.requireNonNull(file.getOriginalFilename());
            if(Pattern.matches(".+(\\.xls)x?$",fileName.toLowerCase(Locale.ROOT))) {
                return this.service.importData(file,contractId,projectId,type);
            } else {
                R.fail("文件格式不正确，请上传Excel文件");
            }
        }
        return R.fail("缺少参数");
    }

    @PostMapping("/batchDel")
    public R bacthDel(String ids){
        return R.status(this.service.deleteLogic(Func.toLongList(ids)));
    }



    @GetMapping("exportExcel")
    public void  exportExcel(HttpServletResponse response, String contractId , Integer type, String search) throws IOException {

        List<DatumPoint> list=this.service.exportExcel(contractId,type,search);
        if(list!=null&&list.size()>0){
            //创建HSSFWorkbook对象(excel的文档对象)
            HSSFWorkbook wb = new HSSFWorkbook();
            //创建sheet对象（excel的表单）
            HSSFSheet sheet=wb.createSheet("测站点数据");
            //创建第一行，这里即是表头。行的最小值是0，代表每一行，上限没研究过，可参考官方的文档
            HSSFRow row1=sheet.createRow(0);
            if(type==1) {
                row1.createCell(0).setCellValue("测站点名称");
                row1.createCell(1).setCellValue("x坐标（m）");
                row1.createCell(2).setCellValue("y坐标（m）");
                row1.createCell(3).setCellValue("高程（m）");
                row1.createCell(4).setCellValue("等级");
                row1.createCell(5).setCellValue("备注");
                for (int i = 0; i < list.size(); i++) {
                    HSSFRow row = sheet.createRow(i + 1);
                    row.createCell(0).setCellValue(list.get(i).getName());
                    row.createCell(1).setCellValue(list.get(i).getX());
                    row.createCell(2).setCellValue(list.get(i).getY());
                    row.createCell(3).setCellValue(list.get(i).getH());
                    row.createCell(4).setCellValue(list.get(i).getLevel());
                    row.createCell(5).setCellValue(list.get(i).getRemark());

                }
            }else if(type==0){
                row1.createCell(0).setCellValue("测站点名称");
                row1.createCell(1).setCellValue("高程（m）");
                row1.createCell(2).setCellValue("等级");
                row1.createCell(3).setCellValue("备注");
                for (int i = 0; i < list.size(); i++) {
                    HSSFRow row = sheet.createRow(i + 1);
                    row.createCell(0).setCellValue(list.get(i).getName());
                    row.createCell(1).setCellValue(list.get(i).getH());
                    row.createCell(2).setCellValue(list.get(i).getLevel());
                    row.createCell(3).setCellValue(list.get(i).getRemark());

                }
            }
            //输出Excel文件
            OutputStream output=response.getOutputStream();
            response.reset();
            Date dt = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
            String fileName = sdf.format(dt);
            if(0==type){
                fileName=fileName+"水准点.xls";
            }else if(1==type){
                fileName=fileName+"导线点.xls";
            }
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            wb.write(output);
            output.close();
        }else {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println(JSON.toJSONString(R.fail("没有查到到相关数据")));
            out.flush();
            out.close();
        }

    }

}
