package com.fs.app.controller;


import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import com.fs.app.annotation.Login;
import com.fs.app.utils.CityTreeUtil;
import com.fs.app.utils.JwtUtils;
import com.fs.app.vo.CityVO;
import com.fs.common.config.FSConfig;
import com.fs.common.config.FSSysConfig;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.exception.file.OssException;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.file.FileUploadUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanySmsLogsService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.service.ICompanyVoiceLogsService;
import com.fs.core.config.ServerConfig;
import com.fs.crm.service.*;
import com.fs.jpush.service.JpushService;
import com.fs.store.domain.FsAppVersion;
import com.fs.store.domain.FsCity;
import com.fs.store.service.IFsAppVersionService;
import com.fs.store.service.IFsCityService;
import com.fs.store.service.IPrescribeService;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.system.service.ISysConfigService;
import com.fs.system.service.ISysDictDataService;
import com.fs.system.vo.DictVO;
import com.fs.voice.service.IVoiceService;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.Cacheable;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api("公共接口")
@RestController
@RequestMapping(value="/app/common")
public class CommonController extends AppBaseController {
	@Autowired
    JwtUtils jwtUtils;
	@Autowired
	private ServerConfig serverConfig;
	@Autowired
	private ISysDictDataService dictDataService;

	@Autowired
	ICrmCustomerUserService crmCustomerUserService;
	@Autowired
	ICrmCustomerService crmCustomerService;

	@Autowired
	private ICrmMsgService msgService;

	@Autowired
	private ISysConfigService configService;

	@Autowired
	private ICrmEventService eventService;

	@Autowired
	private IVoiceService voiceService;

	@Autowired
	ICompanyUserService userService;

	@Autowired
	IPrescribeService prescribeService;
	@Autowired
	FSSysConfig fsSysConfig;
	@Autowired
	private IFsAppVersionService fsAppVersionService;
	@Autowired
	private IFsCityService fsCityService;
	@Autowired
	private JpushService jpushService;

	@Autowired
	private ICrmCustomerHisOrderService crmCustomerHisOrderService;



	@Autowired
	private ICompanySmsLogsService smsLogsService;

	@Autowired
	private ICompanyVoiceLogsService voiceLogsService;

	@Autowired
	private ICompanyUserService companyUserService;

	@Autowired
	private ICrmCustomerContactsService crmCustomerContactsService;

	public static final Logger LOGGER = LoggerFactory.getLogger(CommonController.class);


	@ApiOperation("获取城市数据")
	@GetMapping("/getCitys")
	@Cacheable("citys")
	public R getCitys(HttpServletRequest request){
		List<FsCity> list=fsCityService.selectFsCitys();
		List<CityVO> cityVOS = Lists.newArrayList();
		for (FsCity city : list){
			CityVO cityVO = new CityVO();
			cityVO.setValue(Long.parseLong(city.getCityId()));
			cityVO.setLabel(city.getCityName());
			cityVO.setPid(Long.parseLong(city.getParentId()));
			cityVOS.add(cityVO);
		}
		return R.ok().put("data", CityTreeUtil.list2TreeConverter(cityVOS, 0));

	}

	@ApiOperation("获取最新版本")
	@GetMapping("/getAppVersion")
	public R getAppVersion(@ApiParam(required = false, name = "type", value = "APP类型 1android 2ios") @RequestParam(value = "type", required = false) String type)
	{
		FsAppVersion version=fsAppVersionService.getAppVersion(type);
		return R.ok().put("data",version);
	}
	/**
	 * 通用上传请求
	 */
	@ApiOperation("上传")
	@PostMapping("/upload")
	public R uploadFile(MultipartFile file) throws Exception
	{
		try
		{
			// 上传文件路径
			String filePath = FSConfig.getUploadPath();
			// 上传并返回新文件名称
			String fileName = FileUploadUtils.upload(filePath, file);
			String url = serverConfig.getUrl() + fileName;
			AjaxResult ajax = AjaxResult.success();
			ajax.put("fileName", fileName);
			ajax.put("url", url);
			return R.ok().put("fileName",fileName).put("url",url);
		}
		catch (Exception e)
		{
			return R.error(e.getMessage());
		}
	}


	@ApiOperation("获取数据字典")
	@GetMapping("/getDicts")
//	@Cacheable(value= "dicts")
	public R getDicts(
	){
		return R.ok();


	}
	@ApiOperation("获取数据字典")
	@GetMapping("/getDictByKey")
	public R getDictByKey(@ApiParam(required = false, name = "key", value = "key") @RequestParam(value = "key", required = false) String key){
		List<DictVO> dictVOS=dictDataService.selectDictDataListByType(key);
		return R.ok().put("data",dictVOS);
	}

	@Login
	@ApiOperation("推送测试")
	@GetMapping(value = "/pushText")
	public R pushText()
	{
		CompanyUser companyUser=userService.selectCompanyUserById(Long.parseLong(getUserId()));
		if(StringUtils.isEmpty(companyUser.getJpushId())){
			return R.error("推送ID不存在");
		}
		Map<String, String> extrasMap=new HashMap<>();
		extrasMap.put("customerId","1111");
		extrasMap.put("type","1");
		try {
			jpushService.sendRegisterIdPush("客户消息","您有一个客户消息",extrasMap,companyUser.getJpushId());
		} catch (APIConnectionException e) {
			e.printStackTrace();
			return R.error(e.getMessage());
		} catch (APIRequestException e) {
			e.printStackTrace();
			return R.error(e.getMessage());
		}
		return R.ok();
	}

	@ApiOperation("获取系统配置")
	@GetMapping(value = "/getConfig")
	public R getConfig()
	{
		String sysConfig=configService.selectConfigByKey("sys:config");
		return R.ok().put("sysConfig",sysConfig);
	}
	@ApiOperation("获取选择员工")
	@GetMapping("/getSelectUserList")
	public R getSelectUserList(HttpServletRequest request,
	@ApiParam(required = false, name = "nickName", value = "nickName") @RequestParam(value = "nickName", required = false) String nickName
	)
	{
		CompanyUser map=new CompanyUser();
		map.setNickName(nickName);
		map.setCompanyId(getCompanyId());
		map.setIsDel(0);
		map.setStatus("0");
		List<CompanyUser> list = userService.selectCompanyUserList(map);
		return R.ok().put("data",list);
	}

	@ApiOperation("上传")
	@PostMapping("uploadOSS")
	public R uploadOSS(@RequestParam("file") MultipartFile file) throws Exception
	{

		if (file.isEmpty())
		{
			throw new OssException("上传文件不能为空");
		}
		// 上传文件
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		CloudStorageService storage = OSSFactory.build();
		String url = storage.uploadSuffix(file.getBytes(), suffix);
		return R.ok().put("url",url);
	}



}
