package com.ruoyi.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.domain.CheckTaskInfo;
import com.ruoyi.api.domain.InStoreDto;
import com.ruoyi.api.domain.OutStoreDto;
import com.ruoyi.api.domain.StockDto;
import com.ruoyi.api.service.impl.ApiService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;

import static com.ruoyi.common.core.domain.AjaxResult.*;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.manage.domain.*;
import com.ruoyi.manage.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;


/**
 * @author wanghao
 * @date 2024/1/11  8:55
 */
@RestController
@RequestMapping("/api")
public class ApiController {
    @Autowired
    private IBaseLocationService baseLocationService;
    @Autowired
    private IBaseManufacturerService baseManufacturerService;
    @Autowired
    private ApiService apiService;

    //入库
    // 查询库位 和 品牌
    @PostMapping("/instore/select")
    public AjaxResult instoreSelect() {
        BaseLocation baseLocation = new BaseLocation();
        baseLocation.setStoteTag(1L);
        baseLocation.setIsEnable("Y");
        List<BaseLocation> baseLocationList = baseLocationService.selectBaseLocationList(baseLocation);
        BaseManufacturer baseManufacturer = new BaseManufacturer();
        baseManufacturer.setIsEnable("Y");
        List<BaseManufacturer> baseManufacturerList = baseManufacturerService.selectBaseManufacturerList(baseManufacturer);
        Map<String, List> map = new HashMap<>();
        map.put("baseLocationList", baseLocationList);
        map.put("baseManufacturerList", baseManufacturerList);
        return success(map);
    }

    @PostMapping("/instore/submit")
    public AjaxResult instoreSubmit(@RequestBody InStoreDto inStore) {
        List<String> epcList = inStore.getEpcList();
        int size = epcList.size();
        System.out.println("数据条数：" + size);
        Iterator<String> iterator = epcList.iterator();
        while (iterator.hasNext()) {
            String epc = iterator.next();
            String tag = apiService.selectLedgerbyEpcForInStore(epc);
            if (tag != null) {
                iterator.remove();
            }
        }
        int size1 = epcList.size();
        int i = size - size1;
        if (size1 > 0) {
            apiService.submintInsertRecordIn(inStore);
            apiService.submintInsertLedger(inStore);
        }


        return success("本次入库成功：" + size1 + "条,屏蔽重复入库：" + i + "条");
    }


    @PostMapping("/outStore/select")
    public AjaxResult outStoreSelect() {
        BaseLocation baseLocation = new BaseLocation();
        baseLocation.setStoteTag(2L);
        baseLocation.setIsEnable("Y");
        List<BaseLocation> baseLocationList = baseLocationService.selectBaseLocationList(baseLocation);
        return success(baseLocationList);
    }

    @PostMapping("/outStore/submit")
    public AjaxResult outStoreSubmit(@RequestBody OutStoreDto outStoreDto) {
        try {
            List<String> epcList = outStoreDto.getEpcList();
            //int i=0;
            for (String epc : epcList) {
                String tag = apiService.selectLedgerbyEpcForOutStore(epc);
                if (tag != null) {
                    apiService.submitInsertRecordOut(outStoreDto, epc);
                    apiService.updataLedgerFoyOut(outStoreDto, epc);
                    //i++;
                }

            }


          /*   int size = epcList.size();
            Iterator<String> iterator = epcList.iterator();
            while (iterator.hasNext()) {
                String epc = iterator.next();

                if (tag != null) {
                    iterator.remove();
                }
            }
            int size1 = epcList.size();
            int i = size - size1;
            if (i>0){
                apiService.submitInsertRecordOut(outStoreDto);
                apiService.updataLedger(outStoreDto);
            }*/

            return success();
        } catch (Exception e) {
            return error();
        }

    }

    @PostMapping("/storecheck/select")
    public AjaxResult storeCheckSelect() {
        List<StockDto> list = apiService.storeCheckSelect();
        if (list == null || list.isEmpty()) {
            return error("库存为空");
        }
        return success(list);
    }

    @Autowired
    private IRecordStoreCheckService checkService;

    @Transactional
    @PostMapping("/storecheck/submit")
    public AjaxResult storeCheckSubmit(String json, String user) {
        try {
            List<StockDto> list = JSONObject.parseArray(json, StockDto.class);
            RecordStoreCheck recordStoreCheck = new RecordStoreCheck();
            recordStoreCheck.setCheckNumber(list.size());
            recordStoreCheck.setCheckTime(DateUtils.getNowDate());
            recordStoreCheck.setCheckUser(user);
            int key = checkService.insertRecordStoreCheck(recordStoreCheck);
            apiService.insertCheckInfo(list, recordStoreCheck.getCheckId());
            return success();
        } catch (Exception e) {
            return error("数据异常,请求失败");
        }

    }


    @PostMapping("/bf/select")
    public AjaxResult bfSelect(String epc) {
        LedgerRfid ledgerRfid = apiService.bfSelect(epc);
        if (ledgerRfid == null) {
            return error("RFID 扫描不正确");
        }
        return success(ledgerRfid);
    }

    @Autowired
    private IRecordInvalidatedService recordInvalidatedService;



    @PostMapping("/xj/selectLite")
    public String xjSelectLite(String user) {
        List<StockDto> list = apiService.xjSelect(user);
        if (list == null) {
            return "null";
        }
        return JSONObject.toJSONString(list);
    }

    @Autowired
    private IRecordInspectionService inspectionService;

    @PostMapping("/xj/submit")
    public AjaxResult inspectionSubmit(long tableId, String json, long inspectionId, String user,List<MultipartFile> files) {
        //插入 info 表
        List<StockDto> list = JSONObject.parseArray(json, StockDto.class);
        apiService.insertInspectionInfo(list, inspectionId);
        //修改task状态
        apiService.updataInspectionTaskByObjid(tableId);

        //存储图片，插库
        String filePath = RuoYiConfig.getUploadPath() + "/inspection";
        if (files != null && files.size() > 0) {
            for (MultipartFile multipartFile : files) {
                String pathName = null;
                try {
                    pathName = FileUploadUtils.upload(filePath, multipartFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("上传图片路径：" + pathName);
                apiService.insertInspetionPictrue(inspectionId, tableId,user, pathName);
            }
        }

        return success();

    }

    /**
     * 查询巡检机位
     *
     * @param user
     * @return
     */
    @PostMapping("/inspection/selectTask")
    public AjaxResult inspectionSelectTask(String user) {
        List<CheckTaskInfo> list = apiService.inspectionSelectTask(user);
        if (list == null || list.isEmpty()) {
            return error("需要创建");
        }
        return success(list);
    }

    /**
     * 根据机位查询轮挡
     *
     * @param
     * @return
     */
    @PostMapping("/inspection/select")
    public AjaxResult inspectionSelect(String code) {
        List<StockDto> list = apiService.inspectionSelectLocation(code);
        if (list == null) {
            return error("没有领用轮挡");
        }
        return success(list);
    }

    /**
     * 创建巡检机位列表和巡检任务
     *
     * @param user
     * @return
     */
    @PostMapping("/xj/createTask")
    public AjaxResult inspectionCreateTask(String user) {
        List<CheckTaskInfo> list = apiService.selectLocationByAreaUser(user);
        if (list == null || list.isEmpty()) {
            return error("没有维护巡检区域");
        }
        RecordInspection recordInspection = new RecordInspection();
        recordInspection.setInspectionUser(user);
        int insertNumber = inspectionService.insertRecordInspection(recordInspection);
        apiService.insertCheckTask(Math.toIntExact(recordInspection.getInspectionId()), list);
        return success("创建成功", insertNumber);

    }
    /**
     * 轮挡报废
     * @param epc
     * @param user
     * @param remark
     * @return
     */
    @PostMapping("/bf/submit")
    public AjaxResult bfSubmit(String epc, String reason,String user, String remark,List<MultipartFile> files) {
        //插入记录
        RecordInvalidated recordInvalidated = new RecordInvalidated();
        recordInvalidated.setEpc(epc);
        recordInvalidated.setCreateBy(user);
        recordInvalidated.setRemark(remark);
        recordInvalidatedService.insertRecordInvalidated(recordInvalidated);
        //

        //修改台账
        apiService.updataLedgerForBf(epc, "2");

        //存储图片，插库
        String filePath = RuoYiConfig.getUploadPath() + "/inspection";
        if (files != null && files.size() > 0) {
            for (MultipartFile multipartFile : files) {
                String pathName = null;
                try {
                    pathName = FileUploadUtils.upload(filePath, multipartFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("上传图片路径：" + pathName);
                apiService.insertBfImg(recordInvalidated.getObjid(),epc,user, pathName);
            }
        }

        return success();
    }

    @PostMapping("/fpin/select")
    public AjaxResult fpInSelect(String epc) {
        LedgerRfid ledgerRfid = apiService.fpInSelect(epc);
        if (ledgerRfid == null) {
            return error("RFID 扫描不正确");
        }
        BaseLocation baseLocation = new BaseLocation();
        baseLocation.setStoteTag(1L);
        baseLocation.setIsEnable("Y");
        List<BaseLocation> baseLocationList = baseLocationService.selectBaseLocationList(baseLocation);
        ledgerRfid.setBaseLocationList(baseLocationList);
        return success(ledgerRfid);
    }

    @PostMapping("/fpin/submit")
    public AjaxResult fpInSubmit(String epc, String localtionCode, String user, String bf, String subCode) {
        int i = apiService.fpInSubmit(epc, localtionCode, user, bf, subCode);
        apiService.updataLedgerIn(epc, subCode);
        return success();
    }

    @PostMapping("/fpout/select")
    public AjaxResult fpOutSelect() {
        List<StockDto> list = apiService.fpOutSelect();
        if (list == null || list.isEmpty()) {
            return error("暂无废品库存");
        }
        return success(list);
    }

    @PostMapping("/fpout/submit")
    public AjaxResult fpoutSubmit(String json, String user) {
        try {
            List<StockDto> list = JSONObject.parseArray(json, StockDto.class);
            apiService.insertWasreOutRecord(list, user);
            apiService.updataLedgerForWasreOut(list, user);
            return success();
        } catch (Exception e) {
            return error();
        }

    }
}
