package com.ruoyi.web.controller.storageLocation;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.redis.RedisLock;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.storageLocation.domain.Operlog;
import com.ruoyi.storageLocation.domain.StorageLocation;
import com.ruoyi.storageLocation.domain.StorageSelected;
import com.ruoyi.storageLocation.service.StorageLocationService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 库位管理Controller
 */
@RestController
@RequestMapping("/storageLocation/storageLocation")
@DataSource(DataSourceType.STORAGE)
public class storageLocationController extends BaseController
{

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private StorageLocationService storageLocationService;

    @Autowired
    private ISysConfigService configService;

    /*===========================================库位设置==========================================================*/
    /**
     * 获取库位占用信息
     */
    @GetMapping("/list")
    public AjaxResult list(StorageLocation storageLocation)
    {
        AjaxResult ajaxResult = new AjaxResult();
        String user_name = getLoginUser().getUsername();//当前登陆者
        List<StorageLocation> listA = storageLocationService.selectStorageLocationAList(storageLocation);
        List<StorageLocation> listB = storageLocationService.selectStorageLocationBList(storageLocation);
        List<StorageLocation> listC = storageLocationService.selectStorageLocationCList(storageLocation);

        ajaxResult.put("materialDetailA",listA);
        ajaxResult.put("materialDetailB",listB);
        ajaxResult.put("materialDetailC",listC);

        //根据库位状态 同步更新库位占用缓存-刷新页面时用
        for(StorageLocation sl:listA){
            String materialBh = sl.getMaterialBh();
            String materialState = sl.getMaterialState();
            String kw_user_name = redisCache.getCacheObject(getLocationZyCacheKey(materialBh));
            if("0".equals(materialState)){
                if(StringUtils.isNotNull(kw_user_name)&&user_name.equals(kw_user_name)){
                    redisCache.deleteObject(getLocationZyCacheKey(materialBh));
                }
            }
        }
        for(StorageLocation sl:listB){
            String materialBh = sl.getMaterialBh();
            String materialState = sl.getMaterialState();
            String kw_user_name = redisCache.getCacheObject(getLocationZyCacheKey(materialBh));
            if("0".equals(materialState)){
                if(StringUtils.isNotNull(kw_user_name)&&user_name.equals(kw_user_name)){
                    redisCache.deleteObject(getLocationZyCacheKey(materialBh));
                }
            }
        }
        for(StorageLocation sl:listC){
            String materialBh = sl.getMaterialBh();
            String materialState = sl.getMaterialState();
            String kw_user_name = redisCache.getCacheObject(getLocationZyCacheKey(materialBh));
            if("0".equals(materialState)){
                if(StringUtils.isNotNull(kw_user_name)&&user_name.equals(kw_user_name)){
                    redisCache.deleteObject(getLocationZyCacheKey(materialBh));
                }
            }
        }
        return ajaxResult;
    }

    /**
     * 录入库位信息
     */
    @Log(title = "录入库位信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StorageLocation storageLocation)
    {
        String user_name = getLoginUser().getUsername();//当前登陆者
        String materialBh = storageLocation.getMaterialBh();

        String kw_user_name = redisCache.getCacheObject(getLocationZyCacheKey(materialBh));
        if(StringUtils.isNull(kw_user_name)){
            return error("已超过有效录入信息时间，请关闭重新录入!");
        }else if(!user_name.equals(kw_user_name)){
            return error("已超过有效录入信息时间，当前库位有人正在操作!");
        }else{
            redisCache.setCacheObject(getLocationZyCacheKey(materialBh),user_name);
            redisCache.deleteObject(getLocationLyCacheKey(materialBh));

            //插入操作记录表
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Operlog operlog = new Operlog();
            operlog.setOperlog_user_name(user_name);
            operlog.setOperlog_date(format.format(new Date()));
            operlog.setOperlog_event("录入库位信息");
            operlog.setOperlog_kw(storageLocation.getMaterialBh());
            operlog.setOperlog_zlh(storageLocation.getMaterialZlh());
            operlog.setOperlog_xingh(storageLocation.getMaterialXingh());
            operlog.setOperlog_guig(storageLocation.getMaterialGuig());
            operlog.setOperlog_diany(storageLocation.getMaterialDiany());
            operlog.setOperlog_ms(storageLocation.getMaterialMs());

            storageLocationService.addOperlog(operlog);
            return toAjax(storageLocationService.addStorageLocation(storageLocation));
        }

    }

    /**
     * 校验库位是否已占用
     */
    @Log(title = "校验库位是否已占用", businessType = BusinessType.OTHER)
    @PostMapping("/checkStorageLocation")
    public AjaxResult checkStorageLocation(@RequestBody StorageLocation storageLocation)
    {
        String storageExpire = configService.selectConfigByKey("storage.expire.zy");

        String user_name = getLoginUser().getUsername();//当前登陆者
        String materialBh = storageLocation.getMaterialBh();

        String kw_user_name = redisCache.getCacheObject(getLocationZyCacheKey(materialBh));
        if(StringUtils.isNotNull(kw_user_name)&&!user_name.equals(kw_user_name)){
            return error("当前库位有人正在操作,请勿操作!");
        }else{
            redisLock.getLock(getLocationZyCacheKey(materialBh), Integer.valueOf(storageExpire), user_name);
            //redisCache.setCacheObject(getLocationZyCacheKey(materialBh),user_name,Integer.valueOf(storageExpire), TimeUnit.SECONDS);
            return success();
        }
    }

    /**
     * 弹窗取消按钮 清除库位缓存
     */
    @Log(title = "校验库位是否已占用", businessType = BusinessType.OTHER)
    @PostMapping("/cancelStorageLocation")
    public AjaxResult cancelStorageLocation(@RequestBody StorageLocation storageLocation)
    {
        String user_name = getLoginUser().getUsername();//当前登陆者
        String materialBh = storageLocation.getMaterialBh();

        String kw_user_name = redisCache.getCacheObject(getLocationZyCacheKey(materialBh));
        if(StringUtils.isNotNull(kw_user_name)&&user_name.equals(kw_user_name)){
            redisCache.deleteObject(getLocationZyCacheKey(materialBh));
        }
        return success();
    }
    /*===========================================库位设置==========================================================*/

    /*===========================================库位领用==========================================================*/
    /**
     * 获取库位领用信息
     */
    @GetMapping("/lyList")
    public AjaxResult lyList(StorageLocation storageLocation)
    {
        AjaxResult ajaxResult = new AjaxResult();
        String user_name = getLoginUser().getUsername();//当前登陆者
        List<StorageLocation> listA = storageLocationService.selectStorageLocationAList(storageLocation);
        List<StorageLocation> listB = storageLocationService.selectStorageLocationBList(storageLocation);
        List<StorageLocation> listC = storageLocationService.selectStorageLocationCList(storageLocation);

        ajaxResult.put("materialDetailA",listA);
        ajaxResult.put("materialDetailB",listB);
        ajaxResult.put("materialDetailC",listC);

        // 读取已选列表
        List<StorageLocation> selectedListA = storageLocationService.selectStorageSelectedLocationAList(user_name);
        List<StorageLocation> selectedListB = storageLocationService.selectStorageSelectedLocationBList(user_name);
        List<StorageLocation> selectedListC = storageLocationService.selectStorageSelectedLocationCList(user_name);

        ajaxResult.put("selMaterialDetailA",selectedListA);
        ajaxResult.put("selMaterialDetailB",selectedListB);
        ajaxResult.put("selMaterialDetailC",selectedListC);

        // 读取全部已选列表
        List<StorageSelected> selectedList = storageLocationService.selectStorageSelectedLocationList();

        for(StorageSelected sl:selectedList){
            String materialBh = sl.getMaterial_bh();
            String userName = sl.getUser_name();
            redisCache.setCacheObject(getLocationLyCacheKey(materialBh),userName);//缓存keys丢失，重新设置缓存key
        }
        return ajaxResult;
    }

    /**
     * 校验库位是否被领用
     */
    @Log(title = "校验库位是否被领用", businessType = BusinessType.OTHER)
    @PostMapping("/checklyStorageLocation")
    public AjaxResult checklyStorageLocation(@RequestBody StorageLocation storageLocation)
    {

        String user_name = getLoginUser().getUsername();//当前登陆者
        String materialBh = storageLocation.getMaterialBh();

        String kw_user_name = redisCache.getCacheObject(getLocationLyCacheKey(materialBh));
        if(StringUtils.isNotNull(kw_user_name)&&!user_name.equals(kw_user_name)){
            return error("该库位当前有人正在领用操作,请勿操作!");
        }else{
            // 判断已选库位表是否存在库位信息
            StorageSelected storageSelected = storageLocationService.hasStorageLocation(materialBh);
            if(storageSelected!=null){
                if(!user_name.equals(storageSelected.getUser_name())){
                    return error("该库位当前有人正在领用操作,请勿操作!");
                }else{
                    return error("该库位已被选择领用,请勿重复操作!");
                }
            }else{
                // 保存至已选库位表并缓存
                Boolean lock = redisLock.getLock(getLocationLyCacheKey(materialBh), -1, user_name);
                if(lock){
                    storageLocationService.saveStorageLocation(user_name,materialBh);
                }
            }
            return success();
        }
    }

    /**
     * 清除库位领用缓存
     */
    @Log(title = "清除库位领用缓存", businessType = BusinessType.OTHER)
    @PostMapping("/clearLocationLyCacheKey")
    public AjaxResult clearLocationLyCacheKey(@RequestBody StorageLocation storageLocation)
    {
        String user_name = getLoginUser().getUsername();//当前登陆者
        String materialBh = storageLocation.getMaterialBh();

        String kw_user_name = redisCache.getCacheObject(getLocationLyCacheKey(materialBh));
        if(StringUtils.isNotNull(kw_user_name)&&user_name.equals(kw_user_name)){
            redisCache.deleteObject(getLocationLyCacheKey(materialBh));
        }

        //批量插入操作记录表
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = format.format(new Date());
        //查询已选库位信息
        List<String> materialBhList = new ArrayList<String>();
        materialBhList.add(materialBh);
        List<StorageLocation> selectedList = storageLocationService.selectStorageLocation(user_name,materialBhList);

        List<Operlog> operlogList = new ArrayList<Operlog>();
        Operlog operlog = new Operlog();
        for(StorageLocation sl:selectedList){
            operlog = new Operlog();
            operlog.setOperlog_user_name(user_name);
            operlog.setOperlog_date(date);
            operlog.setOperlog_event("删除已选库位信息");
            operlog.setOperlog_kw(sl.getMaterialBh());
            operlog.setOperlog_zlh(sl.getMaterialZlh());
            operlog.setOperlog_xingh(sl.getMaterialXingh());
            operlog.setOperlog_guig(sl.getMaterialGuig());
            operlog.setOperlog_diany(sl.getMaterialDiany());
            operlog.setOperlog_ms(sl.getMaterialMs());
            operlogList.add(operlog);
        }
        storageLocationService.addBatchOperlog(operlogList);
        storageLocationService.deleteStorageLocation(user_name,materialBh);
        return success();
    }

    /**
     * 确认完成认领
     */
    @Log(title = "确认完成领用", businessType = BusinessType.OTHER)
    @PostMapping("/confirmStorageLocation")
    public AjaxResult confirmStorageLocation(@RequestBody String [] materialBhArr)
    {
        String user_name = getLoginUser().getUsername();//当前登陆者
        List<String> materialBhList = Arrays.asList(materialBhArr);
        //批量插入操作记录表
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = format.format(new Date());
        //查询已选库位信息
        List<StorageLocation> selectedList = storageLocationService.selectStorageLocation(user_name,materialBhList);
        List<Operlog> operlogList = new ArrayList<Operlog>();
        Operlog operlog = new Operlog();
        for(StorageLocation sl:selectedList){
            operlog = new Operlog();
            operlog.setOperlog_user_name(user_name);
            operlog.setOperlog_date(date);
            operlog.setOperlog_event("确认完成领用");
            operlog.setOperlog_kw(sl.getMaterialBh());
            operlog.setOperlog_zlh(sl.getMaterialZlh());
            operlog.setOperlog_xingh(sl.getMaterialXingh());
            operlog.setOperlog_guig(sl.getMaterialGuig());
            operlog.setOperlog_diany(sl.getMaterialDiany());
            operlog.setOperlog_ms(sl.getMaterialMs());
            operlogList.add(operlog);
        }
        storageLocationService.addBatchOperlog(operlogList);

        //删除已选库位信息
        storageLocationService.deleteBatchStorageLocation(user_name,materialBhList);
        //更新库位状态 -空闲
        storageLocationService.confirmStorageLocation(materialBhList);
        //删除占用缓存
        for(String materialBh:materialBhArr){
            redisCache.deleteObject(getLocationZyCacheKey(materialBh));// 清空占用缓存keys
        }
        return success();
    }

    /*===========================================库位领用==========================================================*/

    /*===========================================操作记录==========================================================*/
    /**
     * 获取操作记录
     */
    @GetMapping("/listOperlog")
    public AjaxResult listOperlog(Operlog operlog)
    {
        AjaxResult ajaxResult = new AjaxResult();
        List<Operlog> operlogData = storageLocationService.selectOperlogs(operlog);
        ajaxResult.put("operlogData",operlogData);
        return ajaxResult;
    }
    /*===========================================操作记录==========================================================*/

    /**
     * 库位占用缓存键名
     *
     * @param materialBh 库位号
     * @return 缓存键key
     */
    private String getLocationZyCacheKey(String materialBh)
    {
        return CacheConstants.STORAGE_LOCATION + materialBh + "-ZY";
    }

    /**
     * 库位领用缓存键名
     *
     * @param materialBh 库位号
     * @return 缓存键key
     */
    private String getLocationLyCacheKey(String materialBh)
    {
        return CacheConstants.STORAGE_LOCATION + materialBh + "-LY";
    }

}
