package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.base.entity.CommonRoleResource;
import com.winsea.svc.base.base.service.ICommonRoleResourceService;
import com.winsea.svc.base.security.entity.User;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeService;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.entity.view.TmpModel;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.*;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.Const;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 库内自采价格主表 服务实现类
 * </p>
 *
 * @author ccj
 * @since 2021-09-03
 */
@Service
public class PurchasePriceServiceImpl extends ServiceImpl<PurchasePriceMapper, PurchasePrice> implements IPurchasePriceService {

    @Autowired
    private IPurchasePriceDetailService purchasePriceDetailService;
    @Autowired
    private IPurchasePriceDetailPrintService purchasePriceDetailPrintService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private CacheComponent cacheComponent;
    @Autowired
    private INoticeService noticeService;
    @Override
    public Page<PurchasePrice> purchasePriceList(PurchasePrice purchasePrice) {

        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (purchasePrice.getCurrentPage() - 1)
                * purchasePrice.getPageSize());
        //公司id
        pageView.put("compId", purchasePrice.getCompId());
        pageView.put("warehouseId", purchasePrice.getWarehouseId());
        pageView.put("pageSize", purchasePrice.getPageSize());
        pageView.put("currentPage", purchasePrice.getCurrentPage());
        List<PurchasePrice> dataList = this.baseMapper.purchasePriceList(pageView);
        Integer dataCount = this.baseMapper.purchasePriceListCount(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            dataList.forEach(purchasePrice1 -> {
                String taskId = "";
                // 只有待审核状态才有taskId
                if (StringUtils.isNotBlank(purchasePrice1.getWorkflowId())) {
                    JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(purchasePrice1.getWorkflowId()), purchasePrice1.getId());
                    taskId = jsonObject.getString("taskId");
                    purchasePrice1.setTaskId(taskId);
                }
            });
        }
        Page<PurchasePrice> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(purchasePrice.getCurrentPage());
        page.setSize(purchasePrice.getPageSize());
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String purchasePriceAdd(PurchasePrice purchasePrice) {
        //查同一仓库同一货名是否已设置
        List<PurchasePrice> purchasePriceList=this.selectList(new EntityWrapper<PurchasePrice>()
                .eq("warehouse_id",purchasePrice.getWarehouseId())
                .eq("goods_name",purchasePrice.getGoodsName()));
        if (!CollectionUtils.isEmpty(purchasePriceList)){
            throw new YException(YExceptionEnum.PURCHASE_PRICE_ERROR);
        }
        else {
            try {
                String compId = purchasePrice.getCompId();
                String mainId = IdGenerator.generateUUID();
                purchasePrice.setId(mainId);
                purchasePrice.setStatus(StatusEnum.PURCHASE_REVIEWED.getName());
                purchasePrice.setStatusFlag(StatusEnum.PURCHASE_REVIEWED.getFlag());
                // 操作主表数据
                this.insert(purchasePrice);

                List<PurchasePriceDetail> list = new ArrayList<>();
                // 操作明细表数据
                for (PurchasePriceDetail tmp : purchasePrice.getDetails()) {
                    tmp.setId(IdGenerator.generateUUID());
                    tmp.setCompId(compId);
                    tmp.setMainId(mainId);
                    list.add(tmp);
                }
                this.purchasePriceDetailService.insertBatch(list);
                List<PurchasePriceDetailPrint> list1 = new ArrayList<>();
                // 操作打印表数据
                for (PurchasePriceDetailPrint tmp : purchasePrice.getDetailPrints()) {
                    tmp.setId(IdGenerator.generateUUID());
                    tmp.setCompId(compId);
                    tmp.setMainId(mainId);
                    list1.add(tmp);
                }
                this.purchasePriceDetailPrintService.insertBatch(list1);

            } catch (Exception e) {
                System.out.println("新增收购价格异常：" + e.toString());
            }
        }
        boolean isStartWorkflow = StringUtils.isBlank(purchasePrice.getWorkflowId());
        // 不是退回的单子
        if (isStartWorkflow) {
            Workflow workflow = workflowService
                    .findLatestWorkflowByBusinessCodeByApp(purchasePrice.getCompId(), "PROCUREMENT-PRICE-APPROVE");
            // 没配置审核流程，直接结束并处理信息
            if (workflow == null) {
                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
            }
            // 开启审核流
            else {

                // 设置状态 已提交审核
                purchasePrice.setWorkflowId(workflow.getId());
                this.updateById(purchasePrice);
                workflowService.startInstance(workflow.getId(), purchasePrice.getId());
            }
        }
        // 退回的单子 再启用
        else {
            this.updateById(purchasePrice);
            workflowService.activateInstance(purchasePrice.getWorkflowId(), purchasePrice.getId());
        }
        return "ok";
    }

    @Override
    public PurchasePrice purchasePriceLook(PurchasePrice purchasePrice) {
        purchasePrice = this.selectById(purchasePrice.getId());
        String taskId = "";
        // 只有待审核状态才有taskId
        if (StringUtils.isNotBlank(purchasePrice.getWorkflowId())) {
            JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(purchasePrice.getWorkflowId()), purchasePrice.getId());
            taskId = jsonObject.getString("taskId");
            purchasePrice.setTaskId(taskId);
        }
        List<PurchasePriceDetail> details = this.purchasePriceDetailService.selectList(new EntityWrapper<PurchasePriceDetail>().eq("main_id",purchasePrice.getId()));
        for(PurchasePriceDetail purchasePriceDetail:details){
            String[] points =  purchasePriceDetail.getPoint().split(",");
            String[] pointPrices =  purchasePriceDetail.getPointPrice().split(",");
            List<TmpModel> list = new ArrayList<>();
           for(int i=0;i<points.length - 1;i++){
               TmpModel tmpModel = new TmpModel();
               tmpModel.setStartWater(points[i]);
               tmpModel.setEndWater(points[i+1]);
               if(i<pointPrices.length){
                   tmpModel.setPrice(pointPrices[i]);
               }
               list.add(tmpModel);
           }
           purchasePriceDetail.setModelList(list);
        }
        purchasePrice.setDetails(details);
        List<PurchasePriceDetailPrint> detailPrints = this.purchasePriceDetailPrintService.selectList(new EntityWrapper<PurchasePriceDetailPrint>().eq("main_id",purchasePrice.getId()).orderBy("water_min"));
        purchasePrice.setDetailPrints(detailPrints);
        return purchasePrice;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String purchasePriceEdit(PurchasePrice purchasePrice) {
        purchasePrice.setStatus(StatusEnum.PURCHASE_REVIEWED.getName());
        purchasePrice.setStatusFlag(StatusEnum.PURCHASE_REVIEWED.getFlag());
        // 操作主表数据
        this.updateById(purchasePrice);
        this.purchasePriceDetailService.delete(new EntityWrapper<PurchasePriceDetail>().eq("main_id",purchasePrice.getId()));
        this.purchasePriceDetailPrintService.delete(new EntityWrapper<PurchasePriceDetailPrint>().eq("main_id",purchasePrice.getId()));
        // 操作明细表数据
        if(purchasePrice.getDetails()!=null) {
            for (PurchasePriceDetail tmp : purchasePrice.getDetails()) {
                tmp.setId(IdGenerator.generateUUID());
                tmp.setCompId(purchasePrice.getCompId());
                tmp.setMainId(purchasePrice.getId());
            }
            this.purchasePriceDetailService.insertBatch(purchasePrice.getDetails());
        }
        // 操作打印表数据
        if(purchasePrice.getDetailPrints()!=null) {
            for (PurchasePriceDetailPrint tmp : purchasePrice.getDetailPrints()) {
                tmp.setId(IdGenerator.generateUUID());
                tmp.setCompId(purchasePrice.getCompId());
                tmp.setMainId(purchasePrice.getId());
            }
            this.purchasePriceDetailPrintService.insertBatch(purchasePrice.getDetailPrints());
        }
        boolean isStartWorkflow = StringUtils.isBlank(purchasePrice.getWorkflowId());
        if(StatusEnum.PURCHASE_FAILED.getName().equals(purchasePrice.getStatus())) {
            // 不是退回的单子
            if (isStartWorkflow) {
                Workflow workflow = workflowService
                        .findLatestWorkflowByBusinessCodeByApp(purchasePrice.getCompId(), "PROCUREMENT-PRICE-APPROVE");
                // 没配置审核流程，直接结束并处理信息
                if (workflow == null) {
                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                }
                // 开启审核流
                else {

                    // 设置状态 已提交审核
                    purchasePrice.setWorkflowId(workflow.getId());
                    this.updateById(purchasePrice);
                    workflowService.startInstance(workflow.getId(), purchasePrice.getId());
                }
            }
            // 退回的单子 再启用
            else {

                this.updateById(purchasePrice);
                workflowService.activateInstance(purchasePrice.getWorkflowId(), purchasePrice.getId());
            }
        }
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String purchasePriceDel(PurchasePrice purchasePrice) {
        purchasePriceDetailService.delete(new EntityWrapper<PurchasePriceDetail>().eq("main_id",purchasePrice.getId()));
        purchasePriceDetailPrintService.delete(new EntityWrapper<PurchasePriceDetailPrint>().eq("main_id",purchasePrice.getId()));
        this.deleteById(purchasePrice.getId());
        // 删除任务
        noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "PROCUREMENT-PRICE-APPROVE",
                purchasePrice.getId(), null);
        return "ok";
    }

    @Override
    public String purchasePriceAllowEdit(PurchasePrice purchasePrice) {
        WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectById(purchasePrice.getWarehouseId());
        if("1".equals(warehouseBaseInfo.getAllowEdit())){
            warehouseBaseInfo.setAllowEdit("0");
            warehouseBaseInfoService.updateById(warehouseBaseInfo);
        }
        else{
            warehouseBaseInfo.setAllowEdit("1");
            warehouseBaseInfoService.updateById(warehouseBaseInfo);
        }
        cacheComponent.delPrefixKey(Const.SELF_WAREHOUSE);
        return "ok";
    }

    /**
     * 查潮粮单价
     * @param purchasePrice
     * @return
     */
    @Override
    public Float tidalGrainPrice(PurchasePrice purchasePrice) {
        Float tidalGrainPrice=0.0f;
        PurchasePrice purchasePrice1=this.selectOne(new EntityWrapper<PurchasePrice>()
        .eq("warehouse_id",purchasePrice.getWarehouseId())
        .eq("goods_name",purchasePrice.getGoodsName())
        .eq("status_flag","3"));
        if (purchasePrice1!=null){
            PurchasePriceDetailPrint purchasePriceDetailPrint=purchasePriceDetailPrintService.selectOne(new EntityWrapper<PurchasePriceDetailPrint>()
            .eq("main_id",purchasePrice1.getId())
            .le("water_min",purchasePrice.getWaterContent())
            .ge("water_max",purchasePrice.getWaterContent()));
            if (purchasePriceDetailPrint!=null){
                if ("一等品".equals(purchasePrice.getGrade())){
                    tidalGrainPrice=purchasePriceDetailPrint.getPrice1();
                }
                else if ("二等品".equals(purchasePrice.getGrade())){
                    tidalGrainPrice=purchasePriceDetailPrint.getPrice2();
                }
                else if ("三等品".equals(purchasePrice.getGrade())){
                    tidalGrainPrice=purchasePriceDetailPrint.getPrice3();
                }
                else{
                    tidalGrainPrice=purchasePriceDetailPrint.getPriceOther();
                }
            }
        }
        return tidalGrainPrice;
    }

    @Override
    public Float dryGrainPrice(PurchasePrice purchasePrice) {
        Float dryGrainPrice=0.0f;
        PurchasePrice purchasePrice1=this.selectOne(new EntityWrapper<PurchasePrice>()
                .eq("warehouse_id",purchasePrice.getWarehouseId())
                .eq("goods_name",purchasePrice.getGoodsName())
                .eq("status_flag","3"));
        if (purchasePrice1!=null){
            dryGrainPrice=purchasePrice1.getDryGrainPrice();
        }
        return dryGrainPrice;
    }
}
