package com.shinsoft.sto.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shinsoft.frameworkapi.model.SysDepartment;
import com.shinsoft.frameworkapi.model.SysUser;
import com.shinsoft.frameworkapi.service.FrameworkService;
import com.shinsoft.sto.mapper.StocktakingMapper;
import com.shinsoft.sto.model.Stocktaking;
import com.shinsoft.sto.service.StocktakingService;
import org.springframework.stereotype.Service;


import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.shinsoft.tools.JSONTools;
import com.shinsoft.tools.model.common.ResultJSON;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 盘库记录表 服务实现类
 * </p>
 *
 * @author system
 * @since 2024-10-17
 */
@Service
public class StocktakingServiceImp extends ServiceImpl<StocktakingMapper, Stocktaking> implements StocktakingService {


    ResultJSON resultJSON;

    @Autowired
    StocktakingMapper stocktakingMapper;

    @Autowired
    FrameworkService frameworkService;

    @Override
    public ResultJSON query(int page, int rows, String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        Page<Stocktaking> stocktakingPage = new Page<>(page, rows);
        QueryWrapper<Stocktaking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cancel_flag", "0");
        queryWrapper.orderByDesc("add_time");
        String storeNm = "";
        String areaCd = "";
        String stackCd = "";
        String itemNm = "";
        if (ObjectUtils.isNotEmpty(jsonObject.get("storeNm"))) {
            storeNm = jsonObject.getString("storeNm");
            queryWrapper.like("store_nm", storeNm);
        }
        if (ObjectUtils.isNotEmpty(jsonObject.get("areaCd"))) {
            areaCd = jsonObject.getString("areaCd");
            queryWrapper.like("area_cd", areaCd);
        }
        if (ObjectUtils.isNotEmpty(jsonObject.get("stackCd"))) {
            stackCd = jsonObject.getString("stackCd");
            queryWrapper.like("stack_cd", stackCd);
        }
        if (ObjectUtils.isNotEmpty(jsonObject.get("itemNm"))) {
            itemNm = jsonObject.getString("itemNm");
            queryWrapper.like("item_nm", itemNm);
        }
        if (ObjectUtils.isNotEmpty(jsonObject.get("date"))) {
            JSONArray jsonArray = jsonObject.getJSONArray("date");
            if (!CollectionUtils.isEmpty(jsonArray)) {
                Date startDate = null;
                Date endDate = null;
                try {
                    startDate = new SimpleDateFormat("yyyy-MM-dd").parse(jsonArray.getString(0));
                    endDate = new SimpleDateFormat("yyyy-MM-dd").parse(jsonArray.getString(1));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                queryWrapper.between("STOCKTAKING_DATE", startDate,endDate);
            }
        }
        IPage<Stocktaking> list = stocktakingMapper.selectPage(stocktakingPage, queryWrapper);
        resultJSON = JSONTools.toResultJSON(list);
        return resultJSON;
    }

    @Override
    public ResultJSON queryByPK(String id) {
        Stocktaking stocktaking = stocktakingMapper.selectByPK(id);
        resultJSON = JSONTools.toResultJSON(stocktaking);
        return resultJSON;
    }


    @Override
    public ResultJSON save(String userId, String json) {
        Date date = new Date();
        Stocktaking stocktaking = JSON.parseObject(json, new TypeReference<Stocktaking>() {
        });
        ResultJSON userInfoRes = frameworkService.queryUserInfoById(userId, "");
        SysUser user = null;
        List<SysDepartment> deptTreeList = null;
        List<SysDepartment> deptsList = null;
        if (userInfoRes.getCode() == 0) {
            Map<String, Object> mapInfo = JSON.parseObject(userInfoRes.getData().toString(), new TypeReference<Map<String, Object>>() {
            });
            user = JSON.parseObject(mapInfo.get("user").toString(), new TypeReference<SysUser>() {
            });
            deptTreeList = JSON.parseArray(mapInfo.get("deptTree").toString(), SysDepartment.class);
            deptsList = JSON.parseArray(mapInfo.get("depts").toString(), SysDepartment.class);
        }
        if (StringUtils.isEmpty(stocktaking.getId())) {
            stocktaking.setCancelFlag("0");
            stocktaking.setAddId(userId);
            stocktaking.setAddTime(date);

            stocktaking.setStocktakingDate(date);

            if (!CollectionUtils.isEmpty(deptTreeList)) {
                stocktaking.setCompCd(deptTreeList.get(0).getDeptCode());
            }

            if (!ObjectUtils.isEmpty(user)) {
                stocktaking.setAddCode(user.getUserCode());
                stocktaking.setAddName(user.getUserDesc());
                stocktaking.setStocktakingUser(user.getUserDesc());
            }
            if (!CollectionUtils.isEmpty(deptsList)) {
                stocktaking.setDeptCd(deptsList.get(0).getDeptCode());
                stocktaking.setAddDeptId(deptsList.get(0).getId());
                stocktaking.setAddDeptName(deptsList.get(0).getDeptName());
                stocktaking.setAddDeptCode(deptsList.get(0).getDeptCode());
            }
            stocktaking.setSubmitFlag("0");

            stocktakingMapper.insert(stocktaking);
        } else {
            stocktaking.setModifyId(userId);
            stocktaking.setModifyTime(date);
            if (!ObjectUtils.isEmpty(user)) {
                stocktaking.setModifyCode(user.getUserCode());
                stocktaking.setModifyName(user.getUserDesc());
            }
            stocktakingMapper.updateById(stocktaking);
        }

        resultJSON = JSONTools.toResultJSON(stocktaking);
        return resultJSON;
    }

    @Override
    public ResultJSON remove(String userId, String id) {
        Date date = new Date();
        Stocktaking stocktaking = stocktakingMapper.selectById(id);
        stocktaking.setCancelFlag("1");
        stocktaking.setCancelId(userId);
        stocktaking.setCancelTime(date);
        ResultJSON userInfoRes = frameworkService.queryUserInfoById(userId, "");
        SysUser user = null;

        if (!ObjectUtils.isEmpty(userInfoRes) && userInfoRes.getData() != null && !userInfoRes.getData().equals("null") && !userInfoRes.getData().equals("")) {
            Map<String, Object> mapInfo = JSON.parseObject(userInfoRes.getData().toString(), new TypeReference<Map<String, Object>>() {
            });
            user = JSON.parseObject(mapInfo.get("user").toString(), new TypeReference<SysUser>() {
            });
        }
        if (!ObjectUtils.isEmpty(user)) {
            stocktaking.setCancelName(user.getUserDesc());
            stocktaking.setCancelCode(user.getUserCode());
        }
        stocktakingMapper.updateById(stocktaking);
        resultJSON = JSONTools.toResultJSON("");
        return resultJSON;
    }

    @Override
    public ResultJSON removeBatch(String userId, String ids) {
        Date date = new Date();
        List<String> list = JSON.parseObject(ids, new TypeReference<List<String>>() {
        });
        Stocktaking stocktaking;
        for (String id : list) {
            stocktaking = stocktakingMapper.selectById(id);
            stocktaking.setCancelFlag("1");
            stocktaking.setCancelId(userId);
            stocktaking.setCancelTime(date);
            stocktakingMapper.updateById(stocktaking);
        }
        resultJSON = JSONTools.toResultJSON("");
        return resultJSON;
    }

}
