/**
 * 文件：MateriaController.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.MateriaCategoryService;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * Title: 物料主表
 * </p>
 * <p>
 * Description: MateriaController
 * </p>
 * <p>
 * Copyright: Copyright &reg;
 * </p>
 * <p>
 * Company:
 * </p>
 *
 * @author
 * @version 1.0.0
 */
@RestController
@RequestMapping("materia")
public class MateriaController extends BaseCRUDJsonMappingController<MateriaService, MateriaForm, MateriaEntity, Long> {

    @Autowired
    private MateriaCategoryService materiaCategoryService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private MateriaSupplierService materiaSupplierService;
    @Autowired
    private ParamService paramService;
    @Autowired
    private ConfigFieldService configFieldService;
    @Autowired
    private AttachService attachService;

    public MateriaController() {
        super.setFormClass(MateriaForm.class);
        super.setModuleDesc("物料主表");
    }

    @Override
    protected void doListBefore(HttpServletRequest request, HttpServletResponse response, MateriaForm form, Map<String, Object> model, Context context) throws AppException {
        MateriaQuery materiaquery = new MateriaQuery();

        List<MateriaQuery> conditions = Lists.newArrayList(materiaquery);

        if (StringUtils.isNotEmpty(form.getQuery().getName())) {
          //  materiaquery.setName("%" + form.getQuery().getName() + "%");
            conditions.get(0).setName("%" + form.getQuery().getName() + "%");
            form.getQuery().setOrConditionList(conditions);// 使用OR条件查询
            form.getQuery().setName(null);
        }

        if (StringUtils.isNotEmpty(form.getQuery().getCode())) {
            conditions.get(0).setCode("%" + form.getQuery().getCode() + "%");
            form.getQuery().setOrConditionList(conditions);// 使用OR条件查询
            form.getQuery().setCode(null);
        }
        super.doListBefore(request, response, form, model, context);
    }

    @Override
    protected int doListAfter(HttpServletRequest request, HttpServletResponse response, MateriaForm form, Map<String, Object> model, Context context) throws AppException {
        List<MateriaEntity> materiaEntities = (ArrayList<MateriaEntity>) model.get(SysConstains.RESULT_KEY);
        if (!ObjectUtils.isEmpty(materiaEntities)) {
            Map<Long, String> supplyMap = supplierService.find(new SupplierQuery(), getContext()).stream().collect(Collectors.toMap(x -> x.getId(), y -> y.getName(), (n, o) -> o));

            Map<Long, MateriaCategoryEntity> categoryMap = materiaCategoryService.find(new MateriaCategoryQuery(), getContext())
                    .stream().map(item -> {
                        MateriaCategoryEntity materiaCategoryEntity = new MateriaCategoryEntity();
                        materiaCategoryEntity.setId(item.getId());
                        materiaCategoryEntity.setName(item.getName());
                        materiaCategoryEntity.setParentId(item.getParentId());
                        return materiaCategoryEntity;
            }).collect(Collectors.toMap(x -> x.getId(), y -> y));

            List<MateriaCustomEntity> collect = materiaEntities.stream().map(entity -> {
                MateriaCustomEntity materiaCustomEntity = new MateriaCustomEntity();
                BeanUtils.copyProperties(entity, materiaCustomEntity);
                return materiaCustomEntity;
            }).peek(item -> {
                MateriaSupplierQuery materiaSupplierQuery = new MateriaSupplierQuery();
                materiaSupplierQuery.setMateriaId(item.getId());
                List<MateriaSupplierCustomEntity> materiaSupplierEntities = materiaSupplierService.find(materiaSupplierQuery, context).stream().map(m -> {
                    MateriaSupplierCustomEntity materiaSupplierCustomEntity = new MateriaSupplierCustomEntity();
                    materiaSupplierCustomEntity.setSupplierName(supplyMap.get(m.getSupplierId()));
                    return materiaSupplierCustomEntity;
                }).collect(Collectors.toList());

                item.setSupplierEntities(materiaSupplierEntities);

                AttachQuery attachQuery = new AttachQuery();
                attachQuery.setTableCode(Constant.PARAM_MORTALS_IOT_MATERIA);
                attachQuery.setTableDataId(item.getId());
                List<AttachEntity> attachEntityList = attachService.find(attachQuery, context);

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

                item.setCategoryName(getCategoryName(categoryMap, item.getCategoryId()));

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

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

    /**
     * @Description 获取类目名称
     * @param categoryMap
     * @param categoryId
     * @Return java.lang.String
     * @date 2021/3/24 17:45
     * @Author fuJun
     */
    private String getCategoryName(Map<Long, MateriaCategoryEntity> categoryMap, Long categoryId) {
        MateriaCategoryEntity entity = categoryMap.get(categoryId);
        StringBuilder categoryName = new StringBuilder();
        if (entity != null){
            categoryName = new StringBuilder(entity.getName());
            if (entity.getParentId() != null && entity.getParentId() != -1) {
                StringBuilder parentCategoryName = new StringBuilder(getCategoryName(categoryMap, entity.getParentId()));
                categoryName =  parentCategoryName.append("-").append(categoryName.toString());

            }
        }
        return categoryName.toString();
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, MateriaForm form,
                        Map<String, Object> model, Context context) {

        this.addDict(model, "unitOfMeasure", paramService.getParamByFirstOrganize(Constant.Param_MatriaUnitOfMeasure));
        this.addDict(model, "supplyType", paramService.getParamByFirstOrganize(Constant.Param_MatriaSupplyType));
        this.addDict(model, "deliveryPeriodUnit", paramService.getParamByFirstOrganize(Constant.Param_DeliveryPeriodUnit));

        this.addDict(model, "attachType", paramService.getParamByFirstOrganize(Constant.Param_MateriaAttachType));
        this.addDict(model, "categoryId", materiaCategoryService.find(new MateriaCategoryQuery(), getContext()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName(), (n, o) -> o)));
        this.addDict(model, "supplierId", supplierService.find(new SupplierQuery(), getContext()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName(), (n, o) -> o)));
        this.addDict(model, "enabled", IBaseEnum.getEnumMap(YesNo.class));


        ConfigFieldQuery configFieldQuery = new ConfigFieldQuery();
        configFieldQuery.setTableCode("mortals.xhx.materia");
        this.addDict(model, "extField", configFieldService.find(configFieldQuery, context).stream().filter(f -> f.getEnabled() == YesNo.YES.getValue()).collect(Collectors.toMap(x -> x.getFieldCode(), y -> y.getFieldName(), (n, o) -> o)));

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



    /**
     * 物料导入
     */
    @PostMapping(value = "doImportExcel")
    public String doImportExcel(@RequestParam(value = "path", required = false) String path) {
        JSONObject jsonObject = new JSONObject();
        try {

//            if (!FilenameUtils.getExtension(path).equals("xls")) {
//                throw new AppException("目录物料导入只支持xls!");
//            }
            String returnStr = this.service.doImportExcel(path, 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();
    }


    /**
     * 物料废弃
     */
    @PostMapping(value = "discard")
    public String discardMateria(@RequestParam(value = "id", required = true) Long id) {
        JSONObject jsonObject = new JSONObject();
        try {
            this.service.discardMateria(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();
    }


    /**
     * 物料废弃
     */
    @PostMapping(value = "updateAsset")
    public String updateAsset(@RequestParam(value = "id", required = true) Long id,@RequestParam(value = "asset", required = true) String asset) {
        JSONObject jsonObject = new JSONObject();
        try {
            this.service.updateAsset(id,asset, 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();
    }

}