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


import com.unis.crk.aop.SystemLog;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.DataCrkywCpljyxxDefault;
import com.unis.crk.cplbusiness.entity.DataCrkywCpljyxxFlt001;
import com.unis.crk.cplbusiness.mapper.DataCrkywCpljyxxDefaultMapper;
import com.unis.crk.cplbusiness.service.IDataCrkywCpljyxxDefaultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.cplbusiness.service.IDataCrkywCpljyxxFlt001Service;
import com.unis.crk.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;

import java.util.*;

import org.springframework.transaction.annotation.Transactional;
import cn.hutool.json.JSONObject;
import javax.annotation.Resource;
import com.unis.crk.cplbusiness.entity.vo.DataCrkywCpljyxxDefaultVo;
/**
 * <p>
 * 成品粮抽样质检 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-03-21
 */
@Service
public class DataCrkywCpljyxxDefaultServiceImpl extends ServiceImpl<DataCrkywCpljyxxDefaultMapper, DataCrkywCpljyxxDefault> implements IDataCrkywCpljyxxDefaultService {

    @Resource
    private DataCrkywCpljyxxDefaultMapper dataCrkywCpljyxxDefaultMapper;
    @Resource
    private IDataCrkywCpljyxxFlt001Service dataCrkywCpljyxxFlt001Service;

    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    /**
     *修改成品粮抽样质检
     * @param param 成品粮抽样质检业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(DataCrkywCpljyxxDefault param){
        return null;
    }
    /**
     *删除成品粮抽样质检数据
     * @param id 成品粮抽样质检主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "成品化验", methods = "删除",uploadName = "cpl.zj")
    public JSONObject delete(String id){
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        //得到对象
        DataCrkywCpljyxxDefault dataCrkywCpljyxxDefault = super.getById(id);
        if (dataCrkywCpljyxxDefault == null){
            jsonObject.set("msg","此数据已被删除");
            return  jsonObject;
        }

        String unitId = dataCrkywCpljyxxDefault.getUnitid();
        QueryWrapper<DataCrkywCpljyxxFlt001> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("mainDataId",dataCrkywCpljyxxDefault.getDataId());
        List<DataCrkywCpljyxxFlt001> list = dataCrkywCpljyxxFlt001Service.list(deleteWrapper);

        if (dataCrkywCpljyxxFlt001Service.list(deleteWrapper).size() > 0){ //表示有从表数据
            Iterator<DataCrkywCpljyxxFlt001> iterator = list.iterator();
            while (iterator.hasNext()){
                deleteDataRecordService.save(iterator.next().getDataId(),"data_crkyw_cpljyxx_flt_001",iterator.next().getUnitid(),new Date());
            }
            if (!dataCrkywCpljyxxFlt001Service.remove(deleteWrapper)) {
//                    return  jsonObject;
            }
        }

        if (!super.removeById(id)) { //删除成功
            jsonObject.set("msg","删除汽车检验主表数据失败");
            return  jsonObject;
        }
        deleteDataRecordService.save(id,"data_crkyw_cpljyxx_default",dataCrkywCpljyxxDefault.getUnitid(),new Date());
        jsonObject.set("success",true);
        jsonObject.set("msg","删除成功");
        return jsonObject;
        }

    /**
     * 按照条件查询成品粮抽样质检信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataCrkywCpljyxxDefaultVo pageQuery){
        //条形查询器
        QueryWrapper<DataCrkywCpljyxxDefault> queryWrapper = new QueryWrapper<>();

            //分页相关
            if(StringUtils.isNotBlank(pageQuery.getUnitId())){
                queryWrapper.eq("a.unitId",pageQuery.getUnitId());
            }
            if(StringUtils.isNotBlank(pageQuery.getJydh())){
                queryWrapper.like("a.zljybhbh", ResultUtil.getQueryWrapperformat(pageQuery.getJydh()));
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlpzbh())){
                queryWrapper.eq("a.sjjlpzbh",pageQuery.getSjjlpzbh());
            }
            if(StringUtils.isNotBlank(pageQuery.getJyfs())){
                queryWrapper.eq("a.jyfs",pageQuery.getJyfs());
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlppbh())){
                queryWrapper.eq("a.sjjlppbh",pageQuery.getSjjlppbh());
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlspmc())){
                queryWrapper.like("a.sjjlspmc",ResultUtil.getQueryWrapperformat(pageQuery.getSjjlspmc()));
            }
            if (StringUtils.isNotBlank(pageQuery.getJysjStart()) && StringUtils.isNotBlank(pageQuery.getJysjEnd())){
                queryWrapper.apply(" DATE_FORMAT(ifnull(a.jysj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getJysjStart()+"' AND DATE_FORMAT(ifnull(a.jysj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getJysjEnd()+" 23:59:59'");

            }
        //分页相关
        Page<DataCrkywCpljyxxDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "成品化验", methods = "新增",uploadName = "cpl.zj")
    public JSONObject saveData(DataCrkywCpljyxxDefault dataCrkywCpljyxxDefault) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        String zljybhbh = dataCrkywCpljyxxDefault.getZljybhbh();
        if (isExist(zljybhbh)){
            jsonObject.set("msg","此检验单号已存在");
            return jsonObject;
        }
        String unitid = dataCrkywCpljyxxDefault.getUnitid();
        String zdbm = dataCrkywCpljyxxDefault.getZdbm();
        String zdmc = dataCrkywCpljyxxDefault.getZdmc();
        String builder = dataCrkywCpljyxxDefault.getBuilder();
        String editor = dataCrkywCpljyxxDefault.getEditor();
        dataCrkywCpljyxxDefault.setJysj(new Date());
        if (StringUtils.isBlank(dataCrkywCpljyxxDefault.getBuilder())){
            dataCrkywCpljyxxDefault.setBuilder(unitid);
            dataCrkywCpljyxxDefault.setEditor(unitid);
        }
        boolean b = super.saveOrUpdate(dataCrkywCpljyxxDefault);
        if (!b) {
            jsonObject.set("msg","保存成品粮化验主表数据失败");
            return  jsonObject;
        }
        //检验方式
        String jyfs = dataCrkywCpljyxxDefault.getJyfs();

        //保存从表信息
        List<DataCrkywCpljyxxFlt001> fltList = dataCrkywCpljyxxDefault.getFltList();
        List<DataCrkywCpljyxxFlt001> saveList = new ArrayList<>();
        if(!fltList.isEmpty() && fltList.size()>0){
            String dataId = dataCrkywCpljyxxDefault.getDataId();
            for (int i = 0; i < fltList.size(); i++) {

                DataCrkywCpljyxxFlt001 dataCrkywCpljyxxFlt001 = fltList.get(i);
                String jyz = dataCrkywCpljyxxFlt001.getJyz();
                if (StringUtils.equals("952731",jyfs) && StringUtils.isBlank(jyz)){
                   continue;
                }
                dataCrkywCpljyxxFlt001.setMainDataId(dataId);
                dataCrkywCpljyxxFlt001.setDeptId(unitid); //部门id
                dataCrkywCpljyxxFlt001.setUnitid(unitid); //
                if (StringUtils.isBlank(dataCrkywCpljyxxDefault.getBuilder())){
                    dataCrkywCpljyxxFlt001.setBuilder(unitid);
                    dataCrkywCpljyxxFlt001.setEditor(unitid);
                }else{
                    dataCrkywCpljyxxFlt001.setBuilder(builder);
                    dataCrkywCpljyxxFlt001.setEditor(editor);
                }
                saveList.add(dataCrkywCpljyxxFlt001);
            }
            if (!saveList.isEmpty()) {
                if (!dataCrkywCpljyxxFlt001Service.saveOrUpdateBatch(saveList)) { //保存成品粮化验从表数据失败
                    throw new Exception("保存成品粮化验从表数据失败");
                }
            }
        }
        jsonObject.set("success",true);
        jsonObject.set("msg","保存成功");
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "成品化验", methods = "修改",uploadName = "cpl.zj")
    public JSONObject updateData(DataCrkywCpljyxxDefault dataCrkywCpljyxxDefault) throws Exception {
        {
            {
                JSONObject jsonObject = new JSONObject();
                jsonObject.set("success",false);
                dataCrkywCpljyxxDefault.setUpdateTime(null);

                if (!super.updateById(dataCrkywCpljyxxDefault)) { //保存汽车化验主表成功
                    jsonObject.set("msg","修改成品粮化验主表数据失败");
                    return  jsonObject;
                }
                //删除从表相关信息
                QueryWrapper<DataCrkywCpljyxxFlt001> deleteWrapper = new QueryWrapper<>();
                deleteWrapper.eq("mainDataId",dataCrkywCpljyxxDefault.getDataId());
                List<DataCrkywCpljyxxFlt001> list = dataCrkywCpljyxxFlt001Service.list(deleteWrapper);
                if (dataCrkywCpljyxxFlt001Service.list(deleteWrapper).size() > 0){ //表示有从表数据
                    Iterator<DataCrkywCpljyxxFlt001> iterator = list.iterator();
                    while (iterator.hasNext()){
                        deleteDataRecordService.save(iterator.next().getDataId(),"data_crkyw_cpljyxx_flt_001",iterator.next().getUnitid(),new Date());
                    }
                    if (!dataCrkywCpljyxxFlt001Service.remove(deleteWrapper)) {
//                    return  jsonObject;
                    }
                }

                //保存从表信息
                String unitId = dataCrkywCpljyxxDefault.getUnitid();
                List<DataCrkywCpljyxxFlt001> fltList = dataCrkywCpljyxxDefault.getFltList();
                if (!fltList.isEmpty()){
                    String id_ = dataCrkywCpljyxxDefault.getDataId();
                    for (int i = 0; i < fltList.size(); i++) {
                        DataCrkywCpljyxxFlt001 dataCrkywCpljyxxFlt001 = fltList.get(i);
                        dataCrkywCpljyxxFlt001.setMainDataId(id_);
                        dataCrkywCpljyxxFlt001.setDeptId(unitId); //部门id
                        dataCrkywCpljyxxFlt001.setUnitid(unitId); //
                        if (StringUtils.isBlank(dataCrkywCpljyxxDefault.getBuilder())){
                            dataCrkywCpljyxxFlt001.setBuilder(unitId);
                            dataCrkywCpljyxxFlt001.setEditor(unitId);
                        }else{
                            dataCrkywCpljyxxFlt001.setBuilder(dataCrkywCpljyxxDefault.getBuilder());
                            dataCrkywCpljyxxFlt001.setEditor(dataCrkywCpljyxxDefault.getEditor());
                        }
                    }
                    if (!dataCrkywCpljyxxFlt001Service.saveOrUpdateBatch(fltList)) { //保存成品粮化验从表数据失败
                        throw  new Exception("修改成品粮化验从表数据失败");
//                        return  jsonObject;
                    }
                }
                jsonObject.set("success",true);
                jsonObject.set("msg","保存成功");
                return jsonObject;
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject deleteData(String id)  {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        //得到对象
        DataCrkywCpljyxxDefault dataCrkywCpljyxxDefault = super.getById(id);
        if (dataCrkywCpljyxxDefault == null){
            jsonObject.set("msg","此数据已被删除");
            return  jsonObject;
        }
        if (!super.removeById(id)) { //删除成功
            jsonObject.set("msg","删除成品粮检验主表数据失败");
            return  jsonObject;
        }
        deleteDataRecordService.save(id,"data_crkyw_cpljyxx_default",dataCrkywCpljyxxDefault.getUnitid(),new Date());

        jsonObject.set("success",true);
        jsonObject.set("msg","删除成功");
        return jsonObject;
    }

    @Override
    public DataCrkywCpljyxxDefault getOneData(String id) {
        DataCrkywCpljyxxDefault dataCrkywCpljyxxDefault = dataCrkywCpljyxxDefaultMapper.selectByIdgetOne(id);
        List<DataCrkywCpljyxxFlt001> list = dataCrkywCpljyxxFlt001Service.getLitByMainDatId(id);
        if(list !=null && list.size()>0){
            dataCrkywCpljyxxDefault.setFltList(list);
        }

        return dataCrkywCpljyxxDefault;
    }

    @Override
    public List getJyxxList(String unitId, String ywlx,String ddbh) {
        QueryWrapper<DataCrkywCpljyxxDefault> queryWrapper = new QueryWrapper<>();
        if(unitId!=null){
            queryWrapper.eq("a.unitid", unitId);
        }
        if(ywlx!=null){
            queryWrapper.eq("a.ywlx", ywlx);
        }
        if(ddbh!=null){
            queryWrapper.eq("a.ddbh", ddbh);
        }else {
        }
        queryWrapper.orderByDesc("a.cjsj");

        return dataCrkywCpljyxxDefaultMapper.getCplJyxxList(queryWrapper);
    }

    /**
     * 通过单位号检查是否已经存在
     *
     * @param zljybhbh
     * @return
     */
    private boolean isExist(String zljybhbh) {
        QueryWrapper<DataCrkywCpljyxxDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("zljybhbh", zljybhbh);
        queryWrapper.last("limit 1");
        return super.getOne(queryWrapper) != null;
    }

}
