package com.nantian.cloud.jly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nantian.cloud.jly.entity.CheckEnterprice;
import com.nantian.cloud.jly.service.CheckEnterpriceReportService;
import com.nantian.cloud.jly.service.CheckEnterpriceService;
import com.nantian.sc.cloud.common.core.util.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantian.cloud.jly.entity.CheckAudit;
import com.nantian.cloud.jly.entity.InspectionData;
import com.nantian.cloud.jly.mapper.InspectionDataMapper;
import com.nantian.cloud.jly.service.CheckAuditService;
import com.nantian.cloud.jly.service.InspectionDataService;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.Date;


/**
 * @date 2018-09-27
 */
@Service("InspectionDataService")
public class InspectionDataServiceImpl extends ServiceImpl<InspectionDataMapper, InspectionData> implements InspectionDataService {

    @Autowired
    private CheckAuditService checkAuditService;

    @Autowired
    private CheckEnterpriceService checkEnterpriceService;

    public InspectionData getByPlanIdAndEpc(BigInteger checkPlanId, String enterpriseCode) {
        return baseMapper.getByPlanIdAndEpc(checkPlanId, enterpriseCode);
    }

    @Override
    public boolean upload(String uuid, String type, BigInteger checkPlanId, String enterpriseCode) {
        InspectionData inspectionData = new InspectionData();
        inspectionData.setCheckPlanId(checkPlanId);
        inspectionData.setEnterpriseCode(enterpriseCode);

        int i = 0;
        InspectionData oldData = baseMapper.selectOne(Wrappers.query(inspectionData));
        ScUser u = SecurityUtils.getUser();
        if (oldData != null) { //修改
            //oldData = uploadByType(uuid, type, oldData);
            if (u.getId() != null) {
                oldData.setUserid(u.getId());
            }
            oldData.setUpdateTime(new Date());
            i = baseMapper.updateById(uploadByType(uuid, type, oldData,""));
            System.err.println("oldDate：" + oldData);
        } else { //新增
            //inspectionData =  uploadByType(uuid, type, inspectionData);
            if (u.getId() != null) {
                inspectionData.setUserid(u.getId());
            }
            inspectionData.setUpdateTime(new Date());
            inspectionData.setDelFlag("1");
            i = baseMapper.insert(uploadByType(uuid, type, inspectionData,""));
            System.err.println("inspectionData：" + inspectionData);
        }

        return i == 0 ? false : true;
    }

    @Override
    public R audit(BigInteger id, String state, String status, String info,String mendFile) {
        CheckAudit checkAudit = new CheckAudit();
        InspectionData inspectionData = this.getById(id);
        int type = 0;

        if (inspectionData == null) {
            return R.failed("查找18项资料中间表失败");
        }

        if (state == null) {
            return R.failed("state参数不能为null");
        } else {
            if ("basicInformationState".equals(state)) {
                inspectionData.setBasicInformationState(status);
                type = 1;
            } else if ("energyMeteringReportState".equals(state)) {
                inspectionData.setEnergyMeteringReportState(status);
                type = 2;
            } else if ("measurementManagementSystemState".equals(state)) {
                inspectionData.setMeasurementManagementSystemState(status);
                type = 3;
            } else if ("energyStatisticsStatementState".equals(state)) {
                inspectionData.setEnergyStatisticsStatementState(status);
                type = 4;
            } else if ("energyMeteringPersonnelState".equals(state)) {
                inspectionData.setEnergyMeteringPersonnelState(status);
                type = 5;
            } else if ("energyusingEquipmentState".equals(state)) {
                inspectionData.setEnergyusingEquipmentState(status);
                type = 6;
            } else if ("energyMeasuringInstrumentsState".equals(state)) {
                inspectionData.setEnergyMeasuringInstrumentsState(status);
                type = 7;
            } else if ("measuringInstrumentsState".equals(state)) {
                inspectionData.setMeasuringInstrumentsState(status);
                type = 8;
            } else if ("secondaryMeasuringInstrumentState".equals(state)) {
                inspectionData.setSecondaryMeasuringInstrumentState(status);
                type = 9;
            } else if ("mainMeasuringInstrumentState".equals(state)) {
                inspectionData.setMainMeasuringInstrumentState(status);
                type = 10;
            } else if ("otherMeasuringInstrumentsState".equals(state)) {
                inspectionData.setOtherMeasuringInstrumentsState(status);
                type = 11;
            } else if ("equippedSituationState".equals(state)) {
                inspectionData.setEquippedSituationState(status);
                type = 12;
            } else if ("accuracyGradeState".equals(state)) {
                inspectionData.setAccuracyGradeState(status);
                type = 13;
            } else if ("inventoryStatusState".equals(state)) {
                inspectionData.setInventoryStatusState(status);
                type = 14;
            } else if ("energyFlowState".equals(state)) {
                inspectionData.setEnergyFlowState(status);
                type = 15;
            } else if ("collectionPointNetworkState".equals(state)) {
                inspectionData.setCollectionPointNetworkState(status);
                type = 16;
            } else if ("valuesTransferState".equals(state)) {
                inspectionData.setValuesTransferState(status);
                type = 17;
            } else if ("rootsDiagramState".equals(state)) {
                inspectionData.setRootsDiagramState(status);
                type = 18;
            } else {
                return R.failed("sate参数有误，无法匹配18项材料的state");
            }
        }

        ScUser u = SecurityUtils.getUser();
        inspectionData.setUserid(u.getId());
        inspectionData.setDeptId(u.getDeptId());
        inspectionData.setUpdateTime(new Date());

        boolean b = this.updateById(inspectionData);
        if (!b) {
            return R.failed("修改18项资料中间表失败");
        }

        checkAudit.setType(type + "");
        checkAudit.setCheckPlanId(inspectionData.getCheckPlanId());
        checkAudit.setEpc(inspectionData.getEnterpriseCode());
        /*CheckAudit oldCheckAudit = checkAuditService.getOne(Wrappers.query(checkAudit));

        if (oldCheckAudit == null) {
            oldCheckAudit = new CheckAudit();
            oldCheckAudit.setType(type + "");
            oldCheckAudit.setCheckPlanId(inspectionData.getCheckPlanId());
            oldCheckAudit.setEpc(inspectionData.getEnterpriseCode());
        }*/
        checkAudit.setDeptId(u.getDeptId());
        checkAudit.setUserid(u.getId());
        checkAudit.setCheckTime(new Date());
        checkAudit.setUpdateTime(new Date());
        checkAudit.setCheckResult(info);
        checkAudit.setCheckPerson(u.getUsername());
        checkAudit.setState("Y".equals(status) ? "T" : "F");
        checkAudit.setMendFile("Y".equals(status) ? "" : mendFile);

        boolean b2 = checkAuditService.saveOrUpdate(checkAudit);
        if (!b2) {
            return R.failed("更新审核意见表失败");
        }
        if ("Y".equals(inspectionData.getBasicInformationState())
                && "Y".equals(inspectionData.getEnergyMeteringReportState())
                && "Y".equals(inspectionData.getMeasurementManagementSystemState())
                && "Y".equals(inspectionData.getEnergyStatisticsStatementState())
                && "Y".equals(inspectionData.getEnergyMeteringPersonnelState())
                && "Y".equals(inspectionData.getEnergyusingEquipmentState())
                && "Y".equals(inspectionData.getEnergyMeasuringInstrumentsState())
                && "Y".equals(inspectionData.getMeasuringInstrumentsState())
                && "Y".equals(inspectionData.getSecondaryMeasuringInstrumentState())
                && "Y".equals(inspectionData.getMainMeasuringInstrumentState())
                && "Y".equals(inspectionData.getOtherMeasuringInstrumentsState())
                && "Y".equals(inspectionData.getEquippedSituationState())
                && "Y".equals(inspectionData.getAccuracyGradeState())
                && "Y".equals(inspectionData.getInventoryStatusState())
                && "Y".equals(inspectionData.getEnergyFlowState())
                && "Y".equals(inspectionData.getCollectionPointNetworkState())
                && "Y".equals(inspectionData.getValuesTransferState())
                && "Y".equals(inspectionData.getRootsDiagramState())) {
            CheckEnterprice e = new CheckEnterprice();
            e.setDelFlag("1");
            e.setCheckPlanId(inspectionData.getCheckPlanId());   //问题
            e.setEpc(inspectionData.getEnterpriseCode());
            QueryWrapper<CheckEnterprice> t = new QueryWrapper(e);
            CheckEnterprice o = checkEnterpriceService.getOne(t);
            if (o == null) {
                return R.failed("更新企业审查状态失败！");
            }
            //e.setCheckStatus("2");
            e.setUpdateTime(new Date());
            e.setUserid(u.getId());
            e.setId(o.getId());
            if (checkEnterpriceService.updateById(e)) {
                return R.ok();
            } else {
                return R.failed("更新企业审查状态失败！");
            }

        }
        return R.ok();
    }

    @Override
    public R uploadFiles(String type, BigInteger checkPlanId, String enterpriseCode, String flieList,String mend) {
        InspectionData inspectionData = new InspectionData();
        inspectionData.setCheckPlanId(checkPlanId);
        inspectionData.setEnterpriseCode(enterpriseCode);
        inspectionData.setDelFlag("1");

        int i = 0;
        InspectionData oldData = baseMapper.selectOne(Wrappers.query(inspectionData));
        ScUser u = SecurityUtils.getUser();
        if (oldData != null) { //修改
            if (u.getId() != null) {
                oldData.setUserid(u.getId());
            }
            oldData.setUpdateTime(new Date());
            i = baseMapper.updateById(uploadByType(flieList, type, oldData,mend));
            System.err.println("oldDate：" + oldData);
        } else { //新增
            //inspectionData =  uploadByType(uuid, type, inspectionData);
            if (u.getId() != null) {
                inspectionData.setUserid(u.getId());
            }
            inspectionData.setUpdateTime(new Date());
            inspectionData.setDelFlag("1");
            i = baseMapper.insert(uploadByType(flieList, type, inspectionData,mend));
            System.err.println("inspectionData：" + inspectionData);
        }

        return i == 0 ? R.failed() : R.ok("保存成功");
    }

    @Override
    public R resetState(BigInteger id, String state, String status, String info, String mendFile) {
        InspectionData inspectionData = this.getById(id);
        if (inspectionData == null) {
            return R.failed("查找18项资料中间表失败");
        }

        if (state == null) {
            return R.failed("state参数不能为null");
        } else {
            if ("basicInformationState".equals(state)) {
                inspectionData.setBasicInformationState(status);
            } else if ("energyMeteringReportState".equals(state)) {
                inspectionData.setEnergyMeteringReportState(status);
            } else if ("measurementManagementSystemState".equals(state)) {
                inspectionData.setMeasurementManagementSystemState(status);
            } else if ("energyStatisticsStatementState".equals(state)) {
                inspectionData.setEnergyStatisticsStatementState(status);
            } else if ("energyMeteringPersonnelState".equals(state)) {
                inspectionData.setEnergyMeteringPersonnelState(status);
            } else if ("energyusingEquipmentState".equals(state)) {
                inspectionData.setEnergyusingEquipmentState(status);
            } else if ("energyMeasuringInstrumentsState".equals(state)) {
                inspectionData.setEnergyMeasuringInstrumentsState(status);
            } else if ("measuringInstrumentsState".equals(state)) {
                inspectionData.setMeasuringInstrumentsState(status);
            } else if ("secondaryMeasuringInstrumentState".equals(state)) {
                inspectionData.setSecondaryMeasuringInstrumentState(status);
            } else if ("mainMeasuringInstrumentState".equals(state)) {
                inspectionData.setMainMeasuringInstrumentState(status);
            } else if ("otherMeasuringInstrumentsState".equals(state)) {
                inspectionData.setOtherMeasuringInstrumentsState(status);
            } else if ("equippedSituationState".equals(state)) {
                inspectionData.setEquippedSituationState(status);
            } else if ("accuracyGradeState".equals(state)) {
                inspectionData.setAccuracyGradeState(status);
            } else if ("inventoryStatusState".equals(state)) {
                inspectionData.setInventoryStatusState(status);
            } else if ("energyFlowState".equals(state)) {
                inspectionData.setEnergyFlowState(status);
            } else if ("collectionPointNetworkState".equals(state)) {
                inspectionData.setCollectionPointNetworkState(status);
            } else if ("valuesTransferState".equals(state)) {
                inspectionData.setValuesTransferState(status);
            } else if ("rootsDiagramState".equals(state)) {
                inspectionData.setRootsDiagramState(status);
            } else {
                return R.failed("sate参数有误，无法匹配18项材料的state");
            }
        }

        ScUser u = SecurityUtils.getUser();
        inspectionData.setUserid(u.getId());
        inspectionData.setDeptId(u.getDeptId());
        inspectionData.setUpdateTime(new Date());

        boolean b = this.updateById(inspectionData);
        if (!b) {
            return R.failed("修改18项资料中间表失败");
        }else {
            return R.failed("重置成功");
        }
    }


    /**
     * 文件类型（1：本单位基本情况和组织机构设置框图，2：能源计量工作自查报告，
     * 3：能源计量管理制度，4：相关审查报告，5：能源流向图，6：能源计量器具配备及计量采集点网络图，
     * 7：能源计量器具自行检定装置量值传递/溯源框图，8：能源计量器具量值传递/溯源框图
     */
    private InspectionData uploadByType(String uuid, String type, InspectionData inspection,String mend) {
        if ("".equals(uuid)){
            uuid="D";
        }
        switch (type) {
            case "1":
                inspection.setBasicInformation(uuid);
                if ("Z".equals(mend)) {
                    inspection.setBasicInformationState("Z");
                }
                break;
            case "2":
                inspection.setEnergyMeteringReport(uuid);
                if ("Z".equals(mend)) {
                    inspection.setEnergyMeteringReportState("Z");
                }
                break;
            case "3":
                inspection.setMeasurementManagementSystem(uuid);
                if ("Z".equals(mend)) {
                    inspection.setMeasurementManagementSystemState("Z");
                }
                break;
            case "4":
                inspection.setEnergyStatisticsStatement(uuid);
                if ("Z".equals(mend)) {
                    inspection.setEnergyStatisticsStatementState("Z");
                }
                break;
            case "5":
                inspection.setEnergyFlow(uuid);
                if ("Z".equals(mend)) {
                    inspection.setEnergyFlowState("Z");
                }
                break;
            case "6":
//                if (inspection.getCollectionPointNetwork() != "D") {
//                    String sun = inspection.getCollectionPointNetwork()+","+uuid;
//                    inspection.setCollectionPointNetwork(sun);
//                } else {
                    inspection.setCollectionPointNetwork(uuid);
                if ("Z".equals(mend)) {
                    inspection.setCollectionPointNetworkState("Z");
                }
//                }
                break;
            case "7":
                inspection.setValuesTransfer(uuid);
                if ("Z".equals(mend)) {
                    inspection.setValuesTransferState("Z");
                }
                break;
            case "8":
                inspection.setRootsDiagram(uuid);
                if ("Z".equals(mend)) {
                    inspection.setRootsDiagramState("Z");
                }
                break;
            default:
                break;
        }
        return inspection;
    }

}

