/*
 *    Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: hnqz
 */
package com.qunzhixinxi.hnqz.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.entity.WmDaPharmacy;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackage;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackageStatus;
import com.qunzhixinxi.hnqz.admin.entity.WmTask;
import com.qunzhixinxi.hnqz.admin.entity.WmTaskContent;
import com.qunzhixinxi.hnqz.admin.mapper.WmDaPharmacyMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskContentMapper;
import com.qunzhixinxi.hnqz.admin.service.WmDaPharmacyService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageStatusService;
import com.qunzhixinxi.hnqz.admin.service.WmTaskService;
import com.qunzhixinxi.hnqz.admin.util.MapUtil;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 档案-药店
 *
 * @author pigx code generator
 * @date 2020-09-23 21:17:34
 */
@Service
@AllArgsConstructor
public class WmDaPharmacyServiceImpl extends ServiceImpl<WmDaPharmacyMapper, WmDaPharmacy> implements WmDaPharmacyService {


	private final WmDaPharmacyMapper wmDaPharmacyMapper;
	private final WmTaskService wmTaskService;
	private final WmTaskContentMapper wmTaskContentMapper;
	private final WmScorePackageService wmScorePackageService;
	private final WmScorePackageStatusService packageStatusService;

	@Override
	public R approvalPharmacy(String taskId) {
		WmDaPharmacy wmDaPharmacy=new WmDaPharmacy();
		//获取任务信息
		WmTask wmTask=wmTaskService.getById(taskId);
		if(null==wmTask){
			return R.failed("未查询到调研信息");
		}
		if("1".equals(wmTask.getPlatAuditStatus())){
			return R.failed("信息已审核，请重新查询后操作");
		}
		WmTaskContent wmTaskContent = wmTaskContentMapper.selectById(wmTask.getTaskContentId());
		if(null==wmTaskContent){
			return R.failed("调研信息为空");
		}
		//Temp3对应药店名称
		//有药店名称,获取药店信息
//		List<WmDaPharmacy> wdplist=wmDaPharmacyMapper.slectByParam(wmTaskContent.getTemp3());
		WmDaPharmacy query = new WmDaPharmacy();
		query.setPharmacyName(wmTaskContent.getTemp3());
		query.setDelFlag("0");
		List<WmDaPharmacy> wdplist=wmDaPharmacyMapper.selectList(Wrappers.query(query));
		if(null!=wdplist&&wdplist.size()>0){
			wmDaPharmacy=wdplist.get(0);
			wmTask.setCompareResult("2");//信息不一致
		}else {
			wmTask.setCompareResult("1");//新增
		}
		Map<String,Object> result = new HashMap();
		result.put("info", wmDaPharmacy);//数据
		result.put("_wmTask", wmTask);
		result.put("wmTask", wmTaskContent);
		result.put("wmTaskContent", wmTaskContent);
		result.put("compareResult", wmTask.getCompareResult());//数据
		return R.ok(result);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateByapproval(Map<String, String> map) {
		String taskId=map.get("taskId");
		WmTask wmTask=wmTaskService.getById(taskId);
		if(wmTask==null){
			return R.failed("未查询到调查信息");
		}
		String approvalInfo=map.get("approvalInfo");
		String approvalOpinion=map.get("approvalOpinion");
		String compareResult=map.get("compareResult");
		//更新时，同一个task_content_id和createtime下的数据，都要更新状态为已审核
//		LambdaUpdateWrapper<WmTask> updateWrapper=new LambdaUpdateWrapper<WmTask>();
//		updateWrapper.set(WmTask::getPlatAuditStatus,"1");
//		updateWrapper.set(WmTask::getApprovalOpinion,approvalOpinion);
//		updateWrapper.set(WmTask::getCompareResult,compareResult);
//		updateWrapper.set(WmTask::getApprovalInfo,approvalInfo);
//		updateWrapper.eq(WmTask::getTaskContentId,wmTask.getTaskContentId());
//		updateWrapper.eq(WmTask::getCreateTime,wmTask.getCreateTime());

		WmTask updateTask = new WmTask();
		updateTask.setId(taskId);
		updateTask.setPlatAuditStatus("1");
		updateTask.setApprovalOpinion(approvalOpinion);
		updateTask.setCompareResult(compareResult);
		updateTask.setApprovalInfo(approvalInfo);

		if("1".equals(approvalOpinion)){//采纳
			//updateWrapper.set(WmTask::getTaskStatus,"3");//审核通过
			// TODO 根据任务积分修改积分包状态
//			updateWrapper.set(WmTask::getRealFlag,"0");//0审核通过
			updateTask.setRealFlag("0");

			WmDaPharmacy wmDaPharmacy = new WmDaPharmacy();
			WmTaskContent wmTaskContent = wmTaskContentMapper.selectById(wmTask.getTaskContentId());
			//更新审核信息
			LocalDateTime now = LocalDateTime.now();
			Integer userId = SecurityUtils.getUser().getId();
			if("1".equals(compareResult)){//新增
				//新增
				wmDaPharmacy.setPharmacyName(wmTaskContent.getTemp3());//名称
				wmDaPharmacy.setAddress(wmTaskContent.getTemp4());//名称
				if (!StringUtil.isEmpty(wmTaskContent.getTemp7())) {//省市区
					String[] citys = wmTaskContent.getTemp7().split("-");
					if(citys.length==3) {
						wmDaPharmacy.setProvince(citys[0]);
						wmDaPharmacy.setCity(citys[1]);
						wmDaPharmacy.setArea(citys[2]);
					}else {
						String[] citys1=wmTaskContent.getTemp7().split(",");
						if(citys1.length==3) {
							wmDaPharmacy.setProvince(citys1[0]);
							wmDaPharmacy.setCity(citys1[1]);
							wmDaPharmacy.setArea(citys1[2]);
						}
					}
				}
				wmDaPharmacy.setCreateTime(now);
				wmDaPharmacy.setCreateUser(userId);
				// 根据地址转换经纬度
				this.convertToLatAndLong(wmDaPharmacy);
				this.save(wmDaPharmacy);
			}else if("2".equals(compareResult)){//信息不一致
				//对比药店和调研信息,只有所属地区不一样
				List<WmDaPharmacy> wdplist=wmDaPharmacyMapper.slectByParam(wmTaskContent.getTemp3());
				if(null!=wdplist&&wdplist.size()>0){
					wmDaPharmacy=wdplist.get(0);
				}
				String address=wmDaPharmacy.getProvince()+"-"+wmDaPharmacy.getCity()+"-"+wmDaPharmacy.getArea();
				if(null!=wmTaskContent.getTemp7()&&!wmTaskContent.getTemp7().equals(address)){
					String[] citys=wmTaskContent.getTemp7().split("-");
					if(citys.length==3){
						wmDaPharmacy.setProvince(citys[0]);
						wmDaPharmacy.setCity(citys[1]);
						wmDaPharmacy.setArea(citys[2]);
					}else {
						String[] citys1=wmTaskContent.getTemp7().split(",");
						if(citys1.length==3) {
							wmDaPharmacy.setProvince(citys1[0]);
							wmDaPharmacy.setCity(citys1[1]);
							wmDaPharmacy.setArea(citys1[2]);
						}
					}
				}
				wmDaPharmacy.setId(map.get("infoId"));
				wmDaPharmacy.setPharmacyName(wmTaskContent.getTemp3());//名称
				wmDaPharmacy.setAddress(wmTaskContent.getTemp4());
				wmDaPharmacy.setUpdateTime(now);
				wmDaPharmacy.setUpdateUser(userId);
				// 根据地址转换经纬度
				this.convertToLatAndLong(wmDaPharmacy);
				//更新药店信息;
				this.updateById(wmDaPharmacy);
			}

		}else{
			//updateWrapper.set(WmTask::getTaskStatus,"2");//审核不通过
//			updateWrapper.set(WmTask::getRealFlag,"1");//1不通过

			updateTask.setRealFlag("1");
		}
		//提交
		updateTask.setTaskStatus("2");
		WmScorePackage wmScorePackage = wmScorePackageService.getById(wmTask.getScorePackageId());
// 		if("1".equals(approvalOpinion)){
// 			if("1".equals(wmScorePackage.getPackageType1())){
// 				Boolean fullFlag = wmTaskService.checkUserTaskSubScore(wmTask.getTaskUserId());
// 				if(fullFlag){
// //					return R.failed(1, "每日最多提交5万积分");
// 					updateTask.setScore(0);
// 				}
//
// 			}
// 		}
		wmTaskService.updateById(updateTask);
//		wmTaskService.update(updateWrapper);

//		if("1".equals(approvalOpinion)){
//
//		}else {

			/**
			 * 审核不通过可能需要释放积分
			 */
			//更新积分包状态
//			WmScorePackage wmScorePackage = wmScorePackageService.getById(wmTask.getScorePackageId());
			WmScorePackageStatus query = new WmScorePackageStatus();
			query.setUserId(wmTask.getTaskUserId());
			query.setPackageId(wmTask.getScorePackageId());
			query.setStatus("2");
			WmScorePackageStatus scorePackageStatus = packageStatusService.getOne(Wrappers.query(query));

			/**
			 * 不需要释放 直接返回
			 */
//			if("1".equals(wmScorePackage.getTaskAddFlag()) && "1".equals(scorePackageStatus.getTaskAddFlag())){
//				return R.ok();
//			}

			packageStatusService.updatePackageAndStatus(wmTask, wmScorePackage, scorePackageStatus);
//		}
		return R.ok();
	}

	/**
	 * 根据经纬度查询
	 *
	 * @param wmDaPharmacy
	 * @return
	 */
	@Override
	public List<WmDaPharmacy> listByPoint(WmDaPharmacy wmDaPharmacy) {
		return wmDaPharmacyMapper.listByPoint(wmDaPharmacy);
	}

	/**
	 * 批量转换经纬度
	 */
	@Override
	public void parseAddress() {
		List<WmDaPharmacy> list = this.list(Wrappers.<WmDaPharmacy>lambdaQuery().isNull(WmDaPharmacy::getLatitude));
		if (CollectionUtil.isNotEmpty(list)) {
			list.forEach(wmDaPharmacy -> {
				this.convertToLatAndLong(wmDaPharmacy);
				this.saveOrUpdate(wmDaPharmacy);
			});
		}
	}

	/**
	 * 根据地址转换经纬度
	 *
	 * @param wmDaPharmacy
	 */
	private void convertToLatAndLong(WmDaPharmacy wmDaPharmacy) {
		String fullAddress = wmDaPharmacy.getProvince() + wmDaPharmacy.getCity() + wmDaPharmacy.getArea()
				+ wmDaPharmacy.getAddress();
		JSONObject jsonObject = MapUtil.getLatAndLogByName(fullAddress);
		if (jsonObject != null) {
			wmDaPharmacy.setProvince(jsonObject.getString("province"));
			wmDaPharmacy.setCity(jsonObject.getString("city"));
			wmDaPharmacy.setArea(jsonObject.getString("district"));
			String location = jsonObject.getString("location");
			if (null != location && location.split(",").length > 0) {
				wmDaPharmacy.setLongitude(location.split(",")[0]);
				wmDaPharmacy.setLatitude(location.split(",")[1]);
			}
		}
	}


}
