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.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.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.TradeWarehouseReceiptApplMapper;
import com.yh.saas.plugin.yiliangyiyun.service.INewWorkflowService;
import com.yh.saas.plugin.yiliangyiyun.service.ITradeWarehouseReceiptApplService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.service.IWarehouseBaseInfoService;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 贸易仓单申请信息 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2021-11-06
 */
@Service
public class TradeWarehouseReceiptApplServiceImpl extends ServiceImpl<TradeWarehouseReceiptApplMapper, TradeWarehouseReceiptAppl> implements ITradeWarehouseReceiptApplService {

    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @SofaReference
    private ICommonRoleResourceService roleResourceService;

    /**
     * 列表
     *
     * @param tradeWarehouseReceiptAppl
     * @return
     */
    @Override
    public Page<TradeWarehouseReceiptAppl> selectTradeWarehouseReceiptAppl(TradeWarehouseReceiptAppl tradeWarehouseReceiptAppl) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (tradeWarehouseReceiptAppl.getCurrentPage() - 1)
                * tradeWarehouseReceiptAppl.getPageSize());
        List<String> businessKeys = null;
        if ("1".equals(tradeWarehouseReceiptAppl.getSearchType())) {
            businessKeys = workflowService.getTaskBusinessKeysByCode("TRADE-WAREHOUSE-REPORT");
        }
        List<String> statusSet = new ArrayList<>();
        List<String> resourceIdList = this.getResourceIdList();
        if (resourceIdList.contains("tradeService-Edit")) { // 填写，提交    权限做完以后替换
            List<String> statusList = Lists.newArrayList(StatusEnum.PUR_RETURN.getFlag());
            statusSet.addAll(statusList);
        }
        //公司id
        pageView.put("compId", tradeWarehouseReceiptAppl.getCompId());
        pageView.put("searchKeyWord", tradeWarehouseReceiptAppl.getSearchKeyWord());
        pageView.put("searchType", tradeWarehouseReceiptAppl.getSearchType());
        pageView.put("pageSize", tradeWarehouseReceiptAppl.getPageSize());
        pageView.put("currentPage", tradeWarehouseReceiptAppl.getCurrentPage());
        pageView.put("statusFlag", tradeWarehouseReceiptAppl.getStatusFlag());
        pageView.put("businessKeys", businessKeys);
        pageView.put("statusSet", statusSet);
        // 查询采购入库总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<TradeWarehouseReceiptAppl> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            dataList.forEach(tradeWarehouseReceiptAppl1 -> {

                String taskId = "";
                // 只有待审核状态才有taskId
                if (StringUtils.isNotBlank(tradeWarehouseReceiptAppl1.getWorkflowId())) {
                    JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(tradeWarehouseReceiptAppl1.getWorkflowId()), tradeWarehouseReceiptAppl1.getId());
                    taskId = jsonObject.getString("taskId");
                    tradeWarehouseReceiptAppl1.setTaskId(taskId);
                }
            });

        }
        Page<TradeWarehouseReceiptAppl> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(tradeWarehouseReceiptAppl.getCurrentPage());
        page.setSize(tradeWarehouseReceiptAppl.getPageSize());
        return page;
    }

    /**
     * 地图信息
     *
     * @return
     */
    @Override
    public List<TradeWarehouseReceiptAppl> getMapInfo() {
        List<TradeWarehouseReceiptAppl> tradeWarehouseReceiptAppls = this.selectList(new EntityWrapper<TradeWarehouseReceiptAppl>()
                .eq("comp_id", AuthSecurityUtils.getCurrentUserInfo().getCompId())
                .groupBy("warehouse_id"));

        if (!CollectionUtils.isEmpty(tradeWarehouseReceiptAppls)) {
            for (int i = 0; i < tradeWarehouseReceiptAppls.size(); i++) {
                List<TradeWarehouseReceiptAppl> warehouseReceiptAppls = new ArrayList<>();
                WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectById(tradeWarehouseReceiptAppls.get(i).getWarehouseId());
                List<TradeWarehouseReceiptAppl> tradeWarehouseReceiptApplList = this.selectList(new EntityWrapper<TradeWarehouseReceiptAppl>()
                        .eq("warehouse_id", tradeWarehouseReceiptAppls.get(i).getWarehouseId()));
                tradeWarehouseReceiptAppls.get(i).setWarehousePositioning(warehouseBaseInfo.getWarehousePositioning());
                for (int j = 0; j < tradeWarehouseReceiptApplList.size(); j++) {
                    if (j == 7) {
                        break;
                    } else {
                        warehouseReceiptAppls.add(tradeWarehouseReceiptApplList.get(j));
                    }
                }
                tradeWarehouseReceiptAppls.get(i).setTradeWarehouseReceiptAppls(warehouseReceiptAppls);
            }
        }
        return tradeWarehouseReceiptAppls;
    }


    /**
     * 添加
     *
     * @param tradeWarehouseReceiptAppl
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertTradeWarehouseReceiptAppl(TradeWarehouseReceiptAppl tradeWarehouseReceiptAppl) {
        //新增主键id
        tradeWarehouseReceiptAppl.setId(IdGenerator.generateUUID());
        tradeWarehouseReceiptAppl.setStatusFlag(StatusEnum.TO_BE_REVIEWED.getFlag());
        tradeWarehouseReceiptAppl.setStatus(StatusEnum.TO_BE_REVIEWED.getName());

        // 操作主表数据
        this.insert(tradeWarehouseReceiptAppl);
//
        boolean isStartWorkflow = StringUtils.isBlank(tradeWarehouseReceiptAppl.getWorkflowId());
        // 不是退回的单子
        if (isStartWorkflow) {
            Workflow workflow = workflowService
                    .findLatestWorkflowByBusinessCodeByApp(tradeWarehouseReceiptAppl.getCompId(), "TRADE-WAREHOUSE-REPORT");
            // 没配置审核流程，直接结束并处理信息
            if (workflow == null) {
                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
            }
            // 开启审核流
            else {

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

            this.updateById(tradeWarehouseReceiptAppl);
            workflowService.activateInstance(tradeWarehouseReceiptAppl.getWorkflowId(), tradeWarehouseReceiptAppl.getId());
        }
        return tradeWarehouseReceiptAppl.getId();
    }


    /**
     * 更改
     *
     * @param tradeWarehouseReceiptAppl
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editTradeWarehouseReceiptAppl(TradeWarehouseReceiptAppl tradeWarehouseReceiptAppl) {
        TradeWarehouseReceiptAppl tradeWarehouseReceiptAppl1 = this.selectById(tradeWarehouseReceiptAppl.getId());
        // 开锁仓
        if ("1".equals(tradeWarehouseReceiptAppl.getEditFlag())) {
            if ("1".equals(tradeWarehouseReceiptAppl1.getLockedStatusFlag())) {
                tradeWarehouseReceiptAppl.setLockedStatusFlag("2");
                tradeWarehouseReceiptAppl.setLockedStatus("已锁仓");
            } else {
                tradeWarehouseReceiptAppl.setLockedStatusFlag("1");
                tradeWarehouseReceiptAppl.setLockedStatus("未锁仓");
            }
            this.updateById(tradeWarehouseReceiptAppl);
        } else {
            this.updateById(tradeWarehouseReceiptAppl);
            if("0".equals(tradeWarehouseReceiptAppl.getStatusFlag())){
                boolean isStartWorkflow = StringUtils.isBlank(tradeWarehouseReceiptAppl.getWorkflowId());
                // 不是退回的单子
                if (isStartWorkflow) {
                    Workflow workflow = workflowService
                            .findLatestWorkflowByBusinessCodeByApp(tradeWarehouseReceiptAppl.getCompId(), "TRADE-WAREHOUSE-REPORT");
                    // 没配置审核流程，直接结束并处理信息
                    if (workflow == null) {
                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                    }
                    // 开启审核流
                    else {
                        // 设置状态 已提交审核
                        tradeWarehouseReceiptAppl.setWorkflowId(workflow.getId());
                        this.updateById(tradeWarehouseReceiptAppl);
                        workflowService.startInstance(workflow.getId(), tradeWarehouseReceiptAppl.getId());
                    }
                }
                // 退回的单子 再启用
                else {

                    this.updateById(tradeWarehouseReceiptAppl);
                    workflowService.activateInstance(tradeWarehouseReceiptAppl.getWorkflowId(), tradeWarehouseReceiptAppl.getId());
                }
            }
        }
        return tradeWarehouseReceiptAppl.getId();
    }


    /**
     * 查看
     *
     * @return
     */
    @Override
    public TradeWarehouseReceiptAppl getTrageInfo(String id){
        TradeWarehouseReceiptAppl tradeWarehouseReceiptAppl = this.selectById(id);
        String taskId = "";
        // 只有待审核状态才有taskId
        if (StringUtils.isNotBlank(tradeWarehouseReceiptAppl.getWorkflowId())) {
            JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(tradeWarehouseReceiptAppl.getWorkflowId()), tradeWarehouseReceiptAppl.getId());
            taskId = jsonObject.getString("taskId");
            tradeWarehouseReceiptAppl.setTaskId(taskId);
        }
        return tradeWarehouseReceiptAppl;
    }

    /**
     * 删除
     *
     * @return
     */
    @Override
    public void deleteTrageInfo(String id){
        TradeWarehouseReceiptAppl tradeWarehouseReceiptAppl = this.selectById(id);
        this.deleteById(tradeWarehouseReceiptAppl.getId());
    }





    /**
     * 可用库存
     *
     * @return
     */
//    @Override
//    public Float getInWeight(String id){
//        TradeWarehouseReceiptAppl tradeWarehouseReceiptAppl = this.selectById(id);
//        return tradeWarehouseReceiptAppl;
//    }


    /**
     * 单号
     *
     * @return
     */
    @Override
    public String getBillNo() {
        String billNo = "";
        String year = new SimpleDateFormat("yy", Locale.CHINESE).format(new Date());
        String month = new SimpleDateFormat("MM", Locale.CHINESE).format(new Date());
        String day = new SimpleDateFormat("dd",Locale.CHINESE).format(new Date());
        int count = this.selectCount(new EntityWrapper<TradeWarehouseReceiptAppl>()
                .eq("comp_id", AuthSecurityUtils.getCurrentUserInfo().getCompId()).and("date(create_date) = curdate()"));
        int maxCount =  count + 1;
        if (maxCount < 10) {
            billNo = year + month + day + "00" + maxCount;
        } else if (maxCount < 100) {
            billNo = year + month + day + "0" + maxCount;
        } else {
            billNo = year + month + day + maxCount;
        }
        return billNo;
    }


    private List<String> getResourceIdList() {
        User currentUser = AuthSecurityUtils.getCurrentUserInfo();
        // 当前登录人主要角色
        return roleResourceService.getBindResourcesByUserId(currentUser.getUserId()).stream()
                .map(CommonRoleResource::getResourceId).collect(Collectors.toList());
    }
}
