package cn.superdesk.uniorder.dubbo.provider.marketing.department;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.dao.entity.marketing.department.UnifiedAreaCity;
import cn.superdesk.uniorder.dao.entity.marketing.department.UnifiedAreaCityTarget;
import cn.superdesk.uniorder.dao.entity.marketing.department.UnifiedAreaCityVirt;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganization;
import cn.superdesk.uniorder.dao.entity.unified.UnifiedCustomer;
import cn.superdesk.uniorder.dao.entity.unified.UnifiedProject;
import cn.superdesk.uniorder.dao.mapper.organisation.SysEnterpriseMapperEx;
import cn.superdesk.uniorder.dao.mapper.organisation.SysOrganizationMapperEx;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedProjectMapper;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dto.vo._function.select.SelectOptionAreaItem;
import cn.superdesk.uniorder.dto.vo._function.select.SelectOptionVirt;
import cn.superdesk.uniorder.dto.vo.marketing.department.*;
import cn.superdesk.uniorder.dubbo.facade.marketing.department.DubboUnifiedAreaService;
import cn.superdesk.uniorder.service.marketing.department.UnifiedAreaCityService;
import cn.superdesk.uniorder.service.marketing.department.UnifiedAreaCityTargetService;
import cn.superdesk.uniorder.service.marketing.department.UnifiedAreaCityVirtService;
import cn.superdesk.uniorder.service.unified.UnifiedCustomerService;
import cn.superdesk.uniorder.common.numerical.AnConvertBeanUtil;
import com.alibaba.dubbo.config.annotation.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service(version = "1.0.0", retries = -1, timeout = 10000)
public class DubboUnifiedAreaServiceImpl implements DubboUnifiedAreaService {

	//	@Autowired
//	UnifiedAreaService           areaService;
	@Autowired
	private UnifiedAreaCityService       areaCityService;
	@Autowired
	private UnifiedAreaCityTargetService areaCityTargetService;
	@Autowired
	private UnifiedAreaCityVirtService   areaCityVirtService;
	@Autowired
	private UnifiedCustomerService       customerService;

	@Autowired
	private UnifiedProjectMapper    unifiedProjectMapper;
	@Autowired
	private SysOrganizationMapperEx sysOrganizationMapperEx;
	@Autowired
	private SysEnterpriseMapperEx   sysEnterpriseMapperEx;


	@Override
	public List<UnifiedAreaWeb> getweb(Map<String, Object> params) {

		return areaCityService.getweb(params);
	}

	/**
	 * 添加区域
	 *
	 * @param param
	 * @param loginSysUser
	 * @return
	 */
	@Override
	public Map<String, Object> addNew(UnifiedAreaParam param, LoginSysUser loginSysUser) {

		Map<String, Object> resMap = new HashMap<>();

		//子区域添加
		UnifiedAreaCity item = AnConvertBeanUtil.copyBean(param, UnifiedAreaCity.class);

		item.setCreateTime(DateUtil.date());
		item.setCreateUserId(loginSysUser.getSysUserId());

		item.setUpdateTime(DateUtil.date());
		item.setUpdateUserId(loginSysUser.getSysUserId());

		areaCityService.addObjTran(item);

		if (param.getKpiTarget() != null) {

			UnifiedAreaCityTarget target = new UnifiedAreaCityTarget();

			target.setAreaCityId(item.getId());

			target.setCreateTime(DateUtil.date());
			target.setCreateUserId(loginSysUser.getSysUserId());

			// 1. 销售额KPI指标 原:月KPI指标
			target.setKpiTarget(param.getKpiTarget());
			target.setOkrTarget(param.getOkrTarget());
			target.setProfitKpiTarget(param.getProfitKpiTarget());
//			2. 销售总额 原:月成交额


			/****************************************** 只能是当前时间？修改 by linjinyu at 20201126 start ******************************************/

			// TODO 再添加两个
//			1. 毛利KPI指标 毛利也就是利润？ profit
//			2. 毛利金额 推出这个是计算出来的？

			Date             dtnow = DateUtil.date();
			SimpleDateFormat sdf   = new SimpleDateFormat("yyyy-MM");
			String           dtstr = sdf.format(dtnow);

			if (null != param.getYearly()) {
				target.setYearly(param.getYearly());
			} else {
				target.setYearly(Integer.parseInt(dtstr.substring(0, 4)));
			}

			if (null != param.getMonthly()) {
				target.setMonthly(param.getMonthly());
			} else {
				target.setMonthly(Integer.parseInt(dtstr.substring(5)));
			}

			/****************************************** 只能是当前时间？修改 by linjinyu at 20201126   end ******************************************/

			target.setUpdateTime(DateUtil.date());
			target.setUpdateUserId(loginSysUser.getSysUserId());

			areaCityTargetService.insertSelective(target);

		}

		resMap.put("code", "1");
		resMap.put("data", item);
		return resMap;
	}

	/**
	 * 编辑区域
	 *
	 * @param param
	 * @param loginSysUser
	 * @return
	 */
	@Override
	public Map<String, Object> updateNew(UnifiedAreaParam param, LoginSysUser loginSysUser) {

		Map<String, Object> resMap = new HashMap<>();

		// 区域添加
		UnifiedAreaCity item = AnConvertBeanUtil.copyBean(param, UnifiedAreaCity.class);

		item.setUpdateTime(DateUtil.date());
		item.setUpdateUserId(loginSysUser.getSysUserId());

		areaCityService.updateObjTran(item);

		if (param.getKpiTarget() != null) {

			UnifiedAreaCityTarget target = new UnifiedAreaCityTarget();

			target.setAreaCityId(item.getId());

			target.setCreateTime(DateUtil.date());
			target.setCreateUserId(loginSysUser.getSysUserId());

			// 1. 销售额KPI指标 原:月KPI指标
			target.setKpiTarget(param.getKpiTarget());
			target.setOkrTarget(param.getOkrTarget());
			target.setProfitKpiTarget(param.getProfitKpiTarget());
//			2. 销售总额 原:月成交额

			// TODO 再添加两个
//			1. 毛利KPI指标 毛利也就是利润？ profit
//			2. 毛利金额 推出这个是计算出来的？


			/****************************************** 只能是当前时间？修改 by linjinyu at 20201126 start ******************************************/
			Date             dtnow = DateUtil.date();
			SimpleDateFormat sdf   = new SimpleDateFormat("yyyy-MM");
			String           dtstr = sdf.format(dtnow);

			if (null != param.getYearly()) {
				target.setYearly(param.getYearly());
			} else {
				target.setYearly(Integer.parseInt(dtstr.substring(0, 4)));
			}

			if (null != param.getMonthly()) {
				target.setMonthly(param.getMonthly());
			} else {
				target.setMonthly(Integer.parseInt(dtstr.substring(5)));
			}
			/****************************************** 只能是当前时间？修改 by linjinyu at 20201126   end ******************************************/

			target.setUpdateTime(DateUtil.date());
			target.setUpdateUserId(loginSysUser.getSysUserId());


			Map<String, Object> query = new HashMap<>();
			query.put("areaItemId", target.getAreaCityId());
			query.put("yearly", target.getYearly());
			query.put("monthly", target.getMonthly());
			List<UnifiedAreaCityTarget> targets = areaCityTargetService.findAll(query);

			if (targets != null && targets.size() > 0) {

				UnifiedAreaCityTarget updateTarget = targets.get(0);


				updateTarget.setKpiTarget(target.getKpiTarget());
				updateTarget.setOkrTarget(target.getOkrTarget());
				updateTarget.setProfitKpiTarget(target.getProfitKpiTarget());

//				updateTarget.setYearly(target.getYearly());
//				updateTarget.setMonthly(target.getMonthly());

				updateTarget.setUpdateUserId(loginSysUser.getSysUserId());
				updateTarget.setUpdateTime(DateUtil.date());

				areaCityTargetService.updateByPrimaryKeySelective(updateTarget);
			} else {
				areaCityTargetService.insertSelective(target);
			}
		}

		resMap.put("code", "1");
		resMap.put("data", item);
		return resMap;
	}

	@Override
	public List<UnifiedAreaCityTargetVo> getAreaCityTargetAll(Map<String, Object> params) {

		log.info("getAreaCityTargetAll : {} ", AnJsonUtils.toJson(params));

		List<UnifiedAreaCityTarget> result = areaCityTargetService.findAll(params);

		log.info("getAreaCityTargetAll result : {} ", AnJsonUtils.toJson(result));

		List<UnifiedAreaCityTargetVo> resultVo = AnConvertBeanUtil.copyListBeanToList(result, UnifiedAreaCityTargetVo.class);

		return resultVo;
	}

	@Override
	public List<SelectOptionVirt> getVirtNotInArea(Map<String, Object> params) {

		return areaCityVirtService.getVirtAll(params);
	}

	@Override
	public void updateAreaVirt(Long areaItemId, Long virtId, String type) {

		if (type.equals("add")) {

			UnifiedAreaCityVirt virt = new UnifiedAreaCityVirt();
			virt.setAreaCityId(areaItemId);
			virt.setVirtId(virtId);
			areaCityVirtService.insertSelective(virt);

			UnifiedCustomer customer = customerService.findById(virtId);

			if (customer == null) {

				SysEnterprise enterprise = sysEnterpriseMapperEx.findByVirtId(virtId);

				UnifiedCustomer add = new UnifiedCustomer();

				add.setCreateTime(DateUtil.date());
				add.setCreateUserId(1L);
				add.setProjectId(enterprise.getOrganizationId());
				add.setVirtId(virtId);
				add.setVirtName(enterprise.getEnterpriseName());

				customerService.insertSelective(add);

				UnifiedProject unifiedProject = unifiedProjectMapper.selectByPrimaryKey(add.getProjectId());

				if (unifiedProject == null) {

					List<SysOrganization> orgs = sysOrganizationMapperEx.findByOutOrgId(add.getProjectId());

					SysOrganization org = orgs.get(0);

					unifiedProject = new UnifiedProject();

					unifiedProject.setCreateTime(DateUtil.date());
					unifiedProject.setCreateUserId(add.getCreateUserId());

					unifiedProject.setProjectId(add.getProjectId());
					unifiedProject.setProjectName(org.getOrganizationName());
					unifiedProject.setProjectNo(org.getOrganizationNo());

					unifiedProject.setUpdateTime(add.getUpdateTime());

					unifiedProjectMapper.insert(unifiedProject);
				}


			}

		} else {
			areaCityVirtService.deleteObj(virtId);
		}
	}

	@Override
	public void delItemTran(Long areaItemId) {

		areaCityService.delItemTran(areaItemId);
	}


	@Override
	public List<SelectOptionAreaItem> findAreaItemSelect(Map<String, Object> params) {

		return areaCityService.findAreaItemSelect(params);
	}

	@Override
	public List<UnifiedAreaTJ> getareatj(Map<String, Object> params) {

		return areaCityService.getareatj(params);
	}

	@Override
	public UnifiedAreaCityWithVirt getAreaDetailByVirtId(Long virtId) {
		return areaCityService.getAreaDetailByVirtId(virtId);
	}

	@Override
	public List<UnifiedAreaCity> findAll(Map<String, Object> queryMap) {
		return areaCityService.findAll(queryMap);
	}

	@Override
	public UnifiedAreaCity addObj(UnifiedAreaCity areaCityAdd) {

		areaCityService.insertSelective(areaCityAdd);
		return areaCityAdd;
	}

	@Override
	public void addAreaVirt(UnifiedAreaCityVirt addareaCityVirt) {

		areaCityVirtService.insertSelective(addareaCityVirt);
	}
}
