/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.stocks.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.stocks.dto.DeviceDepreciateQuery;
import com.tofly.stocks.entity.*;
import com.tofly.stocks.service.DeviceDepreciateService;
import com.tofly.stocks.service.InstockDetailService;
import com.tofly.stocks.service.InstockInfoService;
import com.tofly.stocks.vo.DeviceDepreciateJobVo;
import com.tofly.stocks.vo.DeviceDepreciateSelectVo;
import com.tofly.stocks.vo.DeviceDepreciateVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tofly.stocks.mapper.DeviceDepreciateMapper;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 设备折旧表
 *
 * @author admin
 * @date Mon Dec 12 00:00:00 CST 2022
 */
@Service("deviceDepreciateService")
public class DeviceDepreciateServiceImpl extends ServiceImpl<DeviceDepreciateMapper, DeviceDepreciate> implements DeviceDepreciateService {

    @Autowired
    private InstockDetailService instockDetailService;
    @Autowired
    private InstockInfoService instockInfoService;

    @Override
    public Page<DeviceDepreciateSelectVo> getDepreciateSelectDataPage(Page page, DeviceDepreciateQuery deviceDepreciateQuery) {
       if(deviceDepreciateQuery.getId()==null){

           deviceDepreciateQuery.setId(0L);
       }
        return this.baseMapper.getDepreciateSelectDataPage(page,deviceDepreciateQuery);
    }

    @Override
    @Transactional
    public Boolean saveDepreciate(DeviceDepreciate deviceDepreciate) {
       Integer count=this.baseMapper.selectCount(Wrappers.<DeviceDepreciate>lambdaQuery()
                .eq(DeviceDepreciate::getInstockDetailId,deviceDepreciate.getInstockDetailId()));
       if(count>0){
           throw new RuntimeException("该设备已经有折旧方式了，不能重复添加折旧方式");
       }

        syncDevice(deviceDepreciate);//当前时间
        InstockDetail instockDetail=new InstockDetail();
        instockDetail.setId(deviceDepreciate.getInstockDetailId());
        instockDetail.setCurrentPrice(deviceDepreciate.getCurrentPrice());
        instockDetailService.updateById(instockDetail);
        return this.save(deviceDepreciate);

    }

    /**
     * 计算折旧价值
     * @param deviceDepreciate
     */
    public  void  syncDevice(DeviceDepreciate deviceDepreciate){
        Date date=new Date();
       InstockDetail instockDetail=instockDetailService.getById(deviceDepreciate.getInstockDetailId());
      if(instockDetail==null || instockDetail.getInstockInfoId()==null){
          throw  new RuntimeException("参数错误，入库详情信息不存在，请核实");
      }
       InstockInfo instockInfo=instockInfoService.getById(instockDetail.getInstockInfoId());
        if(instockInfo==null || instockInfo.getId()==null){
            throw  new RuntimeException("参数错误，入库数据不存在，请核实");
        }
        Double totalPrice=instockDetail.getUnitPrice()*instockDetail.getInstockNum();//采购总价值
        Double CurrentPrice=0D; //当前价值
        deviceDepreciate.setDepreciatePrice(0D);
        String DepreciateType=deviceDepreciate.getDepreciateType();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Integer stockMonth=getMonthNum(sdf.format(instockInfo.getInstockTime()),sdf.format(date));
        deviceDepreciate.setInStockMonth(stockMonth);
        String DepreciateValue_str=deviceDepreciate.getDepreciateValue();
        DepreciateValue_str=DepreciateValue_str.replace("%","");
        Double DepreciateValue=Double.parseDouble(DepreciateValue_str);
       // Double stockYear= (double)Math.round(stockMonth*100/12D)/100;
        Double stockYear=stockMonth/12D;

        switch (DepreciateType){
            case  "1": //无折旧方式
                CurrentPrice=totalPrice;
                break;
            case "2": //固定按月折旧金额;采购价值-折旧值*月
                CurrentPrice=totalPrice-(DepreciateValue*stockMonth);
                break;
            case "3": //固定按年折旧金额;采购价值-折旧值*(月/12)
               CurrentPrice=totalPrice-(DepreciateValue*stockYear*100/100.00D);
                break;
            case "4":
                 //固定按月折旧率;采购价值-采购价值*折旧率*月
                CurrentPrice= totalPrice-(totalPrice*DepreciateValue*stockMonth/100.00D);
                break;
            case "5":
                //固定按年折旧率;采购价值-采购价值*折旧率*月

                CurrentPrice= totalPrice-(totalPrice*DepreciateValue*stockYear/100.00D);
                break;
            default:
                break;
        }

        CurrentPrice=CurrentPrice>0?CurrentPrice:0D;
        DecimalFormat df1 = new DecimalFormat("0.0000");//保留4位
        String ss= df1.format(CurrentPrice);
        CurrentPrice=Double.valueOf(ss);
        deviceDepreciate.setCurrentPrice(CurrentPrice);
        deviceDepreciate.setDepreciatePrice(0D);//用不上，默认写为0



  }

    private  Integer getMonthNum(String date1, String date2){

        Integer result = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(sdf.parse(date1));
            c2.setTime(sdf.parse(date2));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
        int month = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12;
        //System.out.println("日期："+date1+"|"+date2+"|,相差"+Math.abs(result)+"个月");
        return result == 0 ? 1 : Math.abs(month + result);

    }

    @Override
    @Transactional
    public Boolean editDepreciate(DeviceDepreciate deviceDepreciate) {

        //修改时候，入库时间
        syncDevice(deviceDepreciate);
        /*DeviceDepreciate deviceDepreciate_new= this.list(Wrappers.<DeviceDepreciate>lambdaQuery()
                .eq(DeviceDepreciate::getInstockDetailId,deviceDepreciate.getInstockDetailId())
                       .orderByDesc(DeviceDepreciate::getCreateTime)
                ).stream().findFirst().orElse(new DeviceDepreciate());

           //修改当前价值，只修改 创建时间为为最新的一条数据
           if(deviceDepreciate_new!=null && deviceDepreciate_new.getId().equals(deviceDepreciate.getId())){
               InstockDetail instockDetail=new InstockDetail();
               instockDetail.setId(deviceDepreciate.getInstockDetailId());
               instockDetail.setCurrentPrice(deviceDepreciate.getCurrentPrice());
               instockDetailService.updateById(instockDetail);

           }*/
        Integer count=this.baseMapper.selectCount(Wrappers.<DeviceDepreciate>lambdaQuery()
                .eq(DeviceDepreciate::getInstockDetailId,deviceDepreciate.getInstockDetailId())
                .ne(DeviceDepreciate::getId,deviceDepreciate.getId()));
        if(count>0){
            throw new RuntimeException("该设备已经有折旧方式了，不能修改");
        }

        InstockDetail instockDetail=new InstockDetail();
        instockDetail.setId(deviceDepreciate.getInstockDetailId());
        instockDetail.setCurrentPrice(deviceDepreciate.getCurrentPrice());
        instockDetailService.updateById(instockDetail);

        return this.updateById(deviceDepreciate);
    }

    @Override
    public Boolean deleteByIds(String ids) {
        List<String> lstIds = Arrays.asList(ids.split(","));

       /* QueryWrapper<StockInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("DEVICE_ID",lstIds);
        Integer count=stockInfoService.count(queryWrapper);
        if(count>0){
            throw new RuntimeException("选择的设备已有库存记录，不能删除");
        }*/

        return this.removeByIds(lstIds);
    }

    @Override
    @Transactional
    public void xxlJobCurrentPrice() {
        List<DeviceDepreciateJobVo> list=this.baseMapper.xxlJobCurrentPrice();
        Date date=new Date();
        if(list!=null &&list.size()>0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            for (DeviceDepreciateJobVo deviceDepreciateVo:list
                 ) {
                Double totalPrice=deviceDepreciateVo.getUnitPrice()*deviceDepreciateVo.getInstockNum();//采购总价值
                Double CurrentPrice=0D; //当前价值
                String DepreciateType=deviceDepreciateVo.getDepreciateType();
                Integer stockMonth=getMonthNum(sdf.format(deviceDepreciateVo.getInstockTime()),sdf.format(date));
                String DepreciateValue_str=deviceDepreciateVo.getDepreciateValue();
                DepreciateValue_str=DepreciateValue_str.replace("%","");
                Double DepreciateValue=Double.parseDouble(DepreciateValue_str);
                Double stockYear=stockMonth/12D;
                switch (DepreciateType){
                    case  "1": //无折旧方式
                        CurrentPrice=totalPrice;
                        break;
                    case "2": //固定按月折旧金额;采购价值-折旧值*月
                        CurrentPrice=totalPrice-(DepreciateValue*stockMonth);
                        break;
                    case "3": //固定按年折旧金额;采购价值-折旧值*(月/12)
                        CurrentPrice=totalPrice-(DepreciateValue*stockYear*100/100.00D);
                        break;
                    case "4":
                        //固定按月折旧率;采购价值-采购价值*折旧率*月
                        CurrentPrice= totalPrice-(totalPrice*DepreciateValue*stockMonth/100.00D);
                        break;
                    case "5":
                        //固定按年折旧率;采购价值-采购价值*折旧率*月

                        CurrentPrice= totalPrice-(totalPrice*DepreciateValue*stockYear/100.00D);
                        break;
                    default:
                        break;

                }
                CurrentPrice=CurrentPrice>0?CurrentPrice:0D;
                DecimalFormat df1 = new DecimalFormat("0.0000");//保留4位
                String ss= df1.format(CurrentPrice);
                CurrentPrice=Double.valueOf(ss);

                this.update(Wrappers.<DeviceDepreciate>lambdaUpdate()
                        .set(DeviceDepreciate::getInStockMonth,stockMonth)
                        .set(DeviceDepreciate::getCurrentPrice,CurrentPrice)
                        .set(DeviceDepreciate::getDepreciatePrice,0D)
                        .set(DeviceDepreciate::getUpdateTime,new Date())
                        .eq(DeviceDepreciate::getId,deviceDepreciateVo.getId())
                );
                InstockDetail instockDetail=new InstockDetail();
                instockDetail.setId(deviceDepreciateVo.getInstockDetailId());
                instockDetail.setCurrentPrice(CurrentPrice);
                instockDetailService.updateById(instockDetail);
            }

        }

    }


    @Override
    public Page<DeviceDepreciateVo> getDataPage(Page page, DeviceDepreciateQuery deviceDepreciateQuery) {
        return this.baseMapper.getDataPage(page,deviceDepreciateQuery);
    }
}
