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

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.key.Constant;
import com.mortals.xhx.module.supplier.model.SupplierEntity;
import com.mortals.xhx.module.supplier.model.SupplierQuery;
import com.mortals.xhx.module.supplier.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * <p>
 * Title: 供应商表
 * </p>
 * <p>
 * Description: SupplierController
 * </p>
 * <p>
 * Copyright: Copyright &reg;
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author
 * @version 1.0.0
 */
@RestController
@RequestMapping("supplier")
public class SupplierController
		extends BaseCRUDJsonMappingController<SupplierService, SupplierForm, SupplierEntity, Long> {
	@Autowired
	private ParamService paramService;

	@Override
	protected void init(HttpServletRequest request, HttpServletResponse response, SupplierForm form,
			Map<String, Object> model, Context context) {
		this.addDict(model, "tags", paramService.getParamByFirstOrganize(Constant.Param_SupplierTags));
		this.addDict(model, "nature", paramService.getParamByFirstOrganize(Constant.Param_PartnerNature));
		this.addDict(model, "settlementType",
				paramService.getParamByFirstOrganize(Constant.Param_PartnerSettlementType));
		super.init(request, response, form, model, context);
	}

	public SupplierController() {
		super.setFormClass(SupplierForm.class);
		super.setModuleDesc("供应商表");
	}


	@Override
	protected void saveBefore(HttpServletRequest request, HttpServletResponse response, SupplierForm form, Map<String, Object> model, Context context) throws AppException {
		//校验名称唯一性

		SupplierQuery query = new SupplierQuery();
		query.setName(form.getEntity().getName());

		SupplierEntity supplierEntity = this.service.find(query, context).stream().findAny().orElseGet(() -> null);

		if(!ObjectUtils.isEmpty(supplierEntity)){
			if(form.getEntity().newEntity()){
				//新增，存在新
				throw new AppException("当前供应商名称已存在，请重新修改后提交！");
			}else{
				//判断是否修改类目名称
				if(form.getEntity().getId()!=supplierEntity.getId()){
					throw new AppException("当前供应商名称已存在，请重新修改后提交！");
				}
			}
		}
	}
}