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

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
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.aop.SystemLog;
import com.unis.crk.basic.entity.BasicEnum;
import com.unis.crk.basic.entity.SysParams;
import com.unis.crk.basic.service.ISysParamsService;
import com.unis.crk.common.service.IBillnonewService;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.*;
import com.unis.crk.cplbusiness.entity.vo.LiAfterSaleVo;
import com.unis.crk.cplbusiness.mapper.LiAfterSaleMapper;
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 LiAfterSaleServiceImpl extends ServiceImpl<LiAfterSaleMapper, LiAfterSale> implements ILiAfterSaleService {
    @Resource
    private LiAfterSaleMapper  liAfterSaleMapper;


    @Autowired
    private IDataCrkywCplrkFlt001Service iDataCrkywCplrkFlt001Service;
    @Autowired
    private ISysParamsService sysParamsService;

    @Autowired
    private IDataCrkywCplrkDefaultService iDataCrkywCplrkDefaultService;
    @Autowired
    private IDataCrkywCplckDefaultService iDataCrkywCplckDefaultService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    @Autowired
    private IDataCrkywCplrkFlt001Service dataCrkywCplrkFlt001Service;
    @Autowired
    private IBillnonewService billnonewService;
    @Override
    public LiAfterSale getByIdgetSale(String id) {
        LiAfterSale byId = this.getById(id);
        String sn = byId.getSn();//售后订单号
        String orderSn = byId.getOrderSn();//订单号
        String unitid = byId.getUnitid();
        ArrayList<DataCrkywCplckDefault> dataCrkywCplckDefaults = new ArrayList<>();
        QueryWrapper<DataCrkywCplckDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ddbh",orderSn);
        List<DataCrkywCplckDefault> list = iDataCrkywCplckDefaultService.list(queryWrapper);
        Iterator<DataCrkywCplckDefault> iterator = list.iterator();
        while (iterator.hasNext()){
            DataCrkywCplckDefault next = iterator.next();
            String dataId = next.getDataId();
            DataCrkywCplckDefault oneData = iDataCrkywCplckDefaultService.getOneData(dataId);
            dataCrkywCplckDefaults.add(oneData);

        }
        byId.setCkList(dataCrkywCplckDefaults);

        if(byId.getIsFh().equals("0")){
            QueryWrapper<DataCrkywCplrkDefault> queryWrapperrk = new QueryWrapper<>();
            queryWrapper.eq("ddbh",orderSn);
            DataCrkywCplrkDefault one = iDataCrkywCplrkDefaultService.getOne(queryWrapperrk);
            byId.setRk(one);
        }else{
            String dataid= IdUtil.simpleUUID();
            ArrayList<DataCrkywCplrkFlt001> dataCrkywCplrkFlt001s = new ArrayList<>();
            DataCrkywCplrkDefault dataCrkywCplrkDefault = new DataCrkywCplrkDefault();
            dataCrkywCplrkDefault.setDataId(dataid);
            dataCrkywCplrkDefault.setUnitid(dataCrkywCplrkDefault.getUnitid());
            dataCrkywCplrkDefault.setYwlx("9528226");
            dataCrkywCplrkDefault.setIsstaging("1");
            dataCrkywCplrkDefault.setCazylx("11");
            dataCrkywCplrkDefault.setDdbh(byId.getSn());
            DataCrkywCplrkFlt001 dataCrkywCplrkFlt001 = new DataCrkywCplrkFlt001();
            dataCrkywCplrkFlt001.setMainDataId(dataid);
            dataCrkywCplrkFlt001.setUnitid(dataCrkywCplrkDefault.getUnitid());
            dataCrkywCplrkFlt001.setDataId(byId.getId());
            dataCrkywCplrkFlt001.setXz("952751");
            dataCrkywCplrkFlt001.setUnitid(dataCrkywCplrkDefault.getUnitid());
            dataCrkywCplrkFlt001s.add(dataCrkywCplrkFlt001);
            dataCrkywCplrkDefault.setFltList(dataCrkywCplrkFlt001s);
            byId.setRk(dataCrkywCplrkDefault);
        }


        return byId;
    }

    @Override
    public IPage<Map<String, Object>> findPageVo(LiAfterSaleVo pageQuery) {
        QueryWrapper<LiAfterSale> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(
                "id",
                "create_by",
                "create_time",
                "delete_flag",
                "update_by",
                "update_time",
                "actual_refund_price",
                "apply_refund_price",
                "flow_price",
                "goods_id",
                "goods_name",
                "member_id",
                "member_name",
                "num",
                "order_sn",
                "store_id",
                "store_name",
                "service_status",
                "sn",
                "order_item_sn",
                "IS_FH"


                );
        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<LiAfterSale> p = new Page<>(pageQuery.getPage(), pageQuery.getLimit());

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveOrAfter(LiAfterSale param) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        param.setIsFh("0");
        this.saveOrUpdate(param);
        String unitid = param.getUnitid();
        String id = param.getId();
        DataCrkywCplrkDefault rk = param.getRk();
        String cplrkBizNo = billnonewService.getCplrkBizNo(unitid);
        rk.setRkbh(cplrkBizNo);
        boolean save = iDataCrkywCplrkDefaultService.save(rk);
        System.out.println(save);
        List<DataCrkywCplrkFlt001> fltList = rk.getFltList();
        Iterator<DataCrkywCplrkFlt001> iterator = fltList.iterator();
        while (iterator.hasNext()){
                DataCrkywCplrkFlt001 next = iterator.next();
                String scpc = next.getScpc();
                next.setUnitid(unitid);// 设置单位id
                SysParams byId = sysParamsService.getById("sy.url");
                String paramVal = byId.getParamVal();
                String syurl=paramVal+"/"+unitid+"/"+rk.getCh()+"/"+rk.getHwh()+"/"+next.getSjjlspmcbh()+"/"+rk.getRkbh()+"/"+next.getScpc();
                next.setSyurl(syurl);
                iDataCrkywCplrkFlt001Service.saveFlt(next);
        }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "电商退货入库", methods = "删除",uploadName = "cpl.dsrk")
    public JSONObject deleteLiAfterServiceImplRk(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        LiAfterSale byId = super.getById(id);
        if (byId == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        byId.setIsFh("1");

        this.saveOrUpdate(byId);
        QueryWrapper<DataCrkywCplrkDefault> queryWrapperrk = new QueryWrapper<>();
        queryWrapperrk.eq("ddbh",byId.getSn());
        DataCrkywCplrkDefault one = iDataCrkywCplrkDefaultService.getOne(queryWrapperrk);//
        String dataId = one.getDataId();
        deleteDataRecordService.save(id,"data_crkyw_cplrk_default",one.getUnitid(),new Date());

        //得到从表数据
        QueryWrapper<DataCrkywCplrkFlt001> flt001QueryWrapper = new QueryWrapper<>();
        flt001QueryWrapper.eq("mainDataId",dataId);
        List<DataCrkywCplrkFlt001> flt001s = dataCrkywCplrkFlt001Service.list(flt001QueryWrapper);
        if (flt001s != null || flt001s.size() > 0){
            for (int i = 0; i < flt001s.size(); i++) {
                //保存从表数据，有错误抛异常
                DataCrkywCplrkFlt001 flt001 = flt001s.get(i);
                dataCrkywCplrkFlt001Service.deleteFlt(flt001.getDataId());
            }
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
    }

}