package com.emr.service.templateSearch;

import com.emr.dao.CommomMapper;
import com.emr.dao.Emr_DictionaryMapper;
import com.emr.dao.approve.Emr_Apply_ApproveMapper;
import com.emr.dao.recordLock.Emr_LockMapper;
import com.emr.dao.templateSearch.Emr_CustomizeMapper;
import com.emr.dao.templateSearch.Emr_ModleMapper;
import com.emr.dao.templateSearch.Emr_Modle_RelatedMapper;
import com.emr.entity.Emr_Dictionary;
import com.emr.entity.Power_User;
import com.emr.entity.approve.Emr_Apply_Approve;
import com.emr.entity.recordLock.Emr_Lock;
import com.emr.entity.templateSearch.Emr_Customize;
import com.emr.entity.templateSearch.Emr_Modle;
import com.emr.entity.templateSearch.Emr_Modle_Related;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/5/21 17:12
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/5/21 17:12
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Service
@Transactional
public class TemplateSearchServiceImpl implements TemplateSearchService {
    @Autowired
    private Emr_CustomizeMapper customizeMapper;
    @Autowired
    private Emr_ModleMapper emrModleMapper;
    @Autowired
    private Emr_Modle_RelatedMapper emrModleRelatedMapper;
    @Autowired
    private CommomMapper commomMapper;
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public int addTemplate(Emr_Customize record, HttpServletRequest request) {
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        record.setCreater(userName);
        record.setUpdater(userName);
        record.setCreateTime(fmt.format(new Date()));
        record.setUpdateTime(fmt.format(new Date()));
        return customizeMapper.insert(record);
    }

    @Override
    public void updateTemplate(Emr_Customize record,HttpServletRequest request) {
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        record.setUpdater(userName);
        record.setUpdateTime(fmt.format(new Date()));
        customizeMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public void deleteTemplate(Integer id) {
        customizeMapper.deleteByPrimaryKey(id);
        //删除关系表
        emrModleRelatedMapper.deleteByCustomizeId(id);
    }

    @Override
    public int addTemplateSelect(Emr_Modle emrModle,HttpServletRequest request) {
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        if(emrModle.getSelectFlag() == 1){
            Emr_Modle modle = emrModleMapper.selectFlagExist(userName);
            //先把该用户有设置的默认模板selectFlag= 1置成0
            if(null != modle){
                modle.setSelectFlag(0);
                emrModleMapper.updateByPrimaryKeySelective(modle);
            }else{
                emrModle.setSelectFlag(1);
            }
        }
        emrModle.setCreater(userName);
        emrModle.setUpdater(userName);
        emrModle.setCreateTime(fmt.format(new Date()));
        emrModle.setUpdateTime(fmt.format(new Date()));
        return emrModleMapper.insert(emrModle);
    }

    @Override
    public void updateTemplateSelect(Emr_Modle emrModle,Integer selectFlagId,HttpServletRequest request) {
        //如果不是该默认模板且修改为默认，则取消原来默认
        Integer selectFlag = emrModle.getSelectFlag();
        if(null != selectFlagId && selectFlag == 1 && emrModle.getId() != selectFlagId){
            Emr_Modle emr_modleSelected = emrModleMapper.selectByPrimaryKey(selectFlagId);
            emr_modleSelected.setSelectFlag(0);
            emrModleMapper.updateByPrimaryKeySelective(emr_modleSelected);
        }
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        emrModle.setUpdater(userName);
        emrModle.setUpdateTime(fmt.format(new Date()));
        emrModleMapper.updateByPrimaryKeySelective(emrModle);
    }

    @Override
    public void updateTemplateSelect(Emr_Modle emrModle,HttpServletRequest request) {
        //如果不是该默认模板且修改为默认，则取消原来默认
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        emrModle.setUpdater(userName);
        emrModle.setUpdateTime(fmt.format(new Date()));
        emrModleMapper.updateByPrimaryKeySelective(emrModle);
    }

    @Override
    public void deleteTemplateSelect(Integer id) {
        emrModleMapper.deleteByPrimaryKey(id);
        //连带选择归属也删除
        emrModleRelatedMapper.deleteByModleId(id);
    }

    @Override
    public void addModleRelated(Integer modleId, String checks,HttpServletRequest request) {
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        String date = fmt.format(new Date());
        //先删除后添加
        emrModleRelatedMapper.deleteByModleId(modleId);
        if(StringUtils.isNoneBlank(checks)){
            ///查询表列数
            int colCount = commomMapper.selectColByTableName("emr_modle_related");
            int simpleInsertCount = 2100/colCount;
            String[] checkList = checks.split(",");
            List<Emr_Modle_Related> list = new ArrayList<>();
            for (int i = 0; i < checkList.length; i++) {
                //处理批量添加sql太长问题，设定个数为180
                if(i > 0 && list.size()%simpleInsertCount == 0){
                    list.clear();
                }
                Emr_Modle_Related related = new Emr_Modle_Related();
                related.setModleId(modleId);
                related.setCustomizeId(Integer.valueOf(checkList[i]));
                related.setCreater(userName);
                related.setUpdater(userName);
                related.setCreateTime(date);
                related.setUpdateTime(date);
                list.add(related);
                //是180的倍数或最后一个
                if((list.size()%simpleInsertCount == 0 || i == checkList.length - 1)){
                    emrModleRelatedMapper.SimpleInsert(list);
                }
            }
        }
    }

    @Override
    public void movePdf(String oldFile, String newFile) throws IOException {
        //一遍读取一遍写入。
        //无论你是是使用的输出流还是输入流，操作的一定是文件。
        //1.读取数据    //输入字节流
        //1.找到需要复制的图片
        File file = new File(oldFile); // NotFoundException
        FileInputStream inputStream = new FileInputStream(file);
        File file1 = new File(newFile);
        FileOutputStream outputStream = new FileOutputStream(file1);
        byte[] b = new byte[1024];
        //int count = 0;
        while (inputStream.read(b) != -1) {
            //2.写入数据   //输出字节流
            outputStream.write(b);
        }

        //关闭流     关闭流的原则: 先开后关  后开的先关。
        outputStream.close();
        inputStream.close();
    }
}
