package com.palmnest.service.estateserve.release.impl;

import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.input.RenovationManageAuditParam;
import com.palmnest.application.dto.input.RenovationManageInputDto;
import com.palmnest.application.dto.output.RenovationManageOutDto;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.model.release.RenovationManage;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.VirtualArchManager;
import com.palmnest.service.estateserve.release.RenovationManageManager;
import com.palmnest.service.estateserve.release.RenovationManageService;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.wechat.WeChatApiManager;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("renovationManageService")
public class RenovationManageServiceImpl implements RenovationManageService {

	private static final String ZXGM = "zxgm";

	public static String host                  = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	public static String wxRenovationDetailUrl = PropertiesKit.readPropertiesValue("wxRenovationDetailUrl", "wechat.properties");


	@Autowired
	private RenovationManageManager renovationManageManager;
	@Autowired
	private ScWxuserManager         scWxuserManager;
	@Autowired
	private VirtualArchManager      virtualArchManager;
	@Autowired
	private OrganizationManager     organizationManager;
	@Autowired
	private UserManager             userManager;
	@Autowired
	private BaseRedisService        baseRedisService;
	@Autowired
	private WeChatApiManager        weChatApiManager;


	@Override
	public Page findPageBy(Map<String, Object> params, int pageSize, int pageNo) {

		return renovationManageManager.findPageBy(params, pageSize, pageNo);
	}


	@Override
	public AppResultDto audit(RenovationManageAuditParam dto,
							  HttpServletRequest request) {

		RenovationManage bill = renovationManageManager.get(Long.decode(dto.getId().toString()));
		if (bill.getStatus() != 1) {
			return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "该单据非审核状态不能审核");
		}
		if (dto.getAuditResult() == 1) {//状态 审核结果 1通过2不通过
			bill.setStatus(2);
			bill.setAuditResult(1);
		} else if (dto.getAuditResult() == 2) {
			bill.setStatus(3);
			bill.setAuditResult(2);
		} else {
			return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "提交状态值不对");
		}
		bill.setAuditOpinion(dto.getAuditOpinion());
		bill.setAuditTime(new Date());


		if (dto.getBillFrom().equals(CodeConstants.PC)) {

			User user = (User) request.getSession().getAttribute("UserCache");
			bill.setAuditUserId(user.getId().intValue());

		} else if (dto.getBillFrom().equals(CodeConstants.ANDROID) || dto.getBillFrom().equals(CodeConstants.iOS)) {

			String userName = baseRedisService.get(request.getHeader("token"));
			if (userName == null) {
				return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
			}
			User user = userManager.getUserByUsername2(userName);
			bill.setAuditUserId(user.getId().intValue());
		}


		renovationManageManager.save(bill);

		if (bill.getStatus() == 2) {
			sendAgreeWechat(bill);
		} else if (bill.getStatus() == 3) {
			sendRefuseWechat(bill);
		}


		return AppResultUtil.createSuccesDto(convert(bill));
	}


	@Override
	public AppResultDto apply(RenovationManageInputDto dto,
							  HttpServletRequest request) {


		RenovationManage bill = new RenovationManage();
		try {
			BeanUtils.copyProperties(bill, dto);


			if (StringUtils.isNotEmpty(dto.getStartTimeStr())) {
				bill.setStartTime(DateUtils.getDateByString(dto.getStartTimeStr(), DateUtils.YYYY_MM_DD));
			}
			if (StringUtils.isNotEmpty(dto.getEndTimeStr())) {
				bill.setEndTime(DateUtils.getDateByString(dto.getEndTimeStr(), DateUtils.YYYY_MM_DD));
			}

			bill.setCreatedAt(new Date());
			bill.setUpdatedAt(new Date());
			bill.setStatus(1);//状态 1待审核2已通过3未通过		


			bill.setApplyTime(new Date());
			String code = CodeGenerateUtils.generate(ZXGM);
			bill.setCode(code);


			String openId = request.getParameter("openId");
			if (StringUtils.isEmpty(openId)) {
				return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "openId不能为空");
			}

			if (null == bill.getOrgId()) {
				return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "项目不能为空");
			}
			if (null == bill.getVirtId()) {
				return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "企业不能为空");
			}

			WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			if (wxUser != null) {
				bill.setCreatorBillId(wxUser.getId());
				bill.setCreatedBy(wxUser.getId());
				bill.setUpdatedBy(wxUser.getId());
			}


			RenovationManage reBill = renovationManageManager.save(bill);
			push(reBill);//app推送

			return AppResultUtil.createSuccesDto(convert(bill));

		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "装修申请失败");
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "装修申请失败");
		} catch (Exception e) {
			return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "装修申请失败");
		}

	}


	@Override
	public RenovationManageOutDto findById(Long id) {

		return this.convert(renovationManageManager.get(id));
	}

	@Override
	public RenovationManageOutDto convert(RenovationManage bill) {

		RenovationManageOutDto dto = new RenovationManageOutDto();

		try {


			BeanUtils.copyProperties(dto, bill);

			if (null != bill.getStartTime()) {
				dto.setStartTime(DateHelper.formatDate(bill.getStartTime(), DateHelper.CURRENT_DATE));
			} else {
				dto.setStartTime("");
			}

			if (null != bill.getEndTime()) {
				dto.setEndTime(DateHelper.formatDate(bill.getEndTime(), DateHelper.CURRENT_DATE));
			} else {
				dto.setEndTime("");
			}

			if (null != bill.getApplyTime()) {
				dto.setApplyTime(DateHelper.formatDate(bill.getApplyTime(), DateHelper.DATE_STRING));
			} else {
				dto.setApplyTime("");
			}

			if (null != bill.getAuditTime()) {
				dto.setAuditTime(DateHelper.formatDate(bill.getAuditTime(), DateHelper.DATE_STRING));
			} else {
				dto.setAuditTime("");
			}
			if (null != bill.getAuditUserId()) {//审批人
				User user = userManager.getUser(bill.getAuditUserId().toString());
				if (null != user) {
					dto.setAuditUser(user.getFullName());
				} else {
					dto.setAuditUser("");
				}
			} else {
				dto.setAuditUser("");
			}


			if (StringUtils.isEmpty(dto.getAuditOpinion())) {
				dto.setAuditOpinion("");
			}

			TbOrganization org = organizationManager.getOrganizationById(bill.getOrgId());
			if (null != org && StringUtils.isNotEmpty(org.getName())) {
				dto.setOrgName(org.getName());
			} else {
				dto.setOrgName("");
			}

			VirtualArchitecture vir = virtualArchManager.get(Integer.parseInt(String.valueOf(bill.getVirtId())));
			if (null != vir && StringUtils.isNotEmpty(vir.getName())) {
				dto.setVirtName(vir.getName());
			} else {
				dto.setVirtName("");
			}

			return dto;

		} catch (Exception e) {

		}
		return dto;

	}


	@Override
	public void push(RenovationManage bill) throws Exception {

		try {
			List<User> users = userManager.findByFunction(bill.getOrgId(), CodeConstants.RENOVATION_PERMISSION);
			String     title = "你好,你有新的待审核装修申请单,请及时处理！";

			VirtualArchitecture virt    = virtualArchManager.get(bill.getVirtId());
			String              content = "申请人：" + bill.getApplyUser() + "," + "申请企业:" + virt.getName();
			PushMessageHelper helper=new PushMessageHelper();
			helper.pushMessage(bill.getId(), CodeConstants.RENOVATION_PUSH_CODE, users, title, content);
		} catch (Exception e) {
			e.printStackTrace();
		}


	}


	@Override
	public void sendAgreeWechat(RenovationManage bill) {

		try {
			WxUser wxUser = scWxuserManager.get(Integer.valueOf(String.valueOf(bill.getCreatorBillId())));
			if (wxUser != null) {
				String              detailUrl    = host + wxRenovationDetailUrl.replaceAll("@id", bill.getId().toString());
				String              applyTimeStr = DateUtils.formatDate(bill.getApplyTime(), DateUtils.YYYY_MM_DD);
				VirtualArchitecture virt         = virtualArchManager.get(bill.getVirtId());
				String              content      = "恭喜，你于" + applyTimeStr + "申请" + virt.getName() + "的装修申请已审核通过!";
				content += " <a href=\"" + detailUrl + "\">查看详情>></a>";
				weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), content);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}


	}


	@Override
	public void sendRefuseWechat(RenovationManage bill) {

		try {
			WxUser wxUser = scWxuserManager.get(Integer.valueOf(String.valueOf(bill.getCreatorBillId())));
			if (wxUser != null) {
				String              detailUrl    = host + wxRenovationDetailUrl.replaceAll("@id", bill.getId().toString());
				String              applyTimeStr = DateUtils.formatDate(bill.getApplyTime(), DateUtils.YYYY_MM_DD);
				VirtualArchitecture virt         = virtualArchManager.get(bill.getVirtId());
				String              content      = "抱歉，你于" + applyTimeStr + "申请" + virt.getName() + "的装修申请审核未通过,审核意见为:" + bill.getAuditOpinion();
				content += " <a href=\"" + detailUrl + "\">查看详情>></a>";
				weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), content);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}


	}


}
