package com.cyksj.web.controller.manage.form;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.manage.form.FormFieldsDataMapper;
import com.cyksj.mapper.manage.form.FormFieldsMapper;
import com.cyksj.mapper.manage.form.FormTemplateMapper;
import com.cyksj.model.dto.FormTemplateDataDto;
import com.cyksj.model.entity.FormFields;
import com.cyksj.model.entity.FormFieldsDefault;
import com.cyksj.model.entity.FormTemplate;
import com.cyksj.model.entity.QuestionnairePromotion;
import com.cyksj.model.views.FormFieldsDataView;
import com.cyksj.service.mange.form.FormService;
import com.cyksj.service.mange.form.QuestionnairePromotionService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/*
 *项目名: netflix
 *文件名: FormController
 *创建者: JavaZou
 *创建时间:2023/6/12 9:58
 */
@RestController
@RequestMapping("/manage/form")
@RequiredArgsConstructor
public class FormController {

	private final FormFieldsMapper formFieldsMapper;

	private final FormFieldsDataMapper formFieldsDataMapper;

	private final FormTemplateMapper formTemplateMapper;

	private final FormService formService;

	private final BeanSearcher beanSearcher;

	private final QuestionnairePromotionService promotionService;

	private final HttpServletRequest request;

	/**
	 * 新增模板 以及对应模板字段
	 */
	@PostMapping("/template/post")
	public Result<String> insertTemplateAndRelationFields(@RequestBody FormTemplateDataDto dataDto) {
		formService.saveOrUpdateTemplateAndRelationFields(dataDto);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 编辑模板以及对应模板字段
	 */
	@PutMapping("/template/put")
	public Result<String> updateTemplateAndRelationFields(@RequestBody FormTemplateDataDto dataDto) {
		formService.saveOrUpdateTemplateAndRelationFields(dataDto);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 选择模板 生成对应问题
	 */
	@PostMapping("/template/fields/value")
	public Result<String> postTemplateFieldsValue(@RequestBody List<FormFieldsDefault> values) {
		formService.saveOrUpdateTemplateFieldsValue(values);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 选择模板 修改对应问题
	 */
	@PutMapping("/template/fields/value")
	public Result<String> updateTemplateFieldsValue(@RequestBody List<FormFieldsDefault> values) {
		formService.saveOrUpdateTemplateFieldsValue(values);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除模板
	 */
	@PutMapping("/template/del/{id}")
	public Result<String> delTid(@PathVariable Long id) {
		formTemplateMapper.update(null, Wrappers.lambdaUpdate(FormTemplate.class)
				.set(FormTemplate::getDeleted, false)
				.eq(FormTemplate::getId, id));

		formFieldsMapper.update(null, Wrappers.lambdaUpdate(FormFields.class)
				.set(FormFields::getDeleted, false)
				.eq(FormFields::getTemplateId, id));
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 问卷表单模板列表
	 */
	@GetMapping("/template/get")
	public Result<SearchResult<FormTemplate>> getTemplate() {
		SearchResult<FormTemplate> search = beanSearcher.search(FormTemplate.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(FormTemplate::getDeleted, true)
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 问卷表单模板 对应模板字段列表
	 */
	@GetMapping("/template/fields/get")
	public Result<SearchResult<FormFields>> getTemplateFields() {
		SearchResult<FormFields> search = beanSearcher.search(FormFields.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(FormFields::getDeleted, true)
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 用户问卷回答列表
	 */
	@GetMapping("/get/question/resp/data")
	public Result<SearchResult<FormFieldsDataView>> getData(Long promotionId, Long fieldsId, Long startTime, Long endTime) {
		DateTime startDate = null;
		DateTime endDate = null;
		if (startTime != null) {
			startDate = DateUtil.date(startTime);
		}
		if (endTime != null) {
			endDate = DateUtil.date(endTime);
		}
		if (promotionId != null) {
			QuestionnairePromotion byId = promotionService.getById(promotionId);
			if (byId == null) throw BusinessRuntimeException.getInstance("问卷不存在");
			if (byId.getName().contains("商务")) {
				FormFields fields = formFieldsMapper.selectOne(Wrappers.lambdaQuery(FormFields.class).eq(FormFields::getTemplateId, byId.getTemplateId())
						.like(FormFields::getFieldsName, "渠道").last("limit 1"));
				if (fields != null) {
					fieldsId = fields.getId();
				}
			}
		}
		String timeSql = StrUtil.EMPTY;
		if (startDate != null) {
			timeSql += String.format(" and fa.created_time >= '%s'", startDate);
		}
		if (endDate != null) {
			timeSql += String.format(" and fa.created_time < '%s'", endDate);
		}
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap())
				.field(FormFieldsDataView::getFieldsId, fieldsId);
		if (StrUtil.isNotBlank(timeSql)) {
			builder.put("time_sql", timeSql);
		}
		SearchResult<FormFieldsDataView> search = beanSearcher.search(FormFieldsDataView.class, builder.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * @param promotionId
	 */
	@GetMapping("/export/question/resp/data")
	public void exportQuestionInfo(@RequestParam(required = false, defaultValue = "1") Long promotionId, Long startTime, Long endTime, String charset, HttpServletResponse response) throws Exception {
		DateTime startDate = null;
		DateTime endDate = null;
		if (startTime != null) {
			startDate = DateUtil.date(startTime);
		}
		if (endTime != null) {
			endDate = DateUtil.date(endTime);
		}
		formService.exportQuestionInfo(promotionId, startDate, endDate, response);
	}
}
