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

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
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.util.StringUtils;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.module.attach.model.AttachEntity;
import com.mortals.xhx.module.attach.model.AttachQuery;
import com.mortals.xhx.module.attach.service.AttachService;
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.MateriaBomService;
import com.mortals.xhx.module.materia.service.MateriaService;
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: MateriaBomController
 * </p>
 * <p>
 * Copyright: Copyright &reg;
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author
 * @version 1.0.0
 */
@RestController
@RequestMapping("materia/bom")
public class MateriaBomController
		extends BaseCRUDJsonMappingController<MateriaBomService, MateriaBomForm, MateriaBomEntity, Long> {

	@Autowired
	private ParamService paramService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private MateriaService materiaService;
	@Autowired
	private AttachService attachService;
	@Autowired
	private ConfigFieldService configFieldService;

	@Override
	protected void doListBefore(HttpServletRequest request, HttpServletResponse response, MateriaBomForm form, Map<String, Object> model, Context context) throws AppException {
		form.getPageInfo().setPrePageResult(999);
		if (StringUtils.isNotEmpty(form.getQuery().getMateriaCode())) {
			MateriaBomQuery materiaquery = new MateriaBomQuery();
			materiaquery.setMateriaCode("%" + form.getQuery().getMateriaCode() + "%");
			form.getQuery().setAndConditionList(Lists.newArrayList(materiaquery));// 使用OR条件查询
			form.getQuery().setMateriaCode(null);
		}
		super.doListBefore(request, response, form, model, context);
	}


	@Override
	protected int doListAfter(HttpServletRequest request, HttpServletResponse response, MateriaBomForm form, Map<String, Object> model, Context context) throws AppException {
		List<MateriaBomEntity> materiaBomEntities = (ArrayList<MateriaBomEntity>) model.get(SysConstains.RESULT_KEY);
		if (!ObjectUtils.isEmpty(materiaBomEntities)) {
			List<MateriaBomCustomEntity> collect = materiaBomEntities.stream().map(entity -> {
				MateriaBomCustomEntity materiaBomCustomEntity = new MateriaBomCustomEntity();
				BeanUtils.copyProperties(entity, materiaBomCustomEntity);
				MateriaEntity materiaEntity = materiaService.get(entity.getMateriaId(), context);
				materiaBomCustomEntity.setMainPicUrl(materiaEntity.getMainPicUrl());
				materiaBomCustomEntity.setSpecModel(materiaEntity.getSpecModel());
				return materiaBomCustomEntity;
			}).peek(item -> {
				AttachQuery attachQuery = new AttachQuery();
				attachQuery.setTableCode(Constant.PARAM_MORTALS_IOT_MATERIA_BOM);
				attachQuery.setTableDataId(item.getId());
				List<AttachEntity> attachEntityList = attachService.find(attachQuery, context);

				if(!ObjectUtils.isEmpty(attachEntityList)){
					item.setAttachEntityList(attachEntityList);
				}

			}).collect(Collectors.toList());
			model.put(SysConstains.RESULT_KEY, collect);
		}



		return super.doListAfter(request, response, form, model, context);
	}

	@Override
	protected void saveBefore(HttpServletRequest request, HttpServletResponse response, MateriaBomForm form, Map<String, Object> model, Context context) throws AppException {
//		if (!form.getEntity().newEntity()&&form.getEntity().getStatus() != BomStatusEnum.BOM_EDIT.getValue()) {
//			throw new AppException("只有修订中的Bom清单才能修改");
//		}
		super.saveBefore(request, response, form, model, context);
	}

	@Override
	protected void init(HttpServletRequest request, HttpServletResponse response, MateriaBomForm 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(Constant.PARAM_MORTALS_IOT_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", "损耗率");
		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);
	}


	public MateriaBomController() {
		super.setFormClass(MateriaBomForm.class);
		super.setModuleDesc("BOM单表");
	}




	/**
	 * 物料bom导入
	 */
	@PostMapping(value = "doImport")
	public String doImport(@RequestParam(value = "materiaBomStr", required = false) String materiaBomStr) {
		JSONObject jsonObject = new JSONObject();
		try {
			String returnStr = this.service.doImportBom(materiaBomStr, getContext());
			if(!ObjectUtils.isEmpty(returnStr)){
				jsonObject.put(KEY_RESULT_MSG, returnStr);
			}
			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();
	}

	/**
	 * 物料bom导出
	 */
	@PostMapping(value = "doExport")
	public String doExport(@RequestParam(value = "id", required = true) Long id,@RequestParam(value = "type",defaultValue = "0") Integer type) {
		JSONObject jsonObject = new JSONObject();
		try {
			String returnPath ="";
			if(type.equals(0)){
				returnPath = this.service.doExportBom(id, getContext());
			}else{
				returnPath = this.service.doExportBomFlat(id, getContext());
			}
			jsonObject.put("path", returnPath);
			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();
	}


	/**
	 * 物料bom复制
	 */
	@PostMapping(value = "copyBom")
	public String copyBom(@RequestParam(value = "id", required = true) Long id) {
		JSONObject jsonObject = new JSONObject();
		try {
			this.service.copyBom(id, getContext());

			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();
	}


	public static void main(String[] args) {
		Double money=1000d;
		Double rate=0.3;
		Double dayRate = rate / 365;

	}
}