/**
* 文件：MateriaBomItemController.java
* 版本：1.0.0
* 日期：
* Copyright &reg; 
* All right reserved.
*/
package com.mortals.xhx.module.materia.web;


import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.common.IBaseEnum;
import com.mortals.framework.common.code.YesNo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.BomStatusEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.module.config.model.ConfigFieldQuery;
import com.mortals.xhx.module.config.service.ConfigFieldService;
import com.mortals.xhx.module.materia.model.*;
import com.mortals.xhx.module.materia.service.MateriaBomItemService;
import com.mortals.xhx.module.materia.service.MateriaBomService;
import com.mortals.xhx.module.materia.service.MateriaService;
import com.mortals.xhx.module.materia.service.MateriaSupplierService;
import com.mortals.xhx.module.supplier.model.SupplierQuery;
import com.mortals.xhx.module.supplier.service.SupplierService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>Title: 物料BOM单项表</p>
 * <p>Description: MateriaBomItemController  </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 * @author 
 * @version 1.0.0
 */
@RestController
@RequestMapping("materia/bom/item")
public class MateriaBomItemController extends BaseCRUDJsonMappingController<MateriaBomItemService,MateriaBomItemForm, MateriaBomItemEntity,Long> {
	@Autowired
	private MateriaSupplierService materiaSupplierService;
	@Autowired
	private MateriaBomService materiaBomService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private MateriaService materiaService;
	@Autowired
	private ParamService paramService;
	@Autowired
	private ConfigFieldService configFieldService;

	public MateriaBomItemController(){
		super.setFormClass(MateriaBomItemForm.class);
		super.setModuleDesc("物料BOM单项表");
	}

	@Override
	protected void doListBefore(HttpServletRequest request, HttpServletResponse response, MateriaBomItemForm form, Map<String, Object> model, Context context) throws AppException {
	form.getPageInfo().setPrePageResult(999);
		super.doListBefore(request, response, form, model, context);
	}

	@Override
	protected int doListAfter(HttpServletRequest request, HttpServletResponse response, MateriaBomItemForm form, Map<String, Object> model, Context context) throws AppException {

		List<MateriaBomItemEntity> materiaBomItemEntities = (ArrayList<MateriaBomItemEntity>) model.get(SysConstains.RESULT_KEY);
		if (!ObjectUtils.isEmpty(materiaBomItemEntities)) {
            List<MateriaBomItemCustomEntity> collect = materiaBomItemEntities.stream().map(entity -> {
				MateriaBomItemCustomEntity bomItemCustomEntity = new MateriaBomItemCustomEntity();
				BeanUtils.copyProperties(entity, bomItemCustomEntity);
				return bomItemCustomEntity;
			}).peek(item -> {
				if(!ObjectUtils.isEmpty(item.getMateriaBomId())){
					MateriaBomItemQuery bomItemQuery = new MateriaBomItemQuery();
					bomItemQuery.setBomId(item.getMateriaBomId());
					List<MateriaBomItemEntity> list = this.service.find(bomItemQuery, context);
					item.setBomItemList(list);
					MateriaBomEntity bomEntity = materiaBomService.get(item.getMateriaBomId(), context);
					item.setBomVersion(bomEntity.getVersion());
				}

				MateriaEntity materiaEntity = materiaService.get(item.getMateriaId(), context);
				item.setUnitOfMeasure(materiaEntity.getUnitOfMeasure());
				item.setSpecModel(materiaEntity.getSpecModel());
				item.setMainPicUrl(materiaEntity.getMainPicUrl());
			}).collect(Collectors.toList());
			model.put(SysConstains.RESULT_KEY, collect);
		}
		return super.doListAfter(request, response, form, model, context);
	}

	@Override
	protected void init(HttpServletRequest request, HttpServletResponse response, MateriaBomItemForm form,
						Map<String, Object> model, Context context) {
		this.addDict(model, "attachType", paramService.getParamByFirstOrganize(Constant.Param_MateriaAttachType));

		this.addDict(model, "useType", paramService.getParamByFirstOrganize(Constant.Param_BomUseType));
		this.addDict(model, "status", paramService.getParamByFirstOrganize(Constant.Param_BomStatus));
		this.addDict(model, "required", IBaseEnum.getEnumMap(YesNo.class));
		this.addDict(model, "supplierId", supplierService.find(new SupplierQuery(), getContext()).stream()
				.collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName(), (o, n) -> n)));
		this.addDict(model, "supplyType", paramService.getParamByFirstOrganize(Constant.Param_MatriaSupplyType));
		this.addDict(model, "unitOfMeasure", paramService.getParamByFirstOrganize(Constant.Param_MatriaUnitOfMeasure));
		ConfigFieldQuery configFieldQuery = new ConfigFieldQuery();
		configFieldQuery.setTableCode("mortals.xhx.materia_bom_item");
		configFieldQuery.setEnabled(YesNo.YES.getValue());

		List<Map<String, String>> list=new ArrayList<Map<String, String>>();
		this.init(list);
		List<Map<String, String>> listTwo = configFieldService.find(configFieldQuery, context).stream().map(item -> {
			Map<String, String> map = new HashMap<>();
			map.put("fieldName", item.getFieldName());
			map.put("fieldCode", item.getFieldCode());
			return map;
		}).collect(Collectors.toList());
		list.addAll(listTwo);
		this.addDict(model, "fieldList",list);
		this.addDict(model, "extField", configFieldService.find(configFieldQuery, context).stream().collect(Collectors.toMap(x -> x.getFieldCode(), y -> y.getFieldName(), (n, o) -> o)));
		super.init(request, response, form, model, context);
	}


	private void init(List<Map<String, String>> list){
		Map<String, String> map = new HashMap<>();
		map.put("fieldName", "物料编码");
		map.put("fieldCode", "materiaCode");
		list.add(map);

		map.put("fieldName", "类目编码");
		map.put("fieldCode", "categoryCode");
		list.add(map);

		map = new HashMap<>();
		map.put("fieldName", "物料名称");
		map.put("fieldCode", "materiaName");
		list.add(map);

		map = new HashMap<>();
		map.put("fieldName", "用量");
		map.put("fieldCode", "useNum");
		list.add(map);

		map = new HashMap<>();
		map.put("fieldName", "损耗率，0-100");
		map.put("fieldCode", "lossRate");
		list.add(map);

		map = new HashMap<>();
		map.put("fieldName", "必选料，否，是");
		map.put("fieldCode", "requiredName");
		list.add(map);

		map = new HashMap<>();
		map.put("fieldName", "补给方式");
		map.put("fieldCode", "supplyTypeName");
		list.add(map);

		map = new HashMap<>();
		map.put("fieldName", "供应商");
		map.put("fieldCode", "supplyName");
		list.add(map);

		map = new HashMap<>();
		map.put("fieldName", "备注");
		map.put("fieldCode", "remark");
		list.add(map);
	}



	/**
	 * 物料供应查询
	 */
	@PostMapping(value = "materiaSupply")
	public String materiaSupply(@RequestParam(value = "id", required = true) Long id) {
		JSONObject jsonObject = new JSONObject();
		try {

			Map<String, String> supplyMap = supplierService.find(new SupplierQuery(), getContext()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName(), (n, o) -> o));
			MateriaSupplierQuery materiaSupplierQuery = new MateriaSupplierQuery();
			materiaSupplierQuery.setMateriaId(id);
			Map<String, String> materiaSupply = materiaSupplierService.find(materiaSupplierQuery, getContext()).stream().collect(Collectors.toMap(x -> x.getSupplierId().toString(), y -> supplyMap.get(y.getSupplierId().toString()), (n, o) -> o));

			MateriaBomQuery materiaBomQuery = new MateriaBomQuery();
			materiaBomQuery.setStatus(BomStatusEnum.BOM_PUBLISH.getValue());
			materiaBomQuery.setMateriaId(id);
			Map<String, String> materiaBomIds = materiaBomService.find(materiaBomQuery, getContext()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getVersion(), (n, o) -> o));

			jsonObject.put("materiaSupply", materiaSupply);
			jsonObject.put("materiaBomIds", materiaBomIds);

			jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
		} catch (Exception e) {
			log.error("废弃物料错误", e);
			jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
			jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
		}
		return jsonObject.toJSONString();
	}



	
	
}