package com.uas.platform.b2b.v2.controller;

import com.uas.platform.b2b.core.util.ThreadUtils;
import com.uas.platform.b2b.model.EnterpriseBaseInfo;
import com.uas.platform.b2b.support.CommBufferedLogger;
import com.uas.platform.b2b.temporary.model.UserSpaceDetail;
import com.uas.platform.b2b.publicapi.service.InviteRecordService;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.sso.entity.UserSpaceView;
import com.uas.sso.entity.UserView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.support.SysConf;
import com.uas.platform.b2b.v2.service.EnterpriseService;
import com.uas.sso.common.util.HttpUtil;
import com.uas.sso.common.util.HttpUtil.ResponseWrap;

@Controller("v2.EnterpriseController")
@RequestMapping(value = "/public/enterprise")
public class EnterpriseController {

	@Autowired
	private EnterpriseService enterpriseService;

	@Autowired
    private InviteRecordService inviteRecordService;

	@Autowired
	private SysConf conf;

	@SuppressWarnings("deprecation")
	@Autowired
	private com.uas.platform.b2b.service.EnterpriseService enterService;

	private final static CommBufferedLogger logger = BufferedLoggerManager.getLogger(CommBufferedLogger.class);

	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public UserSpaceView save(UserSpaceView userSpaceDetail, UserView admin) throws Exception {
		if (userSpaceDetail != null && admin != null) {
			userSpaceDetail.setAdmin(admin);
			Enterprise enterprise = enterpriseService.save(userSpaceDetail);
			userSpaceDetail.setSpaceUU(enterprise.getUu());
			// 为兼容以前模式，同时知会下管理系统。管理系统主要为了获取企业uu
		}
		return null;
	}

	private String syncToManager(UserSpaceView userSpaceDetail) throws Exception {
		JSONObject formData = JSON.parseObject(JSON.toJSONString(userSpaceDetail));
		ResponseWrap res = HttpUtil.doPost(conf.getManageInner() + "/public/enterprise", formData);
		Long enUU = userSpaceDetail.getSpaceUU();
		if (!res.isSuccess()) {
			logger.log("同步数据", "error", "同步企业数据到管理平台失败",enUU != null ? enUU : 0L);
			throw new Exception(res.getContent());
		} else {
			logger.log("同步数据", "success", "同步企业数据到管理平台成功", enUU != null ? Long.valueOf(enUU) : 0L);
			return JSON.parseObject(res.getContent()).getString("dialectUID");
		}
	}

	@RequestMapping(method = RequestMethod.DELETE)
	@ResponseBody
	public void remove(UserSpaceView userSpace) {
		if (userSpace != null) {
			enterpriseService.delete(userSpace);
		}
	}
	
	/**
	 * 账户中心传输更新企业信息
	 * 
	 * @param userSpaceDetail
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/renewUserSpace", method = RequestMethod.POST)
	@ResponseBody
	public String renewUserSpace(UserSpaceDetail userSpaceDetail) throws Exception {
		Enterprise enterprise = null;
		if(userSpaceDetail.getUu() != null) {
			enterprise = enterService.findByEnUU(userSpaceDetail.getUu());
		}
		if (enterprise != null) {
			enterprise.setEnName(userSpaceDetail.getName());
			enterprise.setEnShortname(userSpaceDetail.getShortName());
			enterprise.setEnAddress(userSpaceDetail.getAddress());
			enterprise.setEnBussinessCode(userSpaceDetail.getBusinessCode());
			try {
				final EnterpriseBaseInfo baseInfo = new EnterpriseBaseInfo(enterpriseService.save(enterprise));
                // 如果改了名字，需要去更新邀请记录里面的信息
                if (!enterprise.getEnName().equals(userSpaceDetail.getName())) {
                    ThreadUtils.task(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                inviteRecordService.updateVendName(baseInfo);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).run();
                }
				return "success";
			} catch (Exception e) {
				e.printStackTrace();
				return "error";
			}
		} else {
			return "未找到相关的企业信息";
		}
	}

}
