package com.shinsoft.sto.service.impl.main;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shinsoft.sto.mapper.main.CargoMapper;
import com.shinsoft.sto.mapper.main.CargoChangeRecordMapper;
import com.shinsoft.sto.model.main.Cargo;
import com.shinsoft.sto.model.main.CargoChangeRecord;
import com.shinsoft.sto.service.main.CargoService;
import com.shinsoft.tools.JSONTools;
import com.shinsoft.tools.model.common.ResponseCodeMsg;
import com.shinsoft.tools.model.common.ResultJSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class CargoServiceImp extends ServiceImpl<CargoMapper, Cargo> implements CargoService {

    ResultJSON resultJSON;

    @Autowired
    CargoMapper cargoMapper;
    @Autowired
    CargoChangeRecordMapper cargoChangeRecordMapper;

    @Override
    public ResultJSON query(Integer page, Integer rows, Map<String, Object> params) {
        try {
            Page<Cargo> cargoPage = new Page<>(page, rows);
            Page<Cargo> list = cargoMapper.selectCargoPage(cargoPage, params);

            // 设置客户名称，方便前端显示
            if (list.getRecords() != null) {
                for (Cargo cargo : list.getRecords()) {
                    if (cargo.getUperCustomer() != null) {
                        cargo.setUperCustomerName(cargo.getUperCustomer().getCustomerNm());
                    }
                    if (cargo.getCustomer() != null) {
                        cargo.setCustomerName(cargo.getCustomer().getCustomerNm());
                    }
                }
            }

            resultJSON = JSONTools.toResultJSON(list);
        } catch (Exception ex) {
            ex.printStackTrace();
            resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, ex);
        }
        return resultJSON;
    }
    @Override
    public ResultJSON queryByPK(String id) {
        try {
            Cargo cargo = cargoMapper.selectById(id);
            resultJSON = JSONTools.toResultJSON(cargo);
        } catch (Exception ex) {
            ex.printStackTrace();
            resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, ex);
        }
        return resultJSON;
    }
    @Override
    public ResultJSON save(String userId, String json) {
        try {
            Date date = new Date();
            Cargo cargo = JSON.parseObject(json, new TypeReference<Cargo>() {});

            if (StringUtils.isEmpty(cargo.getId())) {
                cargo.setCancelFlag("0");
                cargo.setAddId(userId);
                cargo.setAddTime(date);
                cargoMapper.insert(cargo);
            } else {
                cargo.setModifyId(userId);
                cargo.setModifyTime(date);
                cargoMapper.updateById(cargo);
            }

            resultJSON = JSONTools.toResultJSON(cargo);
        } catch (Exception ex) {
            ex.printStackTrace();
            resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, ex);
        }
        return resultJSON;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJSON transfer(String userId, String json) {
        try {
            Date date = new Date();
            // 解析前端传递的数据
            Map<String, Object> formData = JSON.parseObject(json, new TypeReference<Map<String, Object>>() {});

            String uperCustomerId = (String) formData.get("uperCustomerId");
            String customerId = (String) formData.get("customerId");
            String subStr = (String) formData.get("subStr"); // 增加/减少
            BigDecimal weight = new BigDecimal(formData.get("weight").toString());
            String ordNo = (String) formData.get("ordNo");
            String remark = (String) formData.get("remark");

            // 根据上游客户ID和客户ID查询是否已存在货权记录
            QueryWrapper<Cargo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uper_customer_id", uperCustomerId)
                    .eq("customer_id", customerId)
                    .eq("cancel_flag", "0");
            Cargo existingCargo = cargoMapper.selectOne(queryWrapper);

            Cargo cargo;
            if (existingCargo == null) {
                // 新增记录
                cargo = new Cargo();
                cargo.setId(UUID.randomUUID().toString().replace("-", ""));
                cargo.setUperCustomerId(uperCustomerId);
                cargo.setCustomerId(customerId);

                if ("增加".equals(subStr)) {
                    // 新增+增加：可使用量=0+重量，已使用量=0
                    cargo.setSumWeight(weight);
                    cargo.setUseWeight(BigDecimal.ZERO);
                } else if ("减少".equals(subStr)) {
                    // 新增+减少：不允许，因为不能从0减少
                    resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, "无法对不存在的记录进行减少操作");
                    return resultJSON;
                } else {
                    // 默认新增：可使用量=0+重量，已使用量=0
                    cargo.setSumWeight(weight);
                    cargo.setUseWeight(BigDecimal.ZERO);
                }

                cargo.setCancelFlag("0");
                cargo.setAddId(userId);
                cargo.setAddTime(date);
                cargoMapper.insert(cargo);
            } else {
                // 更新现有记录
                cargo = existingCargo;
                BigDecimal oldSumWeight = cargo.getSumWeight() != null ? cargo.getSumWeight() : BigDecimal.ZERO;
                BigDecimal oldUseWeight = cargo.getUseWeight() != null ? cargo.getUseWeight() : BigDecimal.ZERO;

                if ("增加".equals(subStr)) {
                    // 增加：可使用量=原可使用量+重量，已使用量不变
                    cargo.setSumWeight(oldSumWeight.add(weight));
                } else if ("减少".equals(subStr)) {
                    // 减少：可使用量=原可使用量-重量，已使用量=0+重量
                    if (oldSumWeight.compareTo(weight) < 0) {
                        resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, "减少的重量不能大于当前可使用量");
                        return resultJSON;
                    }
                    cargo.setSumWeight(oldSumWeight.subtract(weight));
                    cargo.setUseWeight(oldUseWeight.add(weight));
                }

                cargo.setModifyId(userId);
                cargo.setModifyTime(date);
                cargoMapper.updateById(cargo);
            }

            // 记录货权变更履历
            CargoChangeRecord changeRecord = new CargoChangeRecord();
            changeRecord.setId(UUID.randomUUID().toString().replace("-", ""));
            changeRecord.setWeight(weight);
            changeRecord.setChangeFrom("手动调整");
            changeRecord.setSubStr(subStr);
            changeRecord.setUperCustomerId(uperCustomerId);
            changeRecord.setCustomerId(customerId);
            changeRecord.setOrdNo(ordNo);
            changeRecord.setRemark(remark);
            changeRecord.setCancelFlag("0");
            changeRecord.setAddId(userId);
            changeRecord.setAddTime(date);
            changeRecord.setModifyId(userId);
            changeRecord.setModifyTime(date);
            cargoChangeRecordMapper.insert(changeRecord);

            resultJSON = JSONTools.toResultJSON(cargo);
        } catch (Exception ex) {
            ex.printStackTrace();
            resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, ex);
        }
        return resultJSON;
    }
   /* @Override
    public ResultJSON save(String userId, String json) {
        try {
            Date date = new Date();
            Cargo cargo = JSON.parseObject(json, new TypeReference<Cargo>() {});

            if (StringUtils.isEmpty(cargo.getId())) {
                cargo.setCancelFlag("0");
                cargo.setAddId(userId);
                cargo.setAddTime(date);
                cargoMapper.insert(cargo);
            } else {
                cargo.setModifyId(userId);
                cargo.setModifyTime(date);
                cargoMapper.updateById(cargo);
            }

            resultJSON = JSONTools.toResultJSON(cargo);
        } catch (Exception ex) {
            ex.printStackTrace();
            resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, ex);
        }
        return resultJSON;
    }

    @Override
    public ResultJSON transfer(String userId, String json) {
        try {
            Date date = new Date();
            Cargo cargo = JSON.parseObject(json, new TypeReference<Cargo>() {});
            // 这里实现货权转移逻辑，包括记录变更履历
            // 具体实现根据业务需求来写
            resultJSON = JSONTools.toResultJSON(cargo);
        } catch (Exception ex) {
            ex.printStackTrace();
            resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, ex);
        }
        return resultJSON;
    }*/

    @Override
    public ResultJSON remove(String userId, String id) {
        try {
            Date date = new Date();
            Cargo cargo = cargoMapper.selectById(id);
            cargo.setCancelFlag("1");
            cargo.setModifyId(userId);
            cargo.setModifyTime(date);
            cargoMapper.updateById(cargo);
            resultJSON = JSONTools.toResultJSON("");
        } catch (Exception ex) {
            ex.printStackTrace();
            resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, ex);
        }
        return resultJSON;
    }

    @Override
    public ResultJSON removeBatch(String userId, String ids) {
        try {
            Date date = new Date();
            List<String> list = JSON.parseObject(ids, new TypeReference<List<String>>() {});
            Cargo cargo;
            for (String id : list) {
                cargo = cargoMapper.selectById(id);
                cargo.setCancelFlag("1");
                cargo.setModifyId(userId);
                cargo.setModifyTime(date);
                cargoMapper.updateById(cargo);
            }
            resultJSON = JSONTools.toResultJSON("");
        } catch (Exception ex) {
            ex.printStackTrace();
            resultJSON = JSONTools.toResultJSON(ResponseCodeMsg.CODE_EX, ex);
        }
        return resultJSON;
    }
}