package com.yeejoin.amos.boot.module.ugp.biz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.ugp.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.CompanyDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.WelderDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.Attachment;
import com.yeejoin.amos.boot.module.ugp.api.entity.Company;
import com.yeejoin.amos.boot.module.ugp.api.entity.Equipment;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProjectResource;
import com.yeejoin.amos.boot.module.ugp.api.mapper.AttachmentMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.EquipmentMapper;

import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectResourceMapper;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.AttachmentServiceImpl;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.OrgServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.yeejoin.amos.boot.module.ugp.biz.service.impl.EquipmentServiceImpl;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.ugp.api.dto.EquipmentDto;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.foundation.enumeration.UserType;

/**
 * 设备信息表
 *
 * @author system_generator
 * @date 2022-09-22
 */
@RestController
@Api(tags = "设备信息表Api")
@RequestMapping(value = "/equipment")
public class EquipmentController extends BaseController {

    @Autowired
    EquipmentServiceImpl equipmentServiceImpl;


	@Autowired
	EquipmentMapper equipmentMapper;

	@Autowired
	AttachmentMapper attachmentMapper;

	@Autowired
	AttachmentServiceImpl attachmentService;

	@Autowired
	OrgServiceImpl orgService;
	@Autowired
	ProjectResourceMapper projectResourceMapper;

    /**
     * 新增设备信息表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增设备信息表", notes = "新增设备信息表")
	@BusinessIdentify
	public ResponseModel<EquipmentDto> save(@RequestBody EquipmentDto model) {
		model.setCompanyId(orgService.getReginParams().getBusinessInfo().getCompanySequenceNbr());
		model.setManufactureDate(new Date());
		model.setInspectionDate(new Date());
		model = equipmentServiceImpl.createWithModel(model);
	    return ResponseHelper.buildResponse(model);
	}

	/**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新设备信息表", notes = "根据sequenceNbr更新设备信息表")
	public ResponseModel<EquipmentDto> updateBySequenceNbrEquipment(@RequestBody EquipmentDto model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
	    model.setRecDate(new Date());
		model.setSequenceNbr(sequenceNbr);
	    return ResponseHelper.buildResponse(equipmentServiceImpl.updateWithModel(model));
	}

	/**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除设备信息表", notes = "根据sequenceNbr删除设备信息表")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") List<Long> sequenceNbr) throws Exception {
		LambdaQueryWrapper<ProjectResource> wrapper = new LambdaQueryWrapper<>();
		for (Long i:sequenceNbr){
			wrapper.eq(ProjectResource::getResourceId,i);
			if (!projectResourceMapper.selectList(wrapper).isEmpty()){
				return CommonResponseUtil.failure("无法删除,设备："+equipmentServiceImpl.getById(i).getName()+"已绑定项目");
			}
		}
		return ResponseHelper.buildResponse(equipmentServiceImpl.removeByIds(sequenceNbr));


    }

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个设备信息表",  notes = "根据sequenceNbr查询单个设备信息表")
	public ResponseModel<EquipmentDto> selectOne(@PathVariable Long sequenceNbr) {
	    return ResponseHelper.buildResponse(equipmentServiceImpl.queryBySeq(sequenceNbr));
	}

	/**
	 * 列表分页查询
	 *
	 * @param current 当前页
	 * @param current 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "设备信息表分页查询",  notes = "设备信息表分页查询")
	@BusinessIdentify
	public ResponseModel<IPage<EquipmentDto>> queryForPage(
			@RequestParam(value = "current") int current,
			@RequestParam(value = "size") int size, Equipment equipment) {
		IPage<EquipmentDto> page = new Page<>();
		page.setSize(size);
		page.setCurrent(current);
		page = equipmentServiceImpl.queryEquipmentPage(page,equipment);
		List<EquipmentDto> equipments = page.getRecords();
		if(!ValidationUtil.isEmpty(equipments)) {
			for (EquipmentDto equipmentDto : equipments) {
				equipmentDto.setCompanyName((String) orgService.getdetialInfo(String.valueOf(equipmentDto.getCompanyId())).get("name"));
			}
		}
		return ResponseHelper.buildResponse(page);
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "设备信息表列表全部数据查询",   notes = "设备信息表列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<EquipmentDto>> selectForList() {
	    return ResponseHelper.buildResponse(equipmentServiceImpl.queryForEquipmentList());
	}
	/**
	 * 设备数据名称查询
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "设备数据名称查询", notes = "设备数据名称查询")
	@GetMapping(value = "/selectName")
	public ResponseModel<List<JSONObject>> selectName() {
		return ResponseHelper.buildResponse(equipmentServiceImpl.selectName());
	}

	/**
	 * 新增设备+附件
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PostMapping (value = "/saveIE")
	@ApiOperation(httpMethod = "POST", value = "新增设备+附件", notes = "新增设备+附件")
	public ResponseModel<EquipmentDto>  saveEquipment(@RequestBody JSONObject object) {
		EquipmentDto equipmentDto = equipmentServiceImpl.saveEI(object);
		Long sequenceNbr = equipmentDto.getSequenceNbr();
		if (object.containsKey("subForm")){
			JSONArray subForm = object.getJSONArray("subForm");
			equipmentServiceImpl.saveAttachment(subForm,sequenceNbr);
		}
		return  ResponseHelper.buildResponse(equipmentDto);
	}
	/**
	 *根据sequenceNbr删除设备的附件
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@DeleteMapping(value = "IE/{sequenceNbr}")
	@ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除设备和附件", notes = "根据sequenceNbr删除设备和附件")
	public ResponseModel<Boolean> deleteEIBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr){
		attachmentMapper.deleteBySourceId(sequenceNbr);
		return ResponseHelper.buildResponse(equipmentServiceImpl.removeById(sequenceNbr));
	}
	/**
	 * 根据sequenceNbr查询设备的附件
	 *
	 * @param sequenceNbr  主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "IE/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询设备和附件",  notes = "根据sequenceNbr查询设备和附件")
	public ResponseModel<JSONObject> selectIEOne(@PathVariable Long sequenceNbr) {

		EquipmentDto equipmentDto = equipmentServiceImpl.queryBySeq(sequenceNbr);

		AttachmentDto attachmentDto = null;
		try {
			attachmentDto = attachmentMapper.selectAttBySeq(sequenceNbr);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("name",equipmentDto.getName());
			jsonObject.put("type",equipmentDto.getType());
			jsonObject.put("code",equipmentDto.getCode());
			jsonObject.put("manufacturer",equipmentDto.getManufacturer());
			jsonObject.put("manufactureDate",equipmentDto.getManufactureDate());
			jsonObject.put("serviceLife",equipmentDto.getServiceLife());
			jsonObject.put("inspectionDate",equipmentDto.getInspectionDate());
			jsonObject.put("useStatus",equipmentDto.getUseStatus());
			jsonObject.put("verifyStatus",equipmentDto.getVerifyStatus());
			JSONArray jsonArray = new JSONArray();
			try{
				jsonArray = JSON.parseArray(attachmentDto.getInfo());
			} catch (Exception e){

			}

			jsonObject.put("subForm",jsonArray);

			return ResponseHelper.buildResponse(jsonObject);
		}


	}
	/**
	 * 根据sequenceNbr更新设备的附件
	 *
	 * @param sequenceNbr  主键
	 * @return
	 */

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PostMapping(value = "IE/{sequenceNbr}")
	@ApiOperation(httpMethod = "POST",value = "根据sequenceNbr更新设备和附件",  notes = "根据sequenceNbr更新设备和附件")
	public ResponseModel<String> selectIEOne(@PathVariable Long sequenceNbr,@RequestBody JSONObject object) {
		equipmentServiceImpl.updateEI(sequenceNbr,object);
		return ResponseHelper.buildResponse("ok");
	}
}
