package com.qunzhixinxi.hnqz.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.entity.Contract;
import com.qunzhixinxi.hnqz.admin.entity.WmDaCustomer;
import com.qunzhixinxi.hnqz.admin.entity.WmDaCustomerProgessExport;
import com.qunzhixinxi.hnqz.admin.entity.WmDaTrack;
import com.qunzhixinxi.hnqz.admin.mapper.ContractMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmDaCustomerMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmDaTrackMapper;
import com.qunzhixinxi.hnqz.admin.service.SysFileService;
import com.qunzhixinxi.hnqz.admin.service.WmDaCustomerService;
import com.qunzhixinxi.hnqz.admin.util.OsEnvUtils;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import net.fenghaitao.AutoExcel;
import net.fenghaitao.parameters.TemplateExportPara;
import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 档案-客户管理
 *
 * @author lixuesong
 * @date 2021年06月04日 15:46
 */
@Service
@AllArgsConstructor
public class WmDaCustomerServiceImpl extends ServiceImpl<WmDaCustomerMapper, WmDaCustomer> implements WmDaCustomerService {

	private final WmDaCustomerMapper wmDaCustomerMapper;

	private final WmDaTrackMapper wmDaTrackMapper;

	private final ContractMapper contractMapper;

	private final SysFileService sysFileService;

	/**
	 * 根据id查询
	 *
	 * @param id
	 * @return
	 */
	@Override
	public WmDaCustomer getCustomerById(Integer id) {
		WmDaCustomer customer = this.getById(id);
		List<WmDaTrack> trackList = wmDaTrackMapper.selectList(Wrappers.<WmDaTrack>lambdaQuery()
				.eq(WmDaTrack::getProjectId, Long.valueOf(id)));
		List<Contract> contractList = contractMapper.selectList(Wrappers.<Contract>lambdaQuery()
				.eq(Contract::getCustomerId, id));
		customer.setContractList(contractList);
		customer.setWmDaTrackList(trackList);
		return customer;
	}

	/**
	 * 分页查询
	 *
	 * @param page
	 * @param wmDaCustomer
	 * @return
	 */
	@Override
	public IPage<WmDaCustomer> listCustomerPage(Page page, WmDaCustomer wmDaCustomer) {
		return wmDaCustomerMapper.listCustomerPage(page, wmDaCustomer);
	}

	/**
	 * 查询销售报表展示的客户
	 *
	 * @param page 分页对象
	 * @param wmDaCustomer 客户对象
	 * @param year 年份
	 * @param startMonth 开始月份
	 * @param endMonth 结束月份
	 * @return
	 */
	@Override
	public IPage<WmDaCustomer> listCustomerWithGmvPage(Page page, WmDaCustomer wmDaCustomer, String year, Integer startMonth, Integer endMonth) {
		return wmDaCustomerMapper.listCustomerWithGmvPage(page, wmDaCustomer, year, startMonth, endMonth);
	}

	/**
	 * 查询销售报表展示的客户
	 *
	 * @param wmDaCustomer 客户对象
	 * @param year 年份
	 * @param startMonth 开始月份
	 * @param endMonth 结束月份
	 * @return
	 */
	@Override
	public List<WmDaCustomer> listCustomerWithGmv(WmDaCustomer wmDaCustomer, String year, Integer startMonth, Integer endMonth) {
		return wmDaCustomerMapper.listCustomerWithGmv(wmDaCustomer, year, startMonth, endMonth);
	}

	/**
	 * 新增客户
	 *
	 * @param wmDaCustomer
	 */
	@Override
	public void saveCustomer(WmDaCustomer wmDaCustomer) {
		// 客户ID生成规则：客户类别id+创建人id+时间戳
		Integer currentUserId = SecurityUtils.getUser().getId();
		String customerNumber = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) + wmDaCustomer.getCustomerType().getVal() + currentUserId;
		wmDaCustomer.setCustomerNumber(customerNumber);
		wmDaCustomer.setCreateTime(LocalDateTime.now());
		wmDaCustomer.setCreateUser(currentUserId);
		// 保存主表
		this.save(wmDaCustomer);
		// 保存合同
		if (CollectionUtil.isNotEmpty(wmDaCustomer.getContractList())) {
			wmDaCustomer.getContractList().stream().forEach(contract -> {
				contract.setCustomerId(wmDaCustomer.getId());
				contractMapper.insert(contract);
			});
		}
		// 保存子列表
		List<WmDaTrack> wmDaTrackList = wmDaCustomer.getWmDaTrackList();
		if (CollectionUtil.isNotEmpty(wmDaTrackList)) {
			wmDaCustomer.getWmDaTrackList().stream().forEach(wmDaTrack -> {
				wmDaTrack.setCreateTime(new Date());
				wmDaTrack.setCreateUser(currentUserId);
				wmDaTrack.setProjectId(Long.valueOf(wmDaCustomer.getId()));
				wmDaTrackMapper.insertSelective(wmDaTrack);
			});
		}
	}

	/**
	 * 更新客户
	 *
	 * @param wmDaCustomer
	 */
	@Override
	public void updateCustomerById(WmDaCustomer wmDaCustomer) {
		LocalDateTime now = LocalDateTime.now();
		Integer currentUserId = SecurityUtils.getUser().getId();
		wmDaCustomer.setUpdateTime(now);
		wmDaCustomer.setUpdateUser(currentUserId);
		this.updateById(wmDaCustomer);
		// 删除关联的合同
		contractMapper.delete(Wrappers.<Contract>lambdaQuery().eq(Contract::getCustomerId, wmDaCustomer.getId()));
		// 保存合同
		if (CollectionUtil.isNotEmpty(wmDaCustomer.getContractList())) {
			wmDaCustomer.getContractList().stream().forEach(contract -> {
				contract.setCustomerId(wmDaCustomer.getId());
				contractMapper.insert(contract);
			});
		}
		// 删除关联的跟踪信息
		wmDaTrackMapper.deleteByProjectId(Long.valueOf(wmDaCustomer.getId()));
		// 保存跟踪信息
		List<WmDaTrack> wmDaTrackList = wmDaCustomer.getWmDaTrackList();
		if (null != wmDaTrackList && wmDaTrackList.size() > 0) {
			wmDaCustomer.getWmDaTrackList().stream().forEach(wmDaTrack -> {
				wmDaTrack.setProjectId(Long.valueOf(wmDaCustomer.getId()));
				wmDaTrack.setUpdateTime(new Date());
				wmDaTrack.setUpdateUser(currentUserId);
				wmDaTrackMapper.insertSelective(wmDaTrack);
			});
		}
	}

	/**
	 * 导出数据
	 *
	 * @param customerList
	 * @return
	 */
	@Override
	public R exportCustomer(List<WmDaCustomer> customerList) throws IOException {
		// 列表实体对象转换
		List<WmDaCustomerProgessExport> exportList = new ArrayList<>();
		this.convertCustomerToExportList(customerList, exportList);

		// 服务器excel文件路径
		String resourcePath = (String) OsEnvUtils.getEachEnvPaths().get("EXCEL_FILE_PATH");
		// 模板路径
		String templatePath = resourcePath  + "customer_develop_progress.xlsx";
		// 导出的文件名
		String fileName = "客户开发进度报告_" + System.currentTimeMillis();
		// 导出文件缓存路径
		String outputPath = resourcePath + "out/" + fileName + ".xlsx";
		// 配置对应excel名称管理器的数据源
		TemplateExportPara para = new TemplateExportPara("WmDaCustomerProgessExport", exportList);
		File templateFile = new File(templatePath);
		File tempFile = new File(outputPath);
		File parentFile = tempFile.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		tempFile.createNewFile();
//		String temp1 = "C:\\Users\\lixuesong\\Desktop\\customer_develop_progress.xlsx";
//		String temp2 = "C:\\Users\\lixuesong\\Desktop\\test\\AutoExcel2.xlsx";
//		AutoExcel.save(temp1, temp2, para);
		AutoExcel.save(templateFile.getAbsolutePath(), tempFile.getAbsolutePath(), para);
		FileInputStream tempStream = new FileInputStream(tempFile);
		MultipartFile multipartFile = new MockMultipartFile(fileName, fileName + ".xlsx",
				"text/plain", IOUtils.toByteArray(tempStream));
		// 上传到文件服务
		R result = sysFileService.uploadFileAllUrlRealName(multipartFile);
		// 删除temp文件
		tempFile.delete();
		return result;
	}

	/**
	 * 列表实体对象转换
	 *
	 * @param customerList
	 * @param exportList
	 */
	private void convertCustomerToExportList(List<WmDaCustomer> customerList, List<WmDaCustomerProgessExport> exportList) {
		customerList.forEach(wmDaCustomer -> {
			WmDaCustomerProgessExport export = new WmDaCustomerProgessExport();
			export.setCustomerName(wmDaCustomer.getCustomerName());
			export.setCustomerType(wmDaCustomer.getCustomerType() == null ? "" : wmDaCustomer.getCustomerType().getName());
			export.setCustomerManager(wmDaCustomer.getCustomerManager());
			export.setChannelName(wmDaCustomer.getChannelName());
			// 开发进度
			if (wmDaCustomer.getCustomerStatus() != null) {
				switch (wmDaCustomer.getCustomerStatus()) {
					case PUT_ON_RECORD:
						export.setPutOnRecord("❣");
						break;
					case PROJECT_APPROVAL:
						export.setPutOnRecord("✔");
						export.setProjectApproval("❣");
						break;
					case SIGN_A_CONTRACT:
						export.setPutOnRecord("✔");
						export.setProjectApproval("✔");
						export.setSignAContract("❣");
						break;
					case GOING_ONLINE:
						export.setPutOnRecord("✔");
						export.setProjectApproval("✔");
						export.setSignAContract("✔");
						export.setGoingOnline("❣");
						break;
					default:
				}
			}
			exportList.add(export);
		});
	}
}
