package com.ruoyi.web.v2.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.v2.entity.JsStoreTransportInfo;
import com.ruoyi.web.v2.mapper.JsStoreMapper;
import com.ruoyi.web.v2.mapper.JsStoreTransportInfoMapper;
import com.ruoyi.web.v2.model.JsStore;
import com.ruoyi.web.v2.model.JsTransport;
import com.ruoyi.web.v2.mapper.JsTransportMapper;
import com.ruoyi.web.v2.service.IJsTransportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.web.v2.utils.PhoneNumberValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * <p>
 * v2.0无害化转运 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-26
 */
@Service
public class JsTransportServiceImpl extends ServiceImpl<JsTransportMapper, JsTransport> implements IJsTransportService {

    @Autowired
    private JsTransportMapper transportMapper;
    @Autowired
    private JsStoreMapper storeMapper;
    @Autowired
    private JsStoreTransportInfoMapper storeTransportInfoMapper;
    @Override
    @Transactional
    public AjaxResult add(JsTransport transport) {
        if (ObjectUtil.isNotEmpty(transport.getPhone())) {
            if (!PhoneNumberValidator.isValidContact(transport.getPhone())) {

                return error("联系方式格式不正确！");
            }
        }
        JsTransport jsTransport = transportMapper.selectOne(new QueryWrapper<JsTransport>().orderByDesc("id").last(" limit 1").between("transport_time", DateUtil.beginOfDay(new Date()),DateUtil.endOfDay(new Date())));
        if (ObjectUtil.isNotEmpty(jsTransport)) {
            String materialBatch = jsTransport.getHarmlessTreatmentId();
            Integer integer = Integer.valueOf(materialBatch);
            String formattedNumber = String.format("%02d", integer+1);
            transport.setHarmlessTreatmentId(formattedNumber);
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String format = sdf.format(new Date());
            transport.setHarmlessTreatmentId(format+String.format("%02d", 1));
        }
        for (String s : transport.getHarmlessTreatmentIds().split(",")) {
            JsStore jsStore = new JsStore();
            jsStore.setIsLeave(1);
            storeMapper.update(jsStore,new UpdateWrapper<JsStore>().eq("harmless_treatment_id",s));
        }

        transportMapper.insert(transport);


        saveStoreTransport(transport);
        return success();
    }
    private void saveStoreTransport(JsTransport jsStore) {
        Double unqualifiedWeight = Double.parseDouble(jsStore.getUnqualifiedWeight());
        JsStoreTransportInfo id = storeTransportInfoMapper.selectOne(new QueryWrapper<JsStoreTransportInfo>().eq("instock_date",DateUtil.format(new Date(),"yyyy-MM-dd")));
        if(id != null){
            id.setStockNum(String.format("%.2f",Double.parseDouble(id.getStockNum()) -unqualifiedWeight ));
            id.setOutstockNum(String.format("%.2f",unqualifiedWeight +Double.parseDouble(id.getOutstockNum())));
            id.setJiaojieren(jsStore.getResponsibilityUser());
            storeTransportInfoMapper.updateById(id);
        }

    }

    @Override
    @Transactional
    public AjaxResult edit(JsTransport transport) {
        if (ObjectUtil.isNotEmpty(transport.getPhone())) {
            if (!PhoneNumberValidator.isValidContact(transport.getPhone())) {

                return error("联系方式格式不正确！");
            }
        }
        JsTransport jsStore1 = transportMapper.selectById(transport.getId());
        transportMapper.updateById(transport);
        transport.setUnqualifiedWeight(String.format("%.2f",Double.parseDouble(transport.getUnqualifiedWeight())-Double.parseDouble(jsStore1.getUnqualifiedWeight())));
        saveStoreTransport(transport);
        return success();
    }

    @Override
    @Transactional
    public AjaxResult delete(String ids) {
        String[] split = ids.split(",");
        for (String s : split) {
            JsTransport jsStore1 = transportMapper.selectById(s);
            jsStore1.setUnqualifiedWeight(String.format("%.2f",Double.parseDouble(jsStore1.getUnqualifiedWeight())*-1));
            transportMapper.deleteById(s);

            for (String s2 : jsStore1.getHarmlessTreatmentIds().split(",")) {
                JsStore jsStore = new JsStore();
                jsStore.setIsLeave(0);
                storeMapper.update(jsStore,new UpdateWrapper<JsStore>().eq("harmless_treatment_id",s2));
            }
            saveStoreTransport(jsStore1);
        }
        return success();
    }

    @Override
    public AjaxResult page(Integer pageNum, Integer pageSize, String startTime, String endTime, Integer harmlessTreatmentId) {
        Page<JsTransport> page = new Page<>(pageNum, pageSize);
        QueryWrapper<JsTransport> queryWrapper = new QueryWrapper<>();
        if ("".equals(startTime) || null == startTime) {

        } else {
            queryWrapper.between("transport_time", startTime, endTime);
        }
        if (null != harmlessTreatmentId) {
            queryWrapper.eq("harmless_treatment_id", harmlessTreatmentId);
        }
        queryWrapper.orderByDesc("transport_time");
        return success(transportMapper.selectPage(page, queryWrapper));
    }

    @Override
    public AjaxResult listAll() {
        return success(transportMapper.selectList(null));
    }
}
