package com.zd.airbottle.controller;

import com.alibaba.fastjson.JSONObject;
import com.zd.airbottle.domain.QpBottleStorage;
import com.zd.airbottle.domain.QpSupplier;
import com.zd.airbottle.domain.QpTaskDetail;
import com.zd.airbottle.domain.vo.*;
import com.zd.airbottle.domain.vo.report.AirAmount;
import com.zd.airbottle.service.*;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.poi.ExcelUtil;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.web.domain.ResultData;
import com.zd.common.core.web.page.TableDataInfo;
import com.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.security.service.TokenService;
import com.zd.system.api.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 气瓶入库Controller
 *
 * @author zd
 * @date 2022-05-19
 */
@RestController
@Api(tags = "【气瓶入库】")
//作者手动加入 ，在接口上加作者@ApiOperationSupport(author = "XXX")
// @ApiSupport(author = Knife4jConfiguration.Author.)
@RequestMapping("/storage")
public class QpBottleStorageController extends BaseController {
    @Autowired
    private IQpBottleStorageService qpBottleStorageService;

    @Autowired
    private IQpTaskService qpTaskService;

    @Autowired
    private IQpBottleStorageOutService qpBottleStorageOutService;

    @Autowired
    private IQpTaskDetailService qpTaskDetailService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IQpSupplierService qpSupplierService;

    @Autowired
    private IQpRfidTagService qpRfidTagService;
    /**
     * 查询气瓶入库列表
     */
    //@PreAuthorize(hasPermi = "airbottle:storage:list")
    @GetMapping("/list")
    @ApiOperation(value = "查询气瓶入库列表")
    public TableDataInfo<QpBottleStorageVO> list(QpBottleStorageVO qpBottleStorage) {
        startPage();
        List<QpBottleStorageVO> list = qpBottleStorageService.selectQpBottleStorageList(qpBottleStorage);
        return getDataTable(list);
    }

    /**
     * 信息统计查询气瓶入库列表
     */
    //@PreAuthorize(hasPermi = "airbottle:storage:list")
    @GetMapping("/info/list")
    @ApiOperation(value = "信息统计查询气瓶入库列表")
    public TableDataInfo<BottleStorageInfoVo> infoList(BottleStorageInfoVo storageInfoVo) {
        startPage();
        List<BottleStorageInfoVo> list = qpBottleStorageService.getStorageInfoList(storageInfoVo);
        return new TableDataInfo<BottleStorageInfoVo>().getDataTable(list);
    }

    /**
     * 导出气瓶入库列表
     */
    @ApiOperation(value = "导出气瓶入库列表")
    //@PreAuthorize(hasPermi = "airbottle:storage:export")
    @Log(title = "气瓶入库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QpBottleStorageVO qpBottleStorage) throws IOException {
        List<QpBottleStorageVO> list = qpBottleStorageService.selectQpBottleStorageList(qpBottleStorage);
        ExcelUtil<QpBottleStorageVO> util = new ExcelUtil<>(QpBottleStorageVO.class);
        util.exportExcel(response, list, "气瓶入库数据");
    }

    /**
     * 根据电子标签查询气瓶入库相关信息
     */
    @ApiOperation(value = "根据电子标签查询气瓶入库相关信息")
    @GetMapping(value = "/get/electronicTag")
    public ResultData<QpBottleStorageRVo> getByElectronicTag(String electronicTag) {
        return ResultData.success(qpBottleStorageService.getByElectronicTag(electronicTag));
    }

    /**
     * 气瓶库存统计
     */
    @ApiOperation(value = "气瓶库存统计")
//    @PreAuthorize(hasPermi = "airbottle:storage:query")
    @GetMapping(value = "/calc/storage")
    public ResultData<List<AirAmount>> calcStorage(String airName) {
        return ResultData.success(qpBottleStorageService.calcStorage(airName));
    }

    /**
     * 楼栋库存统计
     */
    @ApiOperation(value = "楼栋库存统计")
//    @PreAuthorize(hasPermi = "airbottle:storage:query")
    @GetMapping(value = "/calc/build")
    public ResultData<List<AirAmount>> calcBuild(String airName) {
        return ResultData.success(qpBottleStorageService.calcBuildStorage(airName));
    }

    /**
     * 实验室库存排名统计
     */
    @ApiOperation(value = "实验室库存排名统计")
//    @PreAuthorize(hasPermi = "airbottle:storage:query")
    @GetMapping(value = "/calc/location")
    public ResultData<List<AirAmount>> calcLocation(String airName) {
        return ResultData.success(qpBottleStorageService.calcLocationStorage(airName));
    }

    /**
     * 获取气瓶入库详细信息
     */
    @ApiOperation(value = "获取气瓶入库详细信息")
    //@PreAuthorize(hasPermi = "airbottle:storage:query")
    @GetMapping(value = "/getInfo")
    public ResultData<QpBottleStorageVO> getInfo(Long id) {
        return ResultData.success(qpBottleStorageService.selectQpBottleStorageById(id));
    }


    /**
     * 新增气瓶入库
     */
    @ApiOperation(value = "新增气瓶入库")
    //@PreAuthorize(hasPermi = "airbottle:storage:add")
    @Log(title = "气瓶入库", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultData<Boolean> add(@RequestBody QpBottleStorageVO qpBottleStorage) {
        return ResultData.result(qpBottleStorageService.insertQpBottleStorage(qpBottleStorage));
    }

    /**
     * 修改气瓶入库
     */
    @ApiOperation(value = "修改气瓶入库")
    //@PreAuthorize(hasPermi = "airbottle:storage:edit")
    @Log(title = "气瓶入库", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultData<Boolean> edit(@RequestBody QpBottleStorage qpBottleStorage) {
        return ResultData.result(qpBottleStorageService.updateQpBottleStorage(qpBottleStorage));
    }

    /**
     * 删除气瓶入库
     */
    @ApiOperation(value = "删除气瓶入库")
    //@PreAuthorize(hasPermi = "airbottle:storage:remove")
    @Log(title = "气瓶入库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public ResultData<Boolean> remove(@PathVariable Long[] ids) {
        return ResultData.result(qpBottleStorageService.deleteQpBottleStorageByIds(ids));
    }

    /**
     * 根据待办清单id查询
     */
    @ApiOperation(value = "数据集合查询")
    @GetMapping(value = "/getTaskInfo")
    public AjaxResult getTaskInfo(Long id) {
        Map<String, Object> map = new HashMap<>();

        //入库信息查询
        QpBottleStorageVO bottleStorageVO = qpBottleStorageService.selectQpBottleStorageById(id);
        map.put("bottleStorage", bottleStorageVO);

        QpBottleStorageOutVO outvo = new QpBottleStorageOutVO();
        outvo.setStorageId(bottleStorageVO.getId());
        List<QpBottleStorageOutVO> outVOList = qpBottleStorageOutService.selectQpBottleStorageOutList(outvo);
        map.put("storageOut", !outVOList.isEmpty()?outVOList.get(0):outvo);


        QpTaskDetail taskDetail = new QpTaskDetail();
        taskDetail.setTaskId(bottleStorageVO.getTaskId());
        taskDetail.setId(bottleStorageVO.getTaskDetailId());
        List<QpTaskDetail> detailList =  qpTaskDetailService.selectQpTaskDetailList(taskDetail);
        map.put("detailList", detailList.size()>0?detailList.get(0):taskDetail);
        /*if(outVOList.size()>0 && StringUtils.isNotNull(outVOList.get(0).getTransportId())){
            //人员详情
            QpTransportUserVo user = qpTransportUserService.selectQpTransportUserById(outVOList.get(0).getTransportId());
            map.put("user", user);
        }

        if(StringUtils.isNotNull(task.getCarId())){
            //车辆详情
            QpTransportCarVo carvo = qpTransportCarService.selectQpTransportCarById(task.getCarId());
            map.put("car", carvo);
        }*/

        return AjaxResult.success(map);
    }

    /**
     * 电子标签解绑
     * @param id
     * @return
     */
    @ApiOperation(value = "电子标签解绑")
    //@PreAuthorize(hasPermi = "airbottle:storage:edit")
    @Log(title = "电子标签解绑", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unbind")
    public ResultData<Boolean> unbind(Long id) {
        return ResultData.result(qpBottleStorageService.bottleStorageUnbind(id));
    }

    @ApiOperation(value = "电子标签绑定")
    //@PreAuthorize(hasPermi = "airbottle:storage:edit")
    @Log(title = "电子标签绑定", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/binding")
    public ResultData<Boolean> binding(QpBottleStorage qpBottleStorage) {
        return ResultData.result(qpBottleStorageService.bottleStorageBinding(qpBottleStorage));
    }

    /***
     * 供应商首页待办事项列表
     * @param storageInfoVo
     * @return
     */
    @GetMapping("/listTaskIndex")
    @ApiOperation(value = "供应商首页待办事项列表")
    public TableDataInfo<QpBottleStorageVO> listTaskIndex(QpBottleStorageVO storageInfoVo)
    {
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        QpSupplier supplier = qpSupplierService.selectQpSupplierByAccountId(sysUser.getUserId());
        if(supplier==null){
            throw  new ServiceException("未查询到相关人员信息");
        }
        startPage();
        storageInfoVo.setCompanyId(supplier.getId());//供应商id
        List<QpBottleStorageVO> list = qpBottleStorageService.selectQpTaskListIndex(storageInfoVo);
        for (int i=0;i<list.size();i++){

            QpTaskVO task =   qpTaskService.selectQpTaskById(list.get(i).getTaskId());
            list.get(i).setCampus(task.getCampus());//校区
            list.get(i).setBuilding(task.getBuilding());//楼栋
            list.get(i).setRoom(task.getRoom());//房间号

            if("gq".equals(list.get(i).getRemark())){
                QpTaskDetail qpTaskDetail = new QpTaskDetail();
                qpTaskDetail.setTaskId(list.get(i).getTaskId());
                qpTaskDetail.setSupplierId(supplier.getId());
                qpTaskDetail.setIsDispose(0L);
                List<QpTaskDetailVO> detailListVo =  qpTaskDetailService.selectQpTaskDetailListVo(qpTaskDetail);
                if(detailListVo.size()>0){
                    for (int j=0;j<detailListVo.size();j++){
                        JSONObject jsonStr = JSONObject.parseObject(detailListVo.get(j).getApplyDescribe());
                        detailListVo.get(j).setConfigName(jsonStr.get("gasLevel").toString());
                        detailListVo.get(j).setAirName(jsonStr.get("airName").toString());
                    }
                }
                list.get(i).setDetailListVO(detailListVo);
            }else if("wt".equals(list.get(i).getRemark()) || "hs".equals(list.get(i).getRemark())){
                    QpTaskDetail qpTaskDetail = new QpTaskDetail();
                    qpTaskDetail.setTaskId(list.get(i).getTaskId());
                    qpTaskDetail.setId(list.get(i).getTaskDetailId());
                    qpTaskDetail.setSupplierId(supplier.getId());
                    List<QpTaskDetail> detailList =  qpTaskDetailService.selectQpTaskDetailList(qpTaskDetail);
                    JSONObject jsonStr = JSONObject.parseObject(detailList.get(0).getApplyDescribe());
                    list.get(i).setConfigName(jsonStr.get("gasLevel").toString());
                    list.get(i).setAirName(jsonStr.get("airName").toString());
                    list.get(i).setBottleNumber(detailList.get(0).getBottleNumber());
            }
        }
        return getDataTable(list);
    }
}
