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

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.google.common.collect.Lists;
import com.patzn.cloud.commons.api.RestAssert;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.core.oss.OssClient;
import com.patzn.lims.res.service.ILmsPropertyService;
import com.patzn.lims.frame.dto.LmsFrameCustomerInvestigateDTO;
import com.patzn.lims.frame.entity.*;
import com.patzn.lims.frame.enums.FrameFileTypeEnum;
import com.patzn.lims.frame.mapper.LmsFrameCustomerInvestigateMapper;
import com.patzn.lims.frame.service.*;
import com.patzn.lims.frame.vo.LmsFrameCustomerInvestigateVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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 javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 客户满意度管理 服务实现类
 * </p>
 *
 * @author patzn123
 * @since 2018-01-09
 */
@Service
public class LmsFrameCustomerInvestigateServiceImpl extends BaseServiceImpl<LmsFrameCustomerInvestigateMapper, LmsFrameCustomerInvestigate> implements ILmsFrameCustomerInvestigateService {

    @Autowired
    private ILmsFrameFileService lmsFrameFileService;
    @Autowired
    private ILmsFrameLogService lmsFrameLogService;
    @Autowired
    private ILmsFrameCustomerInvestigateDetailService lmsFrameCustomerInvestigateDetailService;
//    @Autowired
//    private ILmsExportService lmsExportService;
    @Autowired
    private ILmsPropertyService lmsPropertyService;
    @Autowired
    private ILmsFrameCustomerInvestigateRecordService lmsFrameCustomerInvestigateRecordService;
    @Autowired
    private OssClient ossClient;




    @Override
    public Page<LmsFrameCustomerInvestigate> page(Page<LmsFrameCustomerInvestigate> page, LmsFrameCustomerInvestigateDTO lmsFrameCustomerInvestigateDTO) {
        lmsFrameCustomerInvestigateDTO.setTempStatus(1);
         QueryWrapper wrapper = Wrappers.<LmsFrameCustomerInvestigate>query(lmsFrameCustomerInvestigateDTO);
        if (StringUtils.isNotBlank(lmsFrameCustomerInvestigateDTO.getCustomerName())){
            wrapper.like("customer_name", lmsFrameCustomerInvestigateDTO.getCustomerName());
            lmsFrameCustomerInvestigateDTO.setCustomerName(null);
        }
        if (StringUtils.isNotBlank(lmsFrameCustomerInvestigateDTO.getCustomerContact())){
            wrapper.like("customer_contact", lmsFrameCustomerInvestigateDTO.getCustomerContact());
            lmsFrameCustomerInvestigateDTO.setCustomerContact(null);
        }
        if (StringUtils.isNotBlank(lmsFrameCustomerInvestigateDTO.getServiceItems())){
            wrapper.like("service_items", lmsFrameCustomerInvestigateDTO.getServiceItems());
            lmsFrameCustomerInvestigateDTO.setServiceItems(null);
        }
        if (null != lmsFrameCustomerInvestigateDTO.getQueryStartTime()) {
            wrapper.ge("to_char(register_time, 'yyyy-MM-dd') ",lmsFrameCustomerInvestigateDTO.getQueryStartTime());
            lmsFrameCustomerInvestigateDTO.setQueryStartTime(null);
        }
        if (null != lmsFrameCustomerInvestigateDTO.getQueryEndTime()) {
            wrapper.le("to_char(register_time, 'yyyy-MM-dd') ", lmsFrameCustomerInvestigateDTO.getQueryEndTime());
            lmsFrameCustomerInvestigateDTO.setQueryEndTime(null);
        }
        wrapper.orderBy(true,true,"register_time");
        return page(page, wrapper);
    }


    @Override
    public List<LmsFrameCustomerInvestigate> list(LmsFrameCustomerInvestigate lmsFrameCustomerInvestigate) {
        lmsFrameCustomerInvestigate.setTempStatus(1);
        return list(Wrappers.<LmsFrameCustomerInvestigate>query(lmsFrameCustomerInvestigate));
    }

    @Override
    public LmsFrameCustomerInvestigateVO getVOById(Long id) {
        LmsFrameCustomerInvestigateVO vo = new LmsFrameCustomerInvestigateVO();
        LmsFrameCustomerInvestigate entity = getById(id);
        if (null != entity){
            BeanUtils.copyProperties(entity, vo);
            //获取附件
            LmsFrameFile lmsFrameFile = new LmsFrameFile();
            lmsFrameFile.setRelId(entity.getId());
            List<LmsFrameFile> list=lmsFrameFileService.list(lmsFrameFile);
            list.forEach(e->{
                e.setFilePath(ossClient.getUrl(e.getFilePath()).toString());
            });
            vo.setLmsFrameFileList(list);
        }
        return vo;
    }

    @Override
    public LmsFrameCustomerInvestigateVO getTempVO() {
        LmsFrameCustomerInvestigateVO lmsFrameCustomerInvestigateVO = new LmsFrameCustomerInvestigateVO();
        LmsFrameCustomerInvestigate entity = new LmsFrameCustomerInvestigate();
        entity.setUserId(LoginHelper.getAccount().getUserId());
        entity.setTempStatus(0);
        LmsFrameCustomerInvestigate lmsFrameCustomerInvestigate = baseMapper.selectOne(Wrappers.query(entity));
        if (null != lmsFrameCustomerInvestigate){
            BeanUtils.copyProperties(lmsFrameCustomerInvestigate, lmsFrameCustomerInvestigateVO);
            //获取附件
            LmsFrameFile lmsFrameFile = new LmsFrameFile();
            lmsFrameFile.setRelId(lmsFrameCustomerInvestigate.getId());
            List<LmsFrameFile> list = lmsFrameFileService.list(lmsFrameFile);
            list.forEach(e->{
                e.setFilePath(ossClient.getUrl(e.getFilePath()).toString());
            });
            lmsFrameCustomerInvestigateVO.setLmsFrameFileList(list);
        } else {
            LmsFrameCustomerInvestigate investigate = new LmsFrameCustomerInvestigate();
            investigate.setTempStatus(0);
            investigate.setUserId(LoginHelper.getAccount().getUserId());
            save(investigate);
            BeanUtils.copyProperties(investigate, lmsFrameCustomerInvestigateVO);
        }

        return lmsFrameCustomerInvestigateVO;
    }

    @Override
    @Transactional
    public Boolean edit(LmsFrameCustomerInvestigate lmsFrameCustomerInvestigate, Account account) {
        if (null != lmsFrameCustomerInvestigate.getId()){//提交数据操作日志保存
            LmsFrameCustomerInvestigate entity = getById(lmsFrameCustomerInvestigate.getId());
            String remark=  lmsPropertyService.getObjectCompareDifferent(lmsFrameCustomerInvestigate,entity,"客户满意度信息对比","信息修改：");
            if (StringUtils.isNotBlank(remark)){

                LmsFrameCustomerInvestigateRecord investigateRecord=new LmsFrameCustomerInvestigateRecord();
                investigateRecord.setType(2);
                investigateRecord.setCustomerInvestigateId(entity.getId());
                investigateRecord.setOrigin(account.getUserName());
                investigateRecord.setOperator(account.getUserName());
                investigateRecord.setRemark(remark);
                investigateRecord.setLiable(account.getUserName());
                investigateRecord.setOrigin(entity.getStatus().equals(0)?"草稿":"已提交");
                investigateRecord.setTarget(entity.getStatus().equals(0)?"草稿":"已提交");
                lmsFrameCustomerInvestigateRecordService.save(investigateRecord);
            }
            if (1 == entity.getStatus() ) {
                LmsFrameLog log = new LmsFrameLog();
                log.setUserId(LoginHelper.getAccount().getUserId());
                log.setUserName(LoginHelper.getAccount().getUserName());
                log.setTableName("lms_frame_customer_investigate");
                log.setOrginParams(entity.toString());
                log.setParams(lmsFrameCustomerInvestigate.toString());
                log.setCreateTime(new Date());
                lmsFrameLogService.save(log);
            }
        }
        return updateById(lmsFrameCustomerInvestigate);
    }

    @Override
    public Boolean add(LmsFrameCustomerInvestigate lmsFrameCustomerInvestigate) {
        LmsFrameCustomerInvestigate entity = new LmsFrameCustomerInvestigate();
        entity.setUserId(LoginHelper.getAccount().getUserId());
        entity.setTempStatus(0);
        LmsFrameCustomerInvestigate temp = baseMapper.selectOne(Wrappers.query(entity));
        if (null != temp){
            lmsFrameCustomerInvestigate.setId(temp.getId());
            lmsFrameCustomerInvestigate.setTempStatus(1);
            return updateById(lmsFrameCustomerInvestigate);
        }
         lmsFrameCustomerInvestigate.setUserId(LoginHelper.getAccount().getUserId());
         lmsFrameCustomerInvestigate.setTempStatus(1);
        lmsFrameCustomerInvestigate.setUname(LoginHelper.getAccount().getUserName());
         return  save(lmsFrameCustomerInvestigate);
    }

    @Override
    public Boolean delete(Long[] ids) {
        if (lmsFrameCustomerInvestigateDetailService.existByIds(ids)) {
            RestAssert.fail("请先删除该条数据下所有的实施数据！");
        }

        lmsFrameFileService.deleteBatch(ids);
        return super.remove(Wrappers.<LmsFrameCustomerInvestigate>query().in("id", ids));
    }

    @Override
    public LmsFrameFile uploadFile(MultipartFile file, LmsFrameCustomerInvestigate lmsFrameCustomerInvestigate) {
        Long companyId = LoginHelper.getAccount().getCompanyId();
        String folderPath = "frame/CustomerInvestigate/" + companyId + "/";
        return lmsFrameFileService.saveAndUpload(file, "lims", folderPath, lmsFrameCustomerInvestigate.getId(), FrameFileTypeEnum.CUSTOMER_INVEST.getValue());
    }

    @Override
    public void downloadFile(Long id, HttpServletResponse response) {
        LmsFrameFile lmsFrameFile = lmsFrameFileService.getById(id);
        String fileUrl = lmsFrameFile.getFilePath();
        String orgFileName = lmsFrameFile.getOrginName().replaceAll("\\s*", "");
        lmsFrameFileService.downloadFile(response, "lims", fileUrl, orgFileName);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteFile(Long id) {
        Long[] ids = new Long[]{id};
        return lmsFrameFileService.deleteBatch(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean submit(List<Long> ids) {
        List<LmsFrameCustomerInvestigate> entityList = Lists.newArrayList();
        for (Long id: ids) {
            LmsFrameCustomerInvestigate entity = new LmsFrameCustomerInvestigate();
            entity.setId(id);
            entity.setStatus(1);
            entityList.add(entity);
        }

        return updateBatchById(entityList);
    }


    @Override
    public void exportCustomerSatisfaction(HttpServletResponse response, Long id) {
//        RestAssert.fail(null==id,"id不能为空");
//        LmsFrameCustomerInvestigate investigate=getById(id);
//        List<LmsFrameCustomerInvestigateDetail> detailList=lmsFrameCustomerInvestigateDetailService.listByInvestigateId(id);
//        RestAssert.fail(CollectionUtils.isEmpty(detailList),"没有调查项目暂不能导出");
//        XWPFDocument doc  = null;
//        try {
//            doc=lmsExportService.getXWPFDoc("model","customer_satisfaction_form.docx");
//        } catch (Exception e1) {
//            e1.printStackTrace();
//        }
//
//        Map<String,String> replaceMap=new HashMap<>();
//        List<String> replaceList= WordReplaceUtil.getToReplaceList(doc);
//        for (String s:replaceList) {
//            replaceMap.put(s,StringHandleUtils.getFieldValueByFieldName(StringHandleUtils.getReplacePreporty(s),investigate));
//        }
//        WordReplaceUtil.replaceWord(replaceMap,doc);
//        List<XWPFTable> tableList=doc.getTables();
//        for (XWPFTable xwpfTable:tableList){
//            String text=xwpfTable.getText();
//            if (StringHandleUtils.containsString(text,"#{itemType}","#{investigateItem}","#{1}","#{2}","#{3}","#{4}","#{5}","#{remark}")){
//                //调查内容
//                Map<Integer,String> map= PoiUtil2007.getCellsContent(xwpfTable,5);
//                PoiUtil2007.insertTableRowAtIndex(xwpfTable,5,detailList.size());
//                int rowLength=detailList.size();
//
//                int mergerStart=5;
//                int mergerRow=0;
//                for (int i=0;i<rowLength;i++){
//                    List<XWPFTableCell> cellList=PoiUtil2007.getRowCells(xwpfTable,5+i);
//                    int cellLength= 0;
//                    if (CollectionUtils.isNotEmpty(cellList)){
//                        cellLength=cellList.size();
//                    }
//                    LmsFrameCustomerInvestigateDetail detail=detailList.get(i);
//                    for(int k=0;k<cellLength;k++){
//                        XWPFTableCell cell= cellList.get(k);
//                        if (cell.getParagraphs().size()>0){
//                            cell.removeParagraph(0);
//                        }
//                        String content="";
//                        String property=  StringHandleUtils.getObjectFromMap(map,k);
//                        if (property.equals("很满意")&&property.equals(detail.getCustomerStandard())){
//                            content="√";
//                        }else if("满意".equals(property)&&property.equals(detail.getCustomerStandard())){
//                            content="√";
//                        }else if("较满意".equals(property)&&detail.getCustomerStandard().equals("较满意")){
//                            content="√";
//                        }else if("不满意".equals(property)&&detail.getCustomerStandard().equals("不满意")){
//                            content="√";
//                        }else{
//                            content=StringHandleUtils.getFieldValueByFieldName(StringHandleUtils.getObjectFromMap(map,k),detail);
//                        }
//                        cell.setText(content);
//                    }
//
//
//                   if (i>0){
//                       LmsFrameCustomerInvestigateDetail detailPre=detailList.get(i-1);
//                       if (detail.getItemType().equals(detailPre.getItemType())){
//                           mergerRow++;
//                       }else{
//                           PoiUtil2007.mergeCellsVertically(xwpfTable,0,mergerStart,mergerStart+mergerRow);
//                           mergerStart=mergerStart+mergerRow+1;
//                           mergerRow=0;
//                       }
//                       if (i==(rowLength-1)){
//                           PoiUtil2007.mergeCellsVertically(xwpfTable,0,mergerStart,mergerStart+mergerRow);
//                       }
//                   }
//                }
//            }
//        }
//        PoiUtil2007ForReplace.replaceText(doc, replaceMap);
//        SimpleDateFormat sdf=new SimpleDateFormat("YYYY-MM-dd");
//        lmsExportService.downloadDoc(response,investigate.getCustomerName()+sdf.format(new Date())+"满意度.docx",doc);
    }
}
