package org.springblade.business.controller;

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.dto.MileagePartDto;
import org.springblade.business.dto.MileagexyDTO;
import org.springblade.business.entity.Mileage;
import org.springblade.business.entity.MileagePart;
import org.springblade.business.entity.Mileagexy;
import org.springblade.business.service.impl.MileagePartService;
import org.springblade.business.service.impl.MileagexyService;
import org.springblade.business.utils.MileageUtill;
import org.springblade.business.vo.MileageVo;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.CollectionUtil;
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 java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author yangyj
 * @Date 2022/5/31 11:02
 * @description TODO
 */
@RestController
@AllArgsConstructor
@RequestMapping("/mileage")
@Api(tags = "平曲线接口")
public class MileageController {
    private final MileagePartService partService;
    private final MileagexyService service;



    @GetMapping("/part/list")
    public R<List<MileagePart>> plist(@RequestParam Map<String, Object> part) {
        List<MileagePart> list = partService.list(Condition.getQueryWrapper(part, MileagePart.class).lambda().orderByDesc(MileagePart::getCreateTime));
        return R.data(list);
    }



//    @GetMapping("/part/list")
//    public R<List<MileagePart>> list( String contractId) {
//        List<MileagePart> data=partService.getBaseMapper().selectList(Wrappers.<MileagePart>query().lambda().eq(MileagePart::getContractId,contractId));
//        return R.data(data);
//    }



    @PostMapping("/part/add")
    public R<MileagePart> add (@RequestBody MileagePart part){
        part.setCreateUser(AuthUtil.getUserId());
        this.partService.save(part);
        return R.data(part);
    }


    @PostMapping("/part/update")
    public R<String> upDate (@RequestBody MileagePartDto part){
         MileagePart old = partService.getById(part.getId());
         if(old==null){
             return R.fail("对象不存在");
         }
        //同步更新片段信息
        if(!old.getPrefix().equals(part.getPrefix())){
            this.partService.updatePart(old.getProjectId(),old.getPrefix(),part.getPrefix());
        }
        old.setName(part.getName());
        old.setPrefix(part.getPrefix());
        old.setRemark(part.getRemark());
        this.partService.updateById(old);
        return R.success("更新成功");
    }

    @PostMapping("/part/del")
    public R<String> partDel(String ids){
        if(StringUtil.isBlank(ids)){
            return R.fail("对象不存在");
        }
        return R.status(partService.removeByIds(Func.toLongList(ids)));
    }



    @GetMapping("pschange")
    public R<MileageVo> coordinate(String b , String value, String jj, String projectId, String partId) {
        if(StringUtil.isEmpty(b)||StringUtil.isEmpty(value)||StringUtil.isEmpty(jj)||StringUtil.isEmpty(projectId)||StringUtil.isEmpty(partId)){
            return  R.fail("参数不全");
        }
        double[] aa= MileageUtill.azimuthZbXy(Double.parseDouble(value),Double.parseDouble(b),Double.parseDouble(jj),this.service.list(Wrappers.<Mileagexy>query().lambda().eq(Mileagexy::getPartId,partId).eq(Mileagexy::getProjectId,projectId)));
        if(aa==null){
            return R.fail("线元信息不存在，请按照图纸录入系统");
        }
        MileageVo vo = new MileageVo();
        vo.setX(Double.parseDouble(String.format("%.3f",aa[0])));
        vo.setValue(Double.parseDouble(value));
        vo.setB(Double.parseDouble(b));
        vo.setJj(Double.parseDouble(jj));
        vo.setY(Double.parseDouble(String.format("%.3f",aa[1])));
        return R.data(vo);
    }

    @PostMapping("/import")
    public R importXy(@RequestParam("file") MultipartFile file, String projectId,String partId,String contractId ) throws Exception {
        if(file != null&&Func.isNotEmpty(partId)) {
            if(Pattern.matches(".+(\\.xls)x?$", Objects.requireNonNull(file.getOriginalFilename()).toLowerCase(Locale.ROOT))) {
             return   R.success(this.service.importMileagexy(file,AuthUtil.getUserId(),projectId,contractId,partId));
            } else {
               return   R.fail("文件格式不正确，请上传Excel文件");
            }
        }
        return R.fail("文件或片段不存在");
    }




    @GetMapping("/list")
    public R<IPage<Mileagexy>> page(Long partId, Query query) {
        IPage<Mileagexy> pages = service.page(Condition.getPage(query), Wrappers.<Mileagexy>lambdaQuery().eq(Mileagexy::getPartId,partId));
        return R.data(pages);
    }


    @PostMapping("/add")
    public R<Mileagexy> add (@RequestBody Mileagexy mileagexy){
        mileagexy.setUpdateUser(AuthUtil.getUserId());
        mileagexy.setValueEnd(mileagexy.getValue()+mileagexy.getL());
        //必须要设置angle
        mileagexy.setAngle(mileagexy.getDu()+Double.valueOf(mileagexy.getFen())/60+mileagexy.getMiao()/3600);
        this.service.save(mileagexy);
        return R.data(mileagexy);
    }



    @PostMapping("/del")
    public R<String> del(String id){
        if(service.removeById(id)){
            return R.data("删除成功");
        }else{
            return R.fail("删除失败");
        }
    }



    @PostMapping("/find")
    public R<Mileagexy> find(String id){
        return  R.data(service.getById(id));
    }




    @PostMapping("/update")
    public R upDate (@RequestBody MileagexyDTO mileagexy){
        if(mileagexy.getId()!=null){
            Mileagexy m= this.service.getById(mileagexy.getId());
            if(m!=null){
                BeanUtils.copyProperties(mileagexy,m);
                m.setValueEnd(mileagexy.getValue()+mileagexy.getL());
                //必须要设置angle
                mileagexy.setAngle(m.getDu()+ Double.valueOf(m.getFen())/60+m.getMiao()/3600);
                return R.status(this.service.updateById(m));
            }
        }
        return R.fail("对象不存在");
    }


    @PostMapping("/getNextMileagexy")
    public Mileagexy  getNextMileagexy(@RequestBody Mileagexy mileagexy) {
        Mileagexy nextmileagexy =new Mileagexy();
        Mileagexy max=service.getMaxMileagexy(mileagexy.getPartId(),0,mileagexy.getProjectId(),mileagexy.getOrderNum());
        if(max!=null){
            MileageUtill.initMileagexy(max,nextmileagexy);
            nextmileagexy.setR(max.getR());
            nextmileagexy.setSwing(max.getSwing());
        }
        return nextmileagexy;
    }


    @GetMapping("getZzList")
    public R<List<Mileage>> getZzList(Mileage mileage) {
        List<Mileage> mileages = new ArrayList<>(MileageUtill.azimuthZzZbXy(mileage.getX(), mileage.getY(), mileage.getValue(), mileage.getB(), this.service.list(Wrappers.<Mileagexy>query().lambda().eq(Mileagexy::getPartId,mileage.getPartId()).eq(Mileagexy::getProjectId,mileage.getProjectId()).orderByAsc(Mileagexy::getOrderNum))));
         if(CollectionUtil.isNotEmpty(mileages)){
            return R.data(mileages);
         }
        return R.fail("暂无数据");
    }


    @GetMapping("exportExcel")
    public boolean  exportExcel(HttpServletResponse response, String projectId , String partId, String partNo) throws IOException {
        LambdaQueryWrapper<Mileagexy> queryWrapper = Wrappers.<Mileagexy>query().lambda();
        queryWrapper.eq(Mileagexy::getPartId,partId).eq(Mileagexy::getProjectId,projectId);
        List<Mileagexy> mileagexyData = this.service.list(queryWrapper);
        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet对象（excel的表单）
        HSSFSheet sheet=wb.createSheet("操作日志列表");

        //创建第一行，这里即是表头。行的最小值是0，代表每一行，上限没研究过，可参考官方的文档
        HSSFRow row1=sheet.createRow(0);
        //在这一行创建单元格，并且将这个单元格的内容设为“账号”，下面同理。
        //列的最小值标识也是0
        row1.createCell(0).setCellValue("序号");
        row1.createCell(1).setCellValue("里程");
        row1.createCell(2).setCellValue("排序");
        row1.createCell(3).setCellValue("长度");
        row1.createCell(4).setCellValue("方位角");
        row1.createCell(5).setCellValue("类型");
        row1.createCell(6).setCellValue("转向");
        row1.createCell(7).setCellValue("x");
        row1.createCell(8).setCellValue("y");
        row1.createCell(9).setCellValue("半径");
        for (int i = 0; i < mileagexyData.size(); i++) {
            HSSFRow row=sheet.createRow(i+1);
            row.createCell(0).setCellValue(i+1);
            row.createCell(1).setCellValue(valuetoStr(mileagexyData.get(i).getValue(),partNo) +'~'+valuetoStr(mileagexyData.get(i).getValueEnd(),partNo));
            row.createCell(2).setCellValue(mileagexyData.get(i).getOrderNum());
            row.createCell(3).setCellValue(mileagexyData.get(i).getL());
            row.createCell(4).setCellValue(mileagexyData.get(i).getAngle());
            row.createCell(5).setCellValue(mileagexyData.get(i).getType());
            row.createCell(6).setCellValue(mileagexyData.get(i).getSwing());
            row.createCell(7).setCellValue(mileagexyData.get(i).getX());
            row.createCell(8).setCellValue(mileagexyData.get(i).getY());
            row.createCell(9).setCellValue(mileagexyData.get(i).getR());

        }
        //输出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)+"平曲线.xls";
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        wb.write(output);
        output.close();
        return true;
    }
    public String valuetoStr(Double num,String partNo) {
        String preffix = "000";
        String xstr="";
        String ystr="";
        double x = Math.floor(num/1000);
        if(x<0){
            x=0;
        }
        xstr = x+"";
        if (Math.round(x) - x == 0) {
            xstr=(long) x+"";
        }
        BigDecimal bg = new BigDecimal(num%1000).setScale(3, BigDecimal.ROUND_HALF_UP);
        double y = bg.doubleValue();
        String sign=y<0?"-":"+";
        ystr = y+"";
        if (Math.round(y) - y == 0) {
            ystr = ""+(long) y;
        }
        if(ystr.length() <= 3|| ystr.indexOf('.')<=3){
            int len =0;
            if(ystr.indexOf('.')>-1){
                len=ystr.indexOf('.');
            }else{
                len=ystr.length();
            }
            ystr=""+preffix.substring(0,preffix.length()-len)+ystr;

        }
        return partNo+'K'+xstr+sign+ystr;
    }


}
