package com.sw.mes.yb.turnstore.service.impl;


import com.alibaba.fastjson.JSON;
import com.sw.mes.base.factory.init.dto.MesToWmsReceiptDataDto;
import com.sw.mes.base.factory.init.dto.MesToWmsReceiptDto;
import com.sw.mes.base.factory.inspect.entity.ReturnRecord;
import com.sw.mes.base.factory.inspect.service.ReturnRecordService;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.turnstore.dao.RecheckInspectReceiveDao;
import com.sw.mes.yb.turnstore.dto.RecheckInspectReceiveDetailDto;
import com.sw.mes.yb.turnstore.entity.RecheckInspectReceive;
import com.sw.mes.yb.turnstore.entity.RecheckInspectReceiveDetail;
import com.sw.mes.yb.turnstore.service.RecheckInspectReceiveDetailService;
import com.sw.mes.yb.turnstore.service.RecheckInspectReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;

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


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
public class RecheckInspectReceiveServiceImpl extends BaseServiceImpl<RecheckInspectReceive> implements RecheckInspectReceiveService {
    RecheckInspectReceiveDao dao;

    @Autowired
    public void setDao(RecheckInspectReceiveDao dao) {
        super.setBaseDao(dao);
        this.dao = dao;
    }

    @Autowired
    private RecheckInspectReceiveDetailService recheckInspectReceiveDetailService;

    @Autowired
    private YbInspectDataService inspectDataBaseService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Autowired
    private ReturnRecordService returnRecordService;

    @Value("${wms.url}")
    private String wmsUrl;

    @Override
    public RecheckInspectReceive findByTrayNo(String trayNo) {
        return dao.findByTrayNo(trayNo);
    }

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse resp) {
        //查询主表
        Specification<RecheckInspectReceive> specification = DynamicSpecifications.bySearchFilter(request, RecheckInspectReceive.class);
        List<RecheckInspectReceive> recheckInspectReceiveList = findByExampleSort(specification, null);
        if (null == recheckInspectReceiveList || recheckInspectReceiveList.isEmpty()) {
            return;
        }
        //通过主表查询
       /* try {
            getExportExcel(recheckInspectReceiveList, request, resp);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateState(RecheckInspectReceive receive, List<RecheckInspectReceiveDetailDto> detailDtoList) {
        //更新详情列表
        for (RecheckInspectReceiveDetailDto detailDto : detailDtoList) {
            //更新数据
            RecheckInspectReceiveDetail receiveDetail = fromDto(detailDto);
            receiveDetail.setState(receive.getState());
            receiveDetail.setConfirmTime(receive.getConfirmTime());
            receiveDetail.setConfirmUser(receive.getConfirmUser());
            if (receive.getState() == 1) {
                //解锁组托状态
                PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(detailDto.getCrystalNo());
                if (null == planProcessingOrder) {
                    throw new BusinessException(detailDto.getCrystalNo() + "工单号不存在");
                }
                planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
                planProcessingOrderService.saveOrUpdate(planProcessingOrder);
                //需求修改调整
                //查询数据字典中接收类型的扩展字段
                DictionaryItem dictionaryItem = null;
                if (StringUtils.isNotBlank(receiveDetail.getCrystalNo()) && StringUtils.isNotBlank(receiveDetail.getQuitType()) && receiveDetail.getQuitType().contains("复检")) {

                    dictionaryItem = dictionaryItemService.findByThemeValueAndValue("withdrawing_type", receiveDetail.getQuitType());
                }
                Integer isDirectIn = EnumValuesFactory.WipStorageStatus.待进站.getKey();
                if (null != dictionaryItem && StringUtils.equals(dictionaryItem.getExtendValue(), "1")) {
                    isDirectIn = EnumValuesFactory.WipStorageStatus.已进站.getKey();
                }
                //执行出站操作---WMS出站---圆棒检验
                Result result = wipStorageService.outStation(receiveDetail.getCrystalNo(), "C", isDirectIn, false);
                if (result.getCode() != ResultCode.SUCCESS.getCode()) {
                    //手动回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new RuntimeException(result.getMessage());
                }
                //更新检验数据库复检次数
                if (receiveDetail.getQuitType().contains("复检")) {
                    YbInspectData inspectDataBase = inspectDataBaseService.findBySectionNo(detailDto.getCrystalNo());
                    if (null != inspectDataBase) {
                        //更新复检次数
                        int reCheck = 1;
                        if (null != inspectDataBase.getReCheckType()) {
                            reCheck = Integer.parseInt(inspectDataBase.getReCheckType()) + 1;
                        }
                        inspectDataBase.setReCheckType(String.valueOf(reCheck));
                        //更新订单类型
                        inspectDataBase.setOrderType("ZH04");
                        //更新检验类型
                        inspectDataBase.setCheckoutName("复检");
                        inspectDataBaseService.saveOrUpdate(inspectDataBase);
                    }
                }
                //创建退库明细
                //创建圆棒退库记录
                ReturnRecord returnRecord = new ReturnRecord();
                BeanUtils.copyProperties(receiveDetail, returnRecord, BeanUtil.getIgnoreProperties(receiveDetail, null, "id"));
                returnRecord.setSectionNo(receiveDetail.getCrystalNo());
                returnRecord.setOrderNo(receiveDetail.getTrayNo());
                returnRecord.setOperationTime(receiveDetail.getConfirmTime());
                returnRecord.setConfirmUser(receiveDetail.getConfirmUser());
                returnRecord.setWithdrawingType("综计WMS");
                returnRecord.setPurpose("0");
                returnRecord.setInputLength(receiveDetail.getLength());
                returnRecord.setReCheckType(receiveDetail.getQuitType());
                returnRecord.setReturnStation("综计WMS");
                returnRecordService.saveOrUpdate(returnRecord);
            }
            recheckInspectReceiveDetailService.saveOrUpdate(receiveDetail);
        }
        saveOrUpdate(receive);
    }

    @Override
    public Result mesToWmsReceipt(String outOrderNo, Integer state) {
        MesToWmsReceiptDto mesToWmsReceiptDto = new MesToWmsReceiptDto();
        MesToWmsReceiptDataDto mesToWmsReceiptDataDto = new MesToWmsReceiptDataDto();
        mesToWmsReceiptDataDto.setOrderNum(outOrderNo);
        mesToWmsReceiptDataDto.setIsReceive("S");
        if (2 == state) {
            mesToWmsReceiptDataDto.setIsReceive("E");
        }
        //调用接口
        String jsonString = JSON.toJSONString(mesToWmsReceiptDataDto);
        mesToWmsReceiptDto.setZDATA(jsonString);
        String content = JSON.toJSONString(mesToWmsReceiptDto);
        String url = wmsUrl + "api/YC6MES/otherinteraction";
        String send = send(content, url);
        if (null != send && send.contains("\"ztype\":\"E\"")) {
            return ResultGenerator.fail(send);
        }
        return ResultGenerator.success();
    }

    public RecheckInspectReceiveDetail fromDto(RecheckInspectReceiveDetailDto dto) {
        return modelMapper.map(dto, RecheckInspectReceiveDetail.class);
    }

    private String send(String data, String url) {
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(mediaType);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> httpEntity = new HttpEntity<>(data, headers);
        //使用exchange请求接口
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }


}
