package com.unis.crk.cplbusiness.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unis.crk.common.service.IBillnonewService;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.DataCrkywCplckDefault;
import com.unis.crk.cplbusiness.entity.DataCrkywCplckFlt001;
import com.unis.crk.cplbusiness.entity.LiOrder;
import com.unis.crk.cplbusiness.entity.LiOrderItem;
import com.unis.crk.cplbusiness.entity.vo.LiOrderVo;
import com.unis.crk.cplbusiness.mapper.LiOrderMapper;
import com.unis.crk.cplbusiness.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ghh
 * @since 2023-01-20
 */
@Service
public class LiOrderServiceImpl extends ServiceImpl<LiOrderMapper, LiOrder> implements ILiOrderService {
    @Resource
    private LiOrderMapper  liOrderMapper;

    @Autowired
    private ILiOrderItemService iLiOrderItemService;
    
    @Autowired
    IDataCrkywCplckFlt001Service iDataCrkywCplckFlt001Service;
    @Autowired
    IDataCrkywCplckDefaultService iDataCrkywCplckDefaultService;
    @Autowired
    private IDataKcglCplxckcDefaultService dataKcglCplxckcDefaultService;
    @Autowired
    private IDataCrkywCplckFlt001Service dataCrkywCplckFlt001Service;

    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    @Autowired
    private IBillnonewService illnonewService;
    /**
     * 根据条件分页查询
     * @param pageQuery
     * @return
     */
    @Override
    public IPage<Map<String, Object>> findPageVo(LiOrderVo pageQuery) {
        //条形查询器
        QueryWrapper<LiOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id",
                "create_by",
                "create_time",
                "update_by",
                "update_time",
                "consignee_address_id_path",
                "consignee_detail",
                "consignee_mobile",
                "consignee_name",
                "goods_num",
                "goods_price",
                "goods_names",
                "member_name",
                "order_status",
                "store_id",
                "store_name",
                "sn",
                "weight",
                "IS_FH",
                "UNITID");
        if(StringUtils.isNotBlank(pageQuery.getUnitId())){
            queryWrapper.eq("UNITID",pageQuery.getUnitId());
        }
        if(StringUtils.isNotBlank(pageQuery.getGoodsName())){
            queryWrapper.like("GOODS_NAMES", ResultUtil.getQueryWrapperformat(pageQuery.getGoodsName()));
        }
        if(StringUtils.isNotBlank(pageQuery.getSn())){
            queryWrapper.like("SN", ResultUtil.getQueryWrapperformat(pageQuery.getSn()));
        }
        if(StringUtils.isNotBlank(pageQuery.getIsFh())){
            queryWrapper.like("IS_FH",ResultUtil.getQueryWrapperformat(pageQuery.getIsFh()));
        }
        if (StringUtils.isNotBlank(pageQuery.getJysjStart()) && StringUtils.isNotBlank(pageQuery.getJysjEnd())){
            queryWrapper.apply(" DATE_FORMAT(ifnull(create_time,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getJysjStart()+"' AND DATE_FORMAT(ifnull(create_time,NOW()),'%Y-%m-%d') <= '"+pageQuery.getJysjEnd()+" 23:59:59'");

        }
        queryWrapper.orderByDesc("create_time");
        //分页相关
        Page<LiOrder> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

        IPage<Map<String,Object>> page =this.pageMaps(p,queryWrapper);
        return page;
    }

    @Override
    public LiOrder getByIdGetOrder(String id) {
        LiOrder byId = this.getById(id);
        String sn = byId.getSn();
            //查询订单子表数据
        if(StringUtils.isNotBlank(byId.getSn())){
            QueryWrapper<LiOrderItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ORDER_SN",sn);
            List<LiOrderItem> list = iLiOrderItemService.list(queryWrapper);
            byId.setOrderItemList(list);
        }
        //查询订单出库数据
        if(byId.getIsFh().equals("0")){
            QueryWrapper<DataCrkywCplckDefault> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ddbh",sn);
            List<DataCrkywCplckDefault> list = iDataCrkywCplckDefaultService.list(queryWrapper);
            if(list.size()>0){
                Iterator<DataCrkywCplckDefault> iterator = list.iterator();
                ArrayList<DataCrkywCplckDefault> dataCrkywCplckDefaults = new ArrayList<>();
                if(iterator.hasNext()){
                    DataCrkywCplckDefault next = iterator.next();
                    String dataId = next.getDataId();
                    DataCrkywCplckDefault oneData = iDataCrkywCplckDefaultService.getOneData(dataId);
                    dataCrkywCplckDefaults.add(oneData);

                }
                byId.setCplckFltList(dataCrkywCplckDefaults);
            }
        }else{
            //若未出库，创建出库数据模型
            ArrayList<DataCrkywCplckDefault> dataCrkywCplckDefaults = new ArrayList<>();
            List<LiOrderItem> orderItemList = byId.getOrderItemList();
            int size = orderItemList.size();
            for(int i=0;i<size;i++){
                List<DataCrkywCplckFlt001> dataCrkywCplckFlt001s = new ArrayList<>();
                LiOrderItem liOrderItem = orderItemList.get(i);
                //创建出库主表模型
                DataCrkywCplckDefault dataCrkywCplckDefault = new DataCrkywCplckDefault();
                dataCrkywCplckDefault.setDataId(liOrderItem.getId());
                dataCrkywCplckDefault.setDdbh(sn);
                dataCrkywCplckDefault.setKhmc(byId.getConsigneeName());
                dataCrkywCplckDefault.setUnitid(byId.getUnitid());
                dataCrkywCplckDefault.setYwlx("9528215");
                dataCrkywCplckDefault.setIsstaging("1");
                dataCrkywCplckDefault.setCazylx("4");
                dataCrkywCplckDefault.setCkbh(illnonewService.getCplckBizNo(byId.getUnitid()));
                //创建出库从表模型
                DataCrkywCplckFlt001 dataCrkywCplckFlt001 = new DataCrkywCplckFlt001();
                dataCrkywCplckFlt001.setMainDataId(liOrderItem.getId());
                dataCrkywCplckFlt001.setDj(liOrderItem.getUnitPrice().doubleValue());
                dataCrkywCplckFlt001.setUnitid(byId.getUnitid());
                dataCrkywCplckFlt001.setXz("952751");
                dataCrkywCplckFlt001s.add(dataCrkywCplckFlt001);
                dataCrkywCplckDefault.setFltList(dataCrkywCplckFlt001s);
                dataCrkywCplckDefaults.add(dataCrkywCplckDefault);
            }
            byId.setCplckFltList(dataCrkywCplckDefaults);
        }
        return byId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveOrder(LiOrder liOrder) throws Exception{

        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        this.saveOrUpdate(liOrder);
        String id = liOrder.getId();
        List<LiOrderItem> orderItemList = liOrder.getOrderItemList();
        if(orderItemList.size()<0){
            jsonObject.set("msg","次订单无子表数据");
            return jsonObject;
        }
        List<DataCrkywCplckDefault> cplckList = liOrder.getCplckFltList();
        Iterator<DataCrkywCplckDefault> iterator = cplckList.iterator();
        while (iterator.hasNext()){
            DataCrkywCplckDefault next = iterator.next();
            iDataCrkywCplckDefaultService.saveCk(next);
        }

        jsonObject.set("success", true);
        jsonObject.set("msg", "保存成功");
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject deleteOrderCk(String id) throws  Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        LiOrder byId = this.getById(id);
        byId.setIsFh("1");
        String sn = byId.getSn();
        this.saveOrUpdate(byId);
        QueryWrapper<DataCrkywCplckDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ddbh",sn);
        List<DataCrkywCplckDefault> list = iDataCrkywCplckDefaultService.list(queryWrapper);
        Iterator<DataCrkywCplckDefault> iterator = list.iterator();
        if(iterator.hasNext()){
            DataCrkywCplckDefault next = iterator.next();
            String dataId = next.getDataId();
            if (!iDataCrkywCplckDefaultService.removeById(id)) { //删除成品粮入库数据失败
                jsonObject.set("msg", "删除成品粮入库数据失败");
                return jsonObject;
            }
            deleteDataRecordService.save(id,"data_crkyw_cplck_default",next.getUnitid(),new Date());
            QueryWrapper<DataCrkywCplckFlt001> flt001QueryWrapper = new QueryWrapper<>();
            flt001QueryWrapper.eq("mainDataId",dataId);
            List<DataCrkywCplckFlt001> flt001s = dataCrkywCplckFlt001Service.list(flt001QueryWrapper);
            if (flt001s != null || flt001s.size() > 0){
                for (int i = 0; i < flt001s.size(); i++) {
                    //保存从表数据，有错误抛异常
                    DataCrkywCplckFlt001 flt001 = flt001s.get(i);
                    dataCrkywCplckFlt001Service.deleteFlt(flt001.getDataId());
                    deleteDataRecordService.save(flt001.getDataId(),"data_crkyw_cplck_flt_001",flt001.getUnitid(),new Date());
                }
            }
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
    }
}
