/**
 * 文件：MateriaVersionServiceImpl.java
 * 版本：1.0.0
 * 日期：
 * Copyright &reg;
 * All right reserved.
 */

package com.mortals.xhx.module.materia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.mortals.framework.common.code.YesNo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.FileUtil;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.BomStatusEnum;
import com.mortals.xhx.common.code.PublishStatusEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.pdu.ApiRespPdu;
import com.mortals.xhx.module.materia.dao.MateriaBomVersionDao;
import com.mortals.xhx.module.materia.model.*;
import com.mortals.xhx.module.materia.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: 产品发布表</p>
 * <p>Description: MateriaVersionServiceImpl service接口 </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 *
 * @author
 * @version 1.0.0
 */
@Service("materiaBomVersionService")
public class MateriaBomVersionServiceImpl extends AbstractCRUDServiceImpl<MateriaBomVersionDao, MateriaBomVersionEntity, Long> implements MateriaBomVersionService {

    @Autowired
    private ParamService paramService;
    @Autowired
    private MateriaService materiaService;
    @Autowired
    private MateriaBomService materiaBomService;
    @Autowired
    private MateriaBomItemService materiaBomItemService;
    @Autowired
    private UserService userService;
//    @Autowired
//    private TalkConfiguration talkConfiguration;
//    @Autowired
//    private IApiGateFeign iApiGateFeign;
    @Autowired
    private MateriaBomTreeService materiaBomTreeService;


    @Override
    protected void saveBefore(MateriaBomVersionEntity entity, Context context) throws AppException {
//
//       if(ObjectUtils.isEmpty(entity.getBomId())){
//           throw new AppException("请选择产品!");
//       }

       //判断当前bom 是否有产品正在审核或者编辑中，


        MateriaBomVersionQuery materiaBomVersionQuery = new MateriaBomVersionQuery();
       materiaBomVersionQuery.setBomCode(entity.getBomCode());
       materiaBomVersionQuery.setPublishStatusList(Lists.newArrayList(PublishStatusEnum.PRODUCT_AUDITING.getValue(),PublishStatusEnum.PRODUCT_PENDING.getValue()));

        MateriaBomVersionEntity materiaBomVersionEntity = this.find(materiaBomVersionQuery, context).stream().findAny().orElseGet(() -> null);

        if(!ObjectUtils.isEmpty(materiaBomVersionEntity)){
            throw new AppException("选择的产品BOM已存在正在提交或者审核中的实例!");
        }
        //校验版本是否存在
        MateriaBomVersionQuery query = new MateriaBomVersionQuery();
        query.setVerCode(entity.getVerCode());
        MateriaBomVersionEntity bomVersionEntity = this.find(query, context).stream().findAny().orElseGet(() -> null);

        if(!ObjectUtils.isEmpty(bomVersionEntity)){
            throw new AppException("已存在相同的版本号，请重新发布!");
        }


        MateriaBomTreeQuery materiaBomTreeQuery = new MateriaBomTreeQuery();
        materiaBomTreeQuery.setCode(entity.getBomCode());

        MateriaBomTreeEntity materiaBomTreeEntity = materiaBomTreeService.find(materiaBomTreeQuery, context).stream().findAny().orElseGet(() -> null);

        if(!ObjectUtils.isEmpty(materiaBomTreeEntity)){
            if(ObjectUtils.isEmpty(materiaBomTreeEntity.getMateriaId())){
                throw new AppException("当前选择的产品，未配置物料，请配置后再提交版本！产品树路径:"+entity.getBomCode());
            }


            MateriaEntity materiaEntity = materiaService.get(materiaBomTreeEntity.getMateriaId(), context);
            entity.setMateriaId(materiaEntity.getId());
            entity.setMateriaCode(materiaEntity.getCode());
        }

        entity.setPublishStatus(PublishStatusEnum.PRODUCT_PENDING.getValue());
    }


    @Override
    protected void saveAfter(MateriaBomVersionEntity entity, Context context) throws AppException {
        //保存后递归所有相关bom项，查询如果是修订状态的，改变为审核中，
        // updateBomsStatus( entity.getBomId(),context);
    }

    private void updateBomsStatus(Long bomId, Integer publishStatus, Context context) {
        MateriaBomEntity materiaBomEntity = materiaBomService.get(bomId, context);
        if (publishStatus.equals(PublishStatusEnum.PRODUCT_AUDITING.getValue())) {
            if (materiaBomEntity.getStatus() == BomStatusEnum.BOM_EDIT.getValue()) {
                //修改修订-》审核中
                materiaBomEntity.setStatus(BomStatusEnum.BOM_AUDIT.getValue());
                materiaBomService.update(materiaBomEntity, context);
            }
        } else if (publishStatus.equals(PublishStatusEnum.PRODUCT_REJECT.getValue())) {
            if (materiaBomEntity.getStatus() == BomStatusEnum.BOM_AUDIT.getValue()) {
                //拒绝 修改审核-》修订
                materiaBomEntity.setStatus(BomStatusEnum.BOM_EDIT.getValue());
                materiaBomService.update(materiaBomEntity, context);
            }
        } else if (publishStatus.equals(PublishStatusEnum.PRODUCT_SUCESS.getValue())) {
            if (materiaBomEntity.getStatus() == BomStatusEnum.BOM_AUDIT.getValue()) {
                //同意 修改审核-》发布
                materiaBomEntity.setStatus(BomStatusEnum.BOM_PUBLISH.getValue());
                materiaBomService.update(materiaBomEntity, context);
            }

        }
      //  MateriaBomItemQuery materiaBomItemQuery = new MateriaBomItemQuery();
      //  materiaBomItemQuery.setBomId(bomId);
      //  materiaBomItemService.find(materiaBomItemQuery, context).stream().filter(f -> f.getMateriaBomId() != null).peek(item -> updateBomsStatus(item.getMateriaBomId(), publishStatus, context)).count();
    }

    @Override
    public Boolean submitProduct(Long id, Context context) {
        MateriaBomVersionEntity productVersionEntity = this.get(id, null);
        if (ObjectUtils.isEmpty(productVersionEntity)) {
            throw new AppException("当前版本不存在！");
        }
        UserEntity userEntity = userService.get(context.getUser().getId(), context);
        if (ObjectUtils.isEmpty(userEntity)) {
            throw new AppException("user is null");
        }

      /*  String resp = iApiGateFeign.getToken(talkConfiguration.getApiKey(), talkConfiguration.getAppsecret());
        ApiRespPdu<String> respPdu = JSONObject.parseObject(resp, new TypeReference<ApiRespPdu<String>>() {
        });
        log.info(String.format("dingdingtalk get token:%s", JSONObject.toJSONString(respPdu)));

        if (YesNo.YES.getValue() == respPdu.getCode()) {
            String token = respPdu.getData();
            resp = iApiGateFeign.getUserIdByMobile(userEntity.getMobile(), token);
            respPdu = JSONObject.parseObject(resp, new TypeReference<ApiRespPdu<String>>() {
            });
            log.info(String.format("dingdingtalk get user:%s", JSONObject.toJSONString(respPdu)));

            if (YesNo.YES.getValue() == respPdu.getCode()) {
                String deptResp = iApiGateFeign.getDeptIdByUserId(respPdu.getData(), token);
                ApiRespPdu<String> deptRespPdu = JSONObject.parseObject(deptResp, new TypeReference<ApiRespPdu<String>>() {
                });
                log.info(String.format("dingdingtalk get dept:%s", JSONObject.toJSONString(deptRespPdu)));

                Map<String, String> map = new HashMap<>();
                List<String> list = new ArrayList<>();
                list.add(respPdu.getData());

                Map<String, String> paramMap = paramService.getParamByFirstOrganize(Constant.Param_VerRdCode);

                map.put("发布产品类型", paramMap.getOrDefault(productVersionEntity.getRdCode(),""));
                map.put("发布版本号", productVersionEntity.getVerCode());
                map.put("发布日期", DateUtils.convertTime2Str(productVersionEntity.getPublishTime().getTime(), DateUtils.P_yyyy_MM_dd));
                map.put("发布人", JSONObject.toJSONString(list));

                map.put("源文件地址", productVersionEntity.getSourceFilePath());

                map.put("源文件标记号", productVersionEntity.getSourceFilePath());

                map.put("发布文件地址", productVersionEntity.getPublishFilePath());

                map.put("发布文件标记号", productVersionEntity.getPublishFileTag());

                map.put("发布版本描述", productVersionEntity.getPublishDesc());

                resp = iApiGateFeign.workCreate(respPdu.getData(), token, map, deptRespPdu.getData());
                respPdu = JSONObject.parseObject(resp, new TypeReference<ApiRespPdu<String>>() {
                });
                log.info(String.format("dingdingtalk workCreate:%s", JSONObject.toJSONString(respPdu)));
                if (YesNo.YES.getValue() == respPdu.getCode()) {
                    productVersionEntity.setPublishStatus(PublishStatusEnum.PRODUCT_AUDITING.getValue());
                    productVersionEntity.setProcessInstanceId(respPdu.getData());
                    this.update(productVersionEntity, null);
                   // updateBomsStatus(productVersionEntity.getBomId(), productVersionEntity.getPublishStatus(), null);
                    return true;
                }
            }
        }*/
        return false;

    }

    @Override
    public Boolean auditProduct(String processInstanceId, String result, String remark) {
        MateriaBomVersionQuery productVersionQuery = new MateriaBomVersionQuery();
        productVersionQuery.setProcessInstanceId(processInstanceId);
        MateriaBomVersionEntity productVersionEntity = this.find(productVersionQuery, null).stream().findAny().orElseGet(() -> null);
        if (!ObjectUtils.isEmpty(productVersionEntity)) {

            if ("refuse".equals(result)) {
                productVersionEntity.setPublishStatus(PublishStatusEnum.PRODUCT_REJECT.getValue());
            } else if ("agree".equals(result)) {
                productVersionEntity.setPublishStatus(PublishStatusEnum.PRODUCT_SUCESS.getValue());
            }
            productVersionEntity.setRemark(remark);
            this.update(productVersionEntity, null);


            MateriaBomEntity materiaBomEntity = materiaBomService.get(productVersionEntity.getBomId(), null);
            if(!ObjectUtils.isEmpty(materiaBomEntity)){
                if ("refuse".equals(result)) {
                    materiaBomEntity.setStatus(BomStatusEnum.BOM_EDIT.getValue());
                } else if ("agree".equals(result)) {
                    materiaBomEntity.setStatus(BomStatusEnum.BOM_PUBLISH.getValue());
                }

                log.info(String.format("undate bom:%s", JSONObject.toJSONString(materiaBomEntity)));
                materiaBomService.update(materiaBomEntity, null);

            }
            //解锁当前bom锁定状态
            // updateBomsStatus(productVersionEntity.getBomId(),productVersionEntity.getPublishStatus(), null);
        }else{
            log.info("productVersionEntity is null! processInstanceId:"+processInstanceId);
        }
        return true;
    }

    @Override
    public void updateBom(Long productVersionId, Long bomId) {
        MateriaBomVersionEntity materiaBomVersionEntity = new MateriaBomVersionEntity();
        materiaBomVersionEntity.setId(productVersionId);
        materiaBomVersionEntity.setBomId(bomId);
        this.getDao().update(materiaBomVersionEntity);
    }

    @Override
    protected void validData(MateriaBomVersionEntity entity, Context context) throws AppException {

        if(ObjectUtils.isEmpty(entity.getBomCode())){
            throw new AppException("请选择产品BOM!");
        }

        super.validData(entity, context);
    }


    public static void main(String[] args) {
        String str="11.44";
        System.out.println(FileUtil.getExtend(str,str));
    }
}