package com.patzn.lims.drug.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.patzn.cloud.commons.api.RestAssert;
import com.patzn.lims.drug.entity.DrugAptitude;
import com.patzn.lims.drug.entity.DrugStandard;
import com.patzn.lims.drug.mapper.DrugAptitudeMapper;
import com.patzn.lims.drug.service.IDrugAptitudeService;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.drug.service.IDrugStandardService;
import com.patzn.lims.drug.vo.DrugAptitudeVO;
import com.patzn.lims.drug.vo.DrugCatalogueItemVO;
import com.patzn.lims.res.entity.LmsUserGroup;
import com.patzn.lims.res.service.ILmsUserGroupService;
import com.patzn.poibox.xwpf.HSSFWorkbookUtil;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * <p>
 * 食药资质项目表 服务实现类
 * </p>
 *
 * @author wwd
 * @since 2020-02-29
 */
@Service
public class DrugAptitudeServiceImpl extends BaseServiceImpl<DrugAptitudeMapper, DrugAptitude> implements IDrugAptitudeService {

    @Autowired
    private IDrugStandardService drugStandardService;
    @Autowired
    private ILmsUserGroupService lmsUserGroupService;

    @Override
    public Page<DrugAptitude> page(Page<DrugAptitude> page, DrugAptitude drugAptitude) {
        QueryWrapper<DrugAptitude> wrapper = Wrappers.<DrugAptitude>query(drugAptitude);

        if (StringUtils.isNotBlank(drugAptitude.getName())){
            wrapper.like("name",drugAptitude.getName());
            drugAptitude.setName(null);
        }

        if (StringUtils.isNotBlank(drugAptitude.getCode())){
            wrapper.like("code",drugAptitude.getCode());
            drugAptitude.setCode(null);
        }

        if (StringUtils.isNotBlank(drugAptitude.getGroupName())){
            wrapper.like("group_name",drugAptitude.getGroupName());
            drugAptitude.setGroupName(null);
        }
        return this.page(page, wrapper);
    }

    @Override
    public Page<DrugAptitude> pageForCatalogue(Page page, DrugAptitudeVO vo) {
        return baseMapper.selectForCatalogueList(page,vo);
    }

    @Override
    public Page<DrugAptitudeVO> pageCatalogueItem(Page page, DrugAptitudeVO vo) {
        return baseMapper.selectCatalogueItemList(page,vo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean importAptitudeItem(MultipartFile file) {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == workbook) {
            return false;
        }
        XSSFSheet sheet = workbook.getSheetAt(0);
        if (sheet == null) {
            return false;
        }
        int lastRowNum = sheet.getLastRowNum();


        List<DrugStandard> standardList=drugStandardService.list(Wrappers.<DrugStandard>query().select("id","code","name"));

        Map<String,Long> mapStandard=new HashMap<>();
        for (DrugStandard standard:standardList) {
            mapStandard.put(standard.getCode()+"***********"+standard.getName(),standard.getId());
        }
        List<DrugStandard> saveStandardList = new ArrayList<>();


        List<DrugAptitude> saveAptitudeItemList = new ArrayList<>();

        List<LmsUserGroup> userGroupList=  lmsUserGroupService.list();
        Map<String,Long> groupMap = new HashMap<>();
        for (LmsUserGroup userGroup:userGroupList) {
            groupMap.put(userGroup.getName(),userGroup.getId());
        }


        for (int i = 1; i <= lastRowNum; i++) {
            //标准号
            String product= HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(0)).toString();

            String name=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(1)).toString();
            RestAssert.fail(StringUtils.isBlank(name),"第"+i+"行数据，检测项目名称不能为空");


            String code=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(2)).toString();
            RestAssert.fail(StringUtils.isBlank(code),"第"+i+"行数据，检测依据不能为空");

            String standardName=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(3)).toString();
            RestAssert.fail(StringUtils.isBlank(standardName),"第"+i+"行数据，检测依据名称不能为空");


            String groupName=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(4)).toString();
            RestAssert.fail(StringUtils.isBlank(groupName),"第"+i+"行数据，检测科室不能为空");
              if (null == groupMap.get(groupName)){
                  RestAssert.fail(StringUtils.isBlank(groupName),"第"+i+"行数据，检测科室"+groupName+"不存在");
              }
            String judge=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(7)).toString();


            RestAssert.fail(org.apache.commons.lang3.StringUtils.isBlank(judge)||
                    !(judge.equalsIgnoreCase("是")||judge.equalsIgnoreCase("否")),"第"+i+"行数据，是否判定请填写‘是’或‘否’");

            if (mapStandard.get(code+"***********"+name)==null){
                  DrugStandard drugStandard = new DrugStandard();
                drugStandard.setName(name);
                drugStandard.setCode(code);
                drugStandard.setId(IdWorker.getId());
                saveStandardList.add(drugStandard);
                mapStandard.put(code+"***********"+name,drugStandard.getId());
            }
        }

        for (int i = 1; i <= lastRowNum; i++) {
            String product= HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(0)).toString();
            String name=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(1)).toString();
            String code=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(2)).toString();
            String standardName=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(3)).toString();
            String groupName=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(4)).toString();
            String compareSys=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(5)).toString();
            String limitValue=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(6)).toString();
            String judge=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(7)).toString();
            String unit=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(8)).toString();
            String remark=HSSFWorkbookUtil.getJavaValue(sheet.getRow(i).getCell(9)).toString();

            DrugAptitude drugAptitude=new DrugAptitude();

            drugAptitude.setCode(code);
            drugAptitude.setStandardName(standardName);
            drugAptitude.setStandardId(mapStandard.get(code));
            drugAptitude.setGroupId(groupMap.get(groupName));
            drugAptitude.setGroupName(groupName);
            drugAptitude.setName(name);
            drugAptitude.setUnit(unit);
            if (judge.equalsIgnoreCase("是")){
                drugAptitude.setJudged(1);
            }else if (judge.equalsIgnoreCase("否")){
                drugAptitude.setJudged(0);
            }
            drugAptitude.setCompareSymbol(compareSys);

            drugAptitude.setProduct(product);

            drugAptitude.setLimitValue(limitValue);
            drugAptitude.setRemark(remark);
            saveAptitudeItemList.add(drugAptitude);
        }


        if (CollectionUtils.isNotEmpty(saveAptitudeItemList)) {
            super.saveBatch(saveAptitudeItemList);
            drugStandardService.saveBatch(saveStandardList);
        }


        return true;
    }


    @Override
    public boolean deleteAptitudeByIds(Long[] id) {
        return remove(Wrappers.<DrugAptitude>query().in("id",id));
    }


}
