package com.ym.mec.web.controller;

import com.ym.mec.biz.dal.dto.PaymentParam;
import com.ym.mec.biz.dal.dto.StudentVipGroupShowListDto;
import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
import com.ym.mec.biz.dal.page.StudentVipGroupQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.entity.MallCreateOrderModel;
import com.ym.mec.common.entity.OrderCancelModel;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dao.SysUserCashAccountDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.SysUserCashAccount;
import com.ym.mec.biz.dal.entity.Teacher;
import com.ym.mec.common.controller.BaseController;

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

@RequestMapping("api")
@Api(tags = "对外接口")
@RestController
public class APIController extends BaseController {
	@Autowired
	private OrderPayOpsService orderPayOpsService;
	@Autowired
	private SysUserCashAccountDao sysUserCashAccountDao;
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private PracticeLessonApplyService practiceLessonApplyService;
	@Autowired
	private PracticeGroupService practiceGroupService;
	@Autowired
	private ImGroupService imGroupService;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private SysTenantConfigService sysTenantConfigService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private VipGroupService vipGroupService;

	@Autowired
	private StudentPaymentOrderService studentPaymentOrderService;

	@GetMapping("/createCashAccount")
	public Boolean createCashAccount(Integer userId,Integer tenantId) {
		// 添加用户现金账户
		sysUserCashAccountDao.insert(new SysUserCashAccount(userId,tenantId, "CNY"));

		return true;
	}

	@GetMapping("/queryTeacherOrganId")
	public Integer queryTeacherOrganId(Integer userId) {
		Teacher teacher = teacherDao.get(userId);
		if (teacher != null) {
			return teacher.getTeacherOrganId();
		}
		return null;
	}

	@GetMapping("/practiceSum")
	public Object practiceSum() {
		return succeed(practiceLessonApplyService.practiceSum());
	}

	@GetMapping("/isPurchasedPracticeCourse")
	public Boolean isPurchasedPracticeCourse(Integer userId) {
		return practiceGroupService.isPurchasedPracticeCourse(userId);
	}

	@GetMapping("/updateNickName")
	public int updateNickName(Integer userId,String nickName) {
		return imGroupService.updateNickName(userId,nickName);
	}

	@GetMapping("/getTenantConfigValue")
	public String getTenantConfigValue(Integer tenantId,String paramName) {
		return sysTenantConfigService.getTenantConfigValue(paramName,tenantId);
	}

	@GetMapping("/queryOrganIdByUserId")
	public String queryOrganIdByUserId(Integer userId, String clientId) {
		if (StringUtils.equalsIgnoreCase("system", clientId) || StringUtils.equalsIgnoreCase("education", clientId)) {
			Employee employee = employeeDao.get(userId);
			if (employee != null) {
				return employee.getOrganIdList();
			}

		} else if (StringUtils.equalsIgnoreCase("teacher", clientId)) {
			Teacher teacher = teacherDao.get(userId);
			if (teacher != null) {
				return teacher.getOrganId() + "";
			}
		} else {
			SysUser user = sysUserFeignService.queryUserInfo();
			if (user != null) {
				return user.getOrganId() + "";
			}
		}
		return null;
	}

	@ApiOperation(value = "获取可购买vip、网管课列表")
	@RequestMapping(value = "/queryVipPracticeGroups")
	public Boolean queryVipPracticeGroups(){
		SysUser sysUser = sysUserService.getUser();
		StudentVipGroupQueryInfo queryInfo = new StudentVipGroupQueryInfo();
		queryInfo.setOrganId(sysUser.getOrganId());
		queryInfo.setUserId(sysUser.getId());
		List<StudentVipGroupShowListDto> listDtos = vipGroupService.queryVipPracticeGroups(queryInfo);
		return CollectionUtils.isEmpty(listDtos)?false:true;
	}



	@PostMapping("/mallCreateOrder")
	public HttpResponseResult<Map> mallCreateOrder(@RequestBody MallCreateOrderModel model) {
		try {
			return succeed(studentPaymentOrderService.createOrder(model));
		} catch (Exception e) {
			e.printStackTrace();
			return failed();
		}
	}


	@PostMapping("/mallSaveOrderInfo")
	public HttpResponseResult<Map> mallSaveOrderInfo(@RequestBody MallCreateOrderModel model) {
		try {
			studentPaymentOrderService.mallSaveOrderInfo(model);
			return succeed();
		} catch (Exception e) {
			e.printStackTrace();
			return failed();
		}
	}

	@ApiOperation(value = "台牌支付")
	@PostMapping("/executePayment")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "amount", value = "支付金额", required = true, dataType = "BigDecimal"),
			@ApiImplicitParam(name = "orderNo", value = "订单号", required = true, dataType = "String"),
			@ApiImplicitParam(name = "payChannel", value = "支付方式（alipay-支付宝app支付）", required = true, dataType = "String"),
	})
	public Object executePayment(@RequestBody PaymentParam paymentParam) {
		try {
			Map<String, Object> payment = orderPayOpsService.executePayment(paymentParam);
			return succeed(payment);
		} catch (Exception e) {
			return failed(e.getMessage());
		}
	}


	@PostMapping("/updateOrder")
	public HttpResponseResult updateOrder(@RequestBody Map map) {

		try {
			studentPaymentOrderService.updateOrder(map);
		} catch (Exception e) {
			e.printStackTrace();
			return failed();
		}
		return succeed();
	}


	/**
	 * 取消订单接口
	 *
	 * @param orderNo
	 * @return
	 */
	@PostMapping("/cancelOrder")
	public HttpResponseResult<OrderCancelModel> cancelOrder(@RequestParam String orderNo) {

		try {
			OrderCancelModel cancelModel = new OrderCancelModel();
			StudentPaymentOrder orderByOrderNo = studentPaymentOrderService.findOrderByOrderNo(orderNo);
			if (orderByOrderNo == null) {
				cancelModel.setSuccess(true);
				cancelModel.setStatus(false);
				return succeed(cancelModel);
			}
			cancelModel = studentPaymentOrderService.cancelOrder(orderByOrderNo);
			return succeed(cancelModel);
		} catch (Exception e) {
			e.printStackTrace();
			return failed();
		}
	}

}
