package com.ruoyi.web.controller.front;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mxjb.domain.MultipleWayData;
import com.ruoyi.mxjb.domain.MxjbMultipleWayForm;
import com.ruoyi.system.domain.SysArea;
import com.ruoyi.system.service.ISysAreaService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.voluntary.domain.BusiGrade;
import com.ruoyi.voluntary.service.IBusiGradeService;
import com.ruoyi.web.domain.MultipleWayReportDto;
import com.ruoyi.web.service.MultipleWayService;
import com.ruoyi.web.util.MultiplyWayExporter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "04 多元升学管理")
@RestController
@RequestMapping("front/multiway/")
public class FrontMultipleWayController extends BaseController {
    private final MultipleWayService multipleWayService;
    private final ISysAreaService sysAreaService;
    private final ISysUserService sysUserService;
    private final ISysConfigService sysConfigService;
    private Map<Long, String> gradeMap;
    private final String multiWayReportData = "multiple-way-schedules";

    public FrontMultipleWayController(MultipleWayService multipleWayService, ISysAreaService sysAreaService, ISysUserService sysUserService, ISysConfigService sysConfigService, IBusiGradeService busiGradeService) {
        this.multipleWayService = multipleWayService;
        this.sysAreaService = sysAreaService;
        this.sysUserService = sysUserService;
        this.sysConfigService = sysConfigService;
        gradeMap = busiGradeService.selectBusiGradeList(new BusiGrade()).stream().collect(Collectors.toMap(BusiGrade::getId, BusiGrade::getName));
    }

    @PostMapping("submit")
    @ApiOperation("03 Submit multiple way form, Returns saved formId")
    public AjaxResult submitMultipleWayForm(@RequestBody MultipleWayData.MultipleWayForm data) {
        return multipleWayService.submitMultipleWayForm(data);
    }

    @GetMapping("report")
    @ApiOperation("04 Returns conclusion of all multiple way directions")
    public AjaxResult getMultipleWayConclusions(@RequestParam Long formId) {
        return AjaxResult.success("查询成功!", multipleWayService.getMultipleWayConclusions(formId));
    }

    @GetMapping("list")
    @ApiOperation("05 Get multiple way form history list")
    public TableDataInfo getMultipleWayHistories(@ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
                              @ApiParam(value = "页大小", example = "15") @RequestParam Integer pageSize) {
        startPage();
        List<MxjbMultipleWayForm> formList = multipleWayService.getMultipleWayHistories(pageNum, pageSize);
        return getDataTable(formList);
    }

    @GetMapping("area")
    @ApiOperation("06 Get area")
    // Get multiple way native province/city/district
    // Returns: area information
    public AjaxResult getMultipleWayArea(@ApiParam(value = "页数", example = "") @RequestParam(required = false) String keyword,
                                                 @ApiParam(value = "父级代码", example = "15") @RequestParam(required = false) Long parentId) {
        if (parentId == null) parentId = 0L;
        SysArea cond = new SysArea();
        cond.setPid(parentId);
        cond.setName(keyword);
        List<SysArea> areaList = sysAreaService.selectSimpleSysAreaList(cond);
        return AjaxResult.success(areaList);
    }
    /**
     * 删除bWwwNews
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(multipleWayService.deleteMultipleWayHistories(ids));
    }

    @GetMapping("/export")
    public void export(@RequestParam Long formId, HttpServletResponse response)
    {
        MxjbMultipleWayForm multiplyWayForm = multipleWayService.getMxjbMultipleWayForm(formId);
        MultipleWayReportDto rp = multipleWayService.getMultipleWayConclusions(multiplyWayForm);
        Map<String, String> variableMap = Maps.newHashMap();
        MultipleWayData.MultipleWayForm form = rp.getContent();
        List<MultipleWayData.MultipleWayConclusion> resultList = Lists.newArrayList(rp.getValidList());
        resultList.addAll(rp.getInvalidList());

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String gradeName = gradeMap.get(sysUser.getGradeId());
        variableMap.put("form_name", sysUser.getNickName());
        variableMap.put("form_gender", form.getGender());
        variableMap.put("form_age", String.valueOf(form.getAge()));
        variableMap.put("form_nation", form.getNation());
        variableMap.put("form_phase", StringUtils.isNotBlank(gradeName) ? gradeName : "");
        variableMap.put("form_course0", form.getCourse0());
        variableMap.put("form_score", form.getScore());
        variableMap.put("form_foreignL", form.getForeignL());
        variableMap.put("form_foreignLSpoken", form.getForeignLSpoken());
        variableMap.put("form_height", form.getHeight() + " cm");
        variableMap.put("form_weight", form.getWeight() + " kg");
        variableMap.put("form_eyesightL", String.valueOf(form.getEyesightL()));
        variableMap.put("form_eyesightR", String.valueOf(form.getEyesightR()));
        variableMap.put("form_disease", form.getDisease());
        variableMap.put("form_provinceName", form.getProvinceName() + "  ");
        variableMap.put("form_cityName", form.getCityName() + "  ");
        variableMap.put("form_districtName", form.getDistrictName());
        variableMap.put("form_nativeType", form.getNativeType());
        variableMap.put("form_nativeSWP", getValue(form.getNativeSWP()));
        variableMap.put("form_nativeLocal", getValue(form.getNativeLocal()));
        variableMap.put("form_feeExpectable", form.getFeeExpectable());
        variableMap.put("form_criminalRecords", getValue(form.getCriminalRecords()));
        variableMap.put("form_frontierChildren", getValue(form.getFrontierChildren()));
        variableMap.put("form_toBeTeacher", getValue(form.getToBeTeacher()));
        variableMap.put("form_toBeGraduate", getValue(form.getToBeGraduate()));
        variableMap.put("form_awards", form.getAwards());

        for (MultipleWayData.MultipleWayConclusion conclusion : resultList) {
            variableMap.put(conclusion.getDirection(), MultiplyWayExporter.getTextLine(conclusion.getValid(), conclusion.getFailures()));
        }
        JSONArray jsonList = JSONArray.parseArray(sysConfigService.selectConfigByKey(multiWayReportData));
        List<String> tableRows = Lists.newArrayList();
        for (int i = 0; i < jsonList.size(); i++) {
            JSONObject jsonObject = jsonList.getJSONObject(i);
            String period = jsonObject.getString("period");
            String months = jsonObject.getString("months");
            String events = jsonObject.getString("events");
            String attentions = jsonObject.getString("attentions");
            tableRows.add(MultiplyWayExporter.getTableRow(period, months, events, attentions));
        }
        variableMap.put("多元升学路径计划", StringUtils.join(tableRows, ""));
        MultiplyWayExporter.export(response, rp, variableMap);
    }

    private String getValue(String text) {
        return ("Y".equals(text) || "是".equals(text)) ? "是" : "否";
    }
}
