package com.yeejoin.amos.boot.module.jcs.biz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledRo;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertSubmittedDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertSubmittedSMSDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.SchedulingReportingDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.TemplateDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.TemplateExtendDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertSubmitted;
import com.yeejoin.amos.boot.module.jcs.api.entity.Template;
import com.yeejoin.amos.boot.module.jcs.api.enums.AlertBusinessTypeEnum;
import com.yeejoin.amos.boot.module.jcs.api.enums.SubmissionMethodEnum;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertCalledServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertSubmittedObjectServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertSubmittedServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.PowerTransferServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.RuleAlertCalledService;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.TemplateServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 警情报送记录
 *
 * @author tb
 * @date 2021-06-17
 */
@RestController
@Api(tags = "警情报送记录Api")
@RequestMapping(value = "/alert-submitted")
public class AlertSubmittedController extends BaseController {

    @Autowired
    AlertSubmittedServiceImpl alertSubmittedService;

    @Autowired
    TemplateServiceImpl templateService;

    @Autowired
    AlertCalledServiceImpl alertCalledService;

    @Autowired
    DataDictionaryServiceImpl dataDictionaryService;

    @Autowired
    PowerTransferServiceImpl powerTransferService;

    @Autowired
    AlertSubmittedObjectServiceImpl iAlertSubmittedObjectService;

    /**
     * 新增警情报送记录
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增警情报送记录", notes = "新增警情报送记录")
    public ResponseModel<Object> saveAlertSubmitted(@RequestBody AlertSubmittedDto alertSubmittedDto) throws Exception {
        return ResponseHelper.buildResponse(alertSubmittedService.save(alertSubmittedDto, getUserInfo().getRealName()));
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")

    public ResponseModel<Boolean> deleteById(@PathVariable Long id) {
        return ResponseHelper.buildResponse(alertSubmittedService.removeById(id));
    }

    /**
     * 修改警情报送记录
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改警情报送记录", notes = "修改警情报送记录")

    public ResponseModel<Boolean> updateByIdAlertSubmitted(@RequestBody AlertSubmitted alertSubmitted) {
        return ResponseHelper.buildResponse(alertSubmittedService.updateById(alertSubmitted));
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @TycloudOperation( ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<AlertSubmitted> selectById(@PathVariable Long id) {
        return ResponseHelper.buildResponse(alertSubmittedService.getById(id));

    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/scheduling/list", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "根据警情id查询融合调度列表", notes = "根据警情id查询融合调度列表")
    public ResponseModel<SchedulingReportingDto> listSchedulingByParam(@RequestBody AlertSubmittedDto queryParam) {
        return ResponseHelper.buildResponse(alertSubmittedService.listSchedulingByParam(queryParam));
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/reporting/list", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "根据警情id查询警情报送列表", notes = "根据警情id查询警情报送列表")
    public ResponseModel<SchedulingReportingDto> listReportingByParam(@RequestBody AlertSubmittedDto queryParam) {
        queryParam.setSubmissionMethodCode(SubmissionMethodEnum.SMS.getCode());
        return ResponseHelper.buildResponse(alertSubmittedService.listReportingByParam(queryParam));
    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public IPage<AlertSubmitted> listPage(String pageNum, String pageSize, AlertSubmitted alertSubmitted) {

        Page<AlertSubmitted> pageBean;
        QueryWrapper<AlertSubmitted> alertSubmittedQueryWrapper = new QueryWrapper<>();
        Class<? extends AlertSubmitted> aClass = alertSubmitted.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            if (field.getName().equals("serialVersionUID")) {
                return;
            }
            try {
                ReflectionUtils.makeAccessible(field);
                Object o = field.get(alertSubmitted);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(alertSubmitted);
                        alertSubmittedQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class) || "long".equals(type.toString())) {
                        Long fileValue = (Long) field.get(alertSubmitted);
                        alertSubmittedQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(alertSubmitted);
                        alertSubmittedQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
                throw new BadRequest("系统异常");
            }
        });
        IPage<AlertSubmitted> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = alertSubmittedService.page(pageBean, alertSubmittedQueryWrapper);
        return page;
    }

    /**
     * 获取警情续报内容
     *
     * @param alertCalledId 警情id
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{alertCalledId}/alert_submitted", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取警情续报内容和模板", notes = "获取警情续报内容和模板")
    public ResponseModel<Object> getAlertSubmittedContent(@PathVariable Long alertCalledId) {
        ArrayList<TemplateDto> templateVos = new ArrayList<>();
        try {
            // 获取警情详情
            String companyName = getSelectedOrgInfo().getCompany().getCompanyName();
            alertSubmittedService.getAlertSubmittedContent(alertCalledId, templateVos, companyName);
        } catch (IllegalAccessException e) {
            throw  new BadRequest("系统异常");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ResponseHelper.buildResponse(templateVos);
    }

    /**
     * 获取融合调度短信内容
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}/scheduling_content", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取融合调度短信内容", notes = "获取融合调度短信内容")
    public ResponseModel<AlertSubmittedSMSDto> getSchedulingContent(@PathVariable Long id) throws ParseException {
        // 获取报送内容
        // 任务 4174  日常值班---融合调度----短信模版中的内容用户可以全部删除掉，按照自定义内容重新录入发送内容 by litw 2021年10月27日
        AlertSubmittedSMSDto schedulingContent = alertSubmittedService.getSchedulingContent(id);
        AlertCalledObjsDto alertCalledVo  = (AlertCalledObjsDto) alertCalledService.selectAlertCalledByIdNoRedisNew(Long.valueOf(schedulingContent.getAlertCallId()));
        /**
         * 构建警情报送规则对象
         */
        boolean flag = false;
        TemplateExtendDto template = null;
        Template templateN = null;

        if(!schedulingContent.getType().equals(AlertBusinessTypeEnum.警情结案.getName()) &&
                !schedulingContent.getType().equals(AlertBusinessTypeEnum.警情续报.getName()) &&
                        !schedulingContent.getType().equals(AlertBusinessTypeEnum.非警情确认.getName())) {
             // 获取模板
                    templateN = templateService
                    .getOne(new QueryWrapper<Template>().eq("type_code", "JQCB").eq("format", false));
            template = new TemplateExtendDto();
            BeanUtils.copyProperties(templateN,template);
            template.setRichContent(template.getContent());
            flag = true;
        }

        AlertCalledRo alertCalledRo = new AlertCalledRo();
        AlertCalled alertCalled = alertCalledVo.getAlertCalled();

        String replaceContent = RuleAlertCalledService.init(alertCalledRo,alertCalledVo);

        Map<String, String> definitions = new HashMap<>();
        definitions.put("$type",alertCalled.getAlertType());
        definitions.put("$callTime", DateUtils.convertDateToString(alertCalled.getCallTime(),DateUtils.DATE_TIME_PATTERN));
        definitions.put("$replaceContent",replaceContent);
        definitions.put("$address",ValidationUtil.isEmpty(alertCalled.getAddress()) ? "" : alertCalled.getAddress());

        definitions.put("$contactUser",ValidationUtil.isEmpty(alertCalled.getContactUser()) ? "" : alertCalled.getContactUser());
        definitions.put("$trappedNum",ValidationUtil.isEmpty(alertCalledRo.getTrappedNum()) ? "" : String.valueOf(alertCalled.getTrappedNum()));
        definitions.put("$casualtiesNum",ValidationUtil.isEmpty(alertCalled.getCasualtiesNum()) ? "" : String.valueOf(alertCalled.getCasualtiesNum()));
        definitions.put("$contactPhone",ValidationUtil.isEmpty(alertCalled.getContactPhone()) ? "" :  alertCalled.getContactPhone());

        String  companyName = JSON.parseObject(schedulingContent.getSubmissionContent()).getString("companyName") ;

        JSONObject jsonObject = null;
        if(!ValidationUtil.isEmpty(alertCalled.getUpdateTime())) {
             jsonObject = JSON.parseObject(schedulingContent.getSubmissionContent());
            jsonObject.put("recDate",DateUtils.convertDateToString(alertCalled.getUpdateTime(), DateUtils.DATE_TIME_PATTERN));
        }

        definitions.put("$companyName", null == companyName ? "" : companyName);

        String content ="";

        if(flag) {
            content  = getTaskInformation( template.getRichContent(),definitions);
        } else {
            content =  getTaskInformation( schedulingContent.getSubmissionTemplate(),definitions);
        }

        if(jsonObject != null) {
            schedulingContent.setSubmissionContent(jsonObject.toJSONString());
        }

        schedulingContent.setSubmissionTemplate(content);
        if(!ValidationUtil.isEmpty(schedulingContent.getSubmissionContent())) {
            try {
                JSON.parseObject(schedulingContent.getSubmissionContent());
            } catch (JSONException jsonException) {
                schedulingContent.setSubmissionContentValue(schedulingContent.getSubmissionContent());
                schedulingContent.setSubmissionTemplate("<p><span data-name=\"custom\"></span></p>");
            }
        }
        return ResponseHelper.buildResponse(schedulingContent);
    }


    private String getTaskInformation(String content, Map<String, String> definitions) {
        int size = definitions.size();
        String[] keys = definitions.keySet().toArray(new String[size]);
        String[] values = definitions.values().toArray(new String[size]);
        return StringUtils.replaceEach(content, keys, values);
    }
}

