package com.shinsoft.sto.service.impl;

import com.shinsoft.frameworkapi.model.SysDepartment;
import com.shinsoft.frameworkapi.model.SysUser;
import com.shinsoft.frameworkapi.service.FrameworkService;
import com.shinsoft.sto.model.Config;
import com.shinsoft.sto.mapper.ConfigMapper;
import com.shinsoft.sto.service.ConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;


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

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-15
 */
@Service
public class ConfigServiceImp extends ServiceImpl<ConfigMapper, Config> implements ConfigService {


    ResultJSON resultJSON;

    @Autowired
    ConfigMapper configMapper;

    @Autowired
    FrameworkService frameworkService;

    @Override
    public ResultJSON query(int page, int rows, String params , Map<String,Object> map) {
        JSONObject jsonObject = JSON.parseObject(params);
        Page<Config> configPage = new Page<>(page, rows);
        QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cancel_flag", "0");
        queryWrapper.orderByDesc("add_time");
        String storeNm = "";
        String activeStatus = "";
        String areaCd = "";
        String stackCd = "";
        String storeType = "";
//        IPage<Config> list = configMapper.selectPage(configPage, queryWrapper);
        if (!ObjectUtils.isEmpty(map)) {
            if (!ObjectUtils.isEmpty(map.get("activeStatus"))) {
                activeStatus = map.get("activeStatus").toString();
            }
            if (!ObjectUtils.isEmpty(map.get("storeNm"))) {
                storeNm = map.get("storeNm").toString();
            }
            if (!ObjectUtils.isEmpty(map.get("areaCd"))) {
                areaCd = map.get("areaCd").toString();
            }
            if (!ObjectUtils.isEmpty(map.get("stackCd"))) {
                stackCd = map.get("stackCd").toString();
            }
            if (!ObjectUtils.isEmpty(map.get("storeType"))) {
                storeType = map.get("storeType").toString();
            }
        }
        Page<Config> autoPage = new Page<>(page, rows);
        Page<Config> list = configMapper.selectAll(autoPage,activeStatus, storeNm, areaCd,stackCd,storeType);


        // 状态，字典
//        ResultJSON startStatusDic = frameworkService.queryDicListByType("START_STATUS");
//        List<Map<String, Object>> startStatusDicList = JSON.parseObject(startStatusDic.getData().toString(), new TypeReference<List<Map<String, Object>>>() {
//        });
//        // 库房类型，字典
//        ResultJSON storeTypeDic = frameworkService.queryDicListByType("STORE_TYPE");
//        List<Map<String, Object>> storeTypeDicList = JSON.parseObject(storeTypeDic.getData().toString(), new TypeReference<List<Map<String, Object>>>() {
//        });
//        List<Config> records = list.getRecords();
//        for (Config record : records) {
//            for (Map<String, Object> stringObjectMap : startStatusDicList) {
//                if (!ObjectUtils.isEmpty(record.getActiveStatus())) {
//                    if (record.getActiveStatus().equals(stringObjectMap.get("dicCode"))) {
//                        record.setActiveStatus(stringObjectMap.get("dicName").toString());
//                    }
//                }
//            }
//            for (Map<String, Object> stringObjectMap : storeTypeDicList) {
//                if (!ObjectUtils.isEmpty(record.getStoreType())) {
//                    if (record.getStoreType().equals(stringObjectMap.get("dicCode"))) {
//                        record.setStoreType(stringObjectMap.get("dicName").toString());
//                    }
//                }
//            }
//        }
        resultJSON = JSONTools.toResultJSON(list);
        return resultJSON;
    }

    // 根据 库房类型，库房
    @Override
    public ResultJSON queryAll(String params, Map<String, Object> map) {
        JSONObject jsonObject = JSON.parseObject(params);
        Page<Config> configPage = new Page<>();
        QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cancel_flag", "0");
        queryWrapper.orderByDesc("add_time");
        String storeNm = "";
        String activeStatus = "";
        String fId2 = "";
        String fId3 = "";
        String storeType = "";
//        IPage<Config> list = configMapper.selectPage(configPage, queryWrapper);
        if (!ObjectUtils.isEmpty(jsonObject)) {
            if (!ObjectUtils.isEmpty(jsonObject.get("activeStatus"))) {
                activeStatus = jsonObject.getString("activeStatus");
            }
            if (!ObjectUtils.isEmpty(jsonObject.get("storeNm"))) {
                storeNm = jsonObject.getString("storeNm");
            }
            if (!ObjectUtils.isEmpty(jsonObject.get("fId2"))) {
                fId2 = jsonObject.getString("fId2");
            }
            if (!ObjectUtils.isEmpty(jsonObject.get("fId3"))) {
                fId3 = jsonObject.getString("fId3");
            }
            if (!ObjectUtils.isEmpty(jsonObject.get("storeType"))) {
                storeType = jsonObject.getString("storeType");
            }
        }
//        IPage<Config> list = configMapper.selectPage(configPage, queryWrapper);
        Page<Config> autoPage = new Page<>();
        Page<Config> list = configMapper.selectAllFj(autoPage, fId2, fId3, activeStatus, storeNm, storeType);
        resultJSON = JSONTools.toResultJSON(list);
        return resultJSON;
    }

    @Override
    public ResultJSON queryAllKF(String params, Map<String, Object> map) {
        JSONObject jsonObject = JSON.parseObject(params);
        String fId = "";
        String storeType = "";
        String storeNm = "";
        String itemCd = "";
        Boolean ifItemKf = false;
        if (!ObjectUtils.isEmpty(jsonObject)) {
            if (!ObjectUtils.isEmpty(jsonObject.get("storeType"))) {
                storeType = jsonObject.getString("storeType");
            }
            if (!ObjectUtils.isEmpty(jsonObject.get("storeNm"))) {
                storeNm = jsonObject.getString("storeNm");
            }
            if (!ObjectUtils.isEmpty(jsonObject.get("itemCd"))) {
                itemCd = jsonObject.getString("itemCd");
            }
            if (!ObjectUtils.isEmpty(jsonObject.get("ifItemKf"))) {
                ifItemKf = Boolean.valueOf(jsonObject.getString("ifItemKf"));
            }
        }
        Page<Config> autoPage = new Page<>();
        Page<Config> list = new Page<>();
        if (ifItemKf == false){
            list = configMapper.selectAllKF(autoPage, storeType,storeNm);
        } else {
            list = configMapper.selectAllKFItem(autoPage, storeType,storeNm , itemCd);
        }
        resultJSON = JSONTools.toResultJSON(list);
        return resultJSON;
    }

    @Override
    public ResultJSON queryAllQH(String params, Map<String, Object> map) {
        JSONObject jsonObject = JSON.parseObject(params);
        String fId = "";
        String areaCd = "";
        if (!ObjectUtils.isEmpty(jsonObject)) {
            if (!ObjectUtils.isEmpty(jsonObject.get("fId"))) {
                fId = jsonObject.getString("fId");
            }
            if (!ObjectUtils.isEmpty(jsonObject.get("areaCd"))) {
                areaCd = jsonObject.getString("areaCd");
            }
        }
//        IPage<Config> list = configMapper.selectPage(configPage, queryWrapper);
        Page<Config> autoPage = new Page<>();
        Page<Config> list = configMapper.selectAllQH(autoPage, fId , areaCd);
        resultJSON = JSONTools.toResultJSON(list);
        return resultJSON;
    }

    @Override
    public ResultJSON queryAllDWH(String params, Map<String, Object> map) {
        JSONObject jsonObject = JSON.parseObject(params);
        String fId = "";
        String stackCd = "";
        if (!ObjectUtils.isEmpty(jsonObject)) {
            if (!ObjectUtils.isEmpty(jsonObject.get("fId"))) {
                fId = jsonObject.getString("fId");
            }
            if (!ObjectUtils.isEmpty(jsonObject.get("stackCd"))) {
                stackCd = jsonObject.getString("stackCd");
            }
        }
//        IPage<Config> list = configMapper.selectPage(configPage, queryWrapper);
        Page<Config> autoPage = new Page<>();
        Page<Config> list = configMapper.selectAllDWH(autoPage, fId , stackCd);
        resultJSON = JSONTools.toResultJSON(list);
        return resultJSON;
    }

    @Override
    public ResultJSON queryByPK(String id) {
//        Config config = configMapper.selectByPK(id);
        Config config = configMapper.selectAllById(id);
        resultJSON = JSONTools.toResultJSON(config);
        return resultJSON;
    }


    @Override
    public ResultJSON save(String userId, String json) {
        Date date = new Date();
        Config config = JSON.parseObject(json, new TypeReference<Config>() {
        });
        QueryWrapper<Config> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.eq("ID",config.getId());
        List<Config> configList = configMapper.selectList(configQueryWrapper);
        Config config1 = configList.get(0);
        config1.setStackCd(config.getStackCd());
        config1.setAreaCd(config.getAreaCd());
        config1.setStoreCd(config.getStoreCd());
        config1.setStoreNm(config.getStoreNm());
        config1.setStoreType(config.getStoreType());
        config1.setModifyId(userId);
        config1.setModifyTime(date);
        config1.setRemarks(config.getRemarks());


        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 (!ObjectUtils.isEmpty(user)) {
            config1.setModifyCode(user.getUserCode());
            config1.setModifyName(user.getUserDesc());
        }

        configMapper.updateById(config1);

        if (!ObjectUtils.isEmpty(config.getId1())) {
            // 库房
            config.setId(config.getId1());
            QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ID",config.getId1());
            List<Config> configs = configMapper.selectList(queryWrapper);
            Config con = configs.get(0);
            con.setStoreType(config.getStoreType());
            con.setStoreNm(config.getStoreNm());
            if (!ObjectUtils.isEmpty(user)) {
                con.setModifyCode(user.getUserCode());
                con.setModifyName(user.getUserDesc());
            }
            configMapper.updateById(con);
        }
        if (!ObjectUtils.isEmpty(config.getId2())) {
            // 区号
            QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ID",config.getId2());
            List<Config> configs = configMapper.selectList(queryWrapper);
            Config con = configs.get(0);

            con.setAreaCd(config.getAreaCd());
            if (!ObjectUtils.isEmpty(user)) {
                con.setModifyCode(user.getUserCode());
                con.setModifyName(user.getUserDesc());
            }
            configMapper.updateById(con);
        }


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

    @Override
    public ResultJSON insert(String userId, String json) {
        Date date = new Date();
        Config config = JSON.parseObject(json, new TypeReference<Config>() {
        });
        config.setCancelFlag("0");
        config.setAddId(userId);
        config.setAddTime(date);
        config.setActiveStatus("2");
        String kfId = "";
        String qhId = "";
        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 (ObjectUtils.isEmpty(config.getId1())) {
            // 库房
            Config configOne = new Config();
            configOne.setStoConfigLevel("1");
            configOne.setStoreType(config.getStoreType());
            configOne.setCancelFlag("0");
            configOne.setAddId(userId);
            configOne.setAddTime(date);
            configOne.setActiveStatus("2");
            configOne.setStoreNm(config.getStoreNm());
            if (!org.apache.commons.lang3.ObjectUtils.isEmpty(user)) {
                configOne.setAddCode(user.getUserCode());
                configOne.setAddName(user.getUserDesc());
            }
            if (!CollectionUtils.isEmpty(deptsList)) {
                configOne.setDeptCd(deptsList.get(0).getDeptCode());
                configOne.setAddDeptId(deptsList.get(0).getId());
                configOne.setAddDeptName(deptsList.get(0).getDeptName());
                configOne.setAddDeptCode(deptsList.get(0).getDeptCode());
            }
            if (!CollectionUtils.isEmpty(deptTreeList)) {
                configOne.setCompCd(deptTreeList.get(0).getDeptCode());
            }

            ResultJSON resultJSON12 = frameworkService.queryDeptTreeByUserId (userId);
            List<Map<String,Object>> list = JSON.parseObject(resultJSON12.getData().toString(), new TypeReference<List<Map<String,Object>>>() {});
            StringBuffer stringBuffer = new StringBuffer();
            if (!CollectionUtils.isEmpty(list)){
                stringBuffer.append(list.get(0).get("deptCode"));
            }
            // 库房编码   部门 +  5位流水
            String max = configMapper.getMax();
            if (!StringUtils.isEmpty(max)) {
                Integer i = Integer.valueOf(max) + 1;
                String string = i.toString();
                StringBuffer lsh = new StringBuffer();
                if (string.length() != 5) {
                    for (int j =0 ; j < 5- string.length() ; j++) {
                        lsh.append("0");
                    }
                }
                lsh.append(string);
                stringBuffer.append(lsh);
            } else {
                stringBuffer.append("00001");
            }
            configOne.setStoreCd(stringBuffer.toString());
            configMapper.insert(configOne);
            kfId = configOne.getId();
        } else {
            kfId = config.getId1();
        }
        if (ObjectUtils.isEmpty(config.getId2())) {
            // 区号
            Config configOne = new Config();
            configOne.setStoConfigLevel("2");
            configOne.setCancelFlag("0");
            configOne.setAddId(userId);
            configOne.setAddTime(date);
            configOne.setActiveStatus("2");
            configOne.setAreaCd(config.getAreaCd());
            configOne.setFId(kfId);
            if (!org.apache.commons.lang3.ObjectUtils.isEmpty(user)) {
                configOne.setAddCode(user.getUserCode());
                configOne.setAddName(user.getUserDesc());
            }
            if (!CollectionUtils.isEmpty(deptsList)) {
                configOne.setDeptCd(deptsList.get(0).getDeptCode());
                configOne.setAddDeptId(deptsList.get(0).getId());
                configOne.setAddDeptName(deptsList.get(0).getDeptName());
                configOne.setAddDeptCode(deptsList.get(0).getDeptCode());
            }
            if (!CollectionUtils.isEmpty(deptTreeList)) {
                configOne.setCompCd(deptTreeList.get(0).getDeptCode());
            }
            configMapper.insert(configOne);
            qhId = configOne.getId();
        } else {
            qhId = config.getId2();
        }
        // 垛位
        config.setStoConfigLevel("3");
        config.setFId(qhId);
        config.setId(null);
        if (!org.apache.commons.lang3.ObjectUtils.isEmpty(user)) {
            config.setAddCode(user.getUserCode());
            config.setAddName(user.getUserDesc());
        }
        if (!CollectionUtils.isEmpty(deptsList)) {
            config.setDeptCd(deptsList.get(0).getDeptCode());
            config.setAddDeptId(deptsList.get(0).getId());
            config.setAddDeptName(deptsList.get(0).getDeptName());
            config.setAddDeptCode(deptsList.get(0).getDeptCode());
        }
        if (!CollectionUtils.isEmpty(deptTreeList)) {
            config.setCompCd(deptTreeList.get(0).getDeptCode());
        }
        configMapper.insert(config);


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

    @Override
    public ResultJSON remove(String userId, String id) {
        Date date = new Date();
        Config config = configMapper.selectById(id);
        config.setCancelFlag("1");
        config.setCancelId(userId);
        config.setCancelTime(date);
        configMapper.updateById(config);
        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>>() {
        });
        Config config;
        for (String id : list) {
            config = configMapper.selectById(id);
            config.setCancelFlag("1");
            config.setCancelId(userId);
            config.setCancelTime(date);
            configMapper.updateById(config);
        }
        resultJSON = JSONTools.toResultJSON("");
        return resultJSON;
    }

    @Override
    public ResultJSON startAndShutDown(String userId, String ids, String status) {
        Date date = new Date();
        List<String> list = JSON.parseObject(ids, new TypeReference<List<String>>() {
        });
        Config partner;
        for (String id : list) {
            partner = configMapper.selectById(id);
            partner.setCancelId(userId);
            partner.setCancelTime(date);
            partner.setActiveStatus(status);
            configMapper.updateById(partner);
        }
        resultJSON = JSONTools.toResultJSON("");
        return resultJSON;
    }

}
