package com.mortals.xhx.module.matter.web;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.module.matter.model.MatterDatumEntity;
import com.mortals.xhx.module.matter.model.MatterDatumFileEntity;
import com.mortals.xhx.module.matter.model.MatterDatumFileQuery;
import com.mortals.xhx.module.matter.service.MatterDatumFileService;
import com.mortals.xhx.module.matter.service.MatterDatumService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mortals.framework.ap.SysConstains.MESSAGE_INFO;

/**
 * 事项申请材料
 *
 * @author zxfei
 * @date 2022-01-20
 */
@RestController
@RequestMapping("matter/datum")
@Slf4j
public class MatterDatumController extends BaseCRUDJsonBodyMappingController<MatterDatumService, MatterDatumEntity, Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private MatterDatumFileService matterDatumFileService;

    public MatterDatumController() {
        super.setModuleDesc("事项申请材料");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "isMust", paramService.getParamBySecondOrganize("MatterDatum", "isMust"));
        this.addDict(model, "materialType", paramService.getParamBySecondOrganize("MatterDatum", "materialType"));
        this.addDict(model, "materialProperty", paramService.getParamBySecondOrganize("MatterDatum", "materialProperty"));
        this.addDict(model, "electronicgs", paramService.getParamBySecondOrganize("MatterDatum", "electronicgs"));
        this.addDict(model, "materialSource", paramService.getParamBySecondOrganize("MatterDatum", "materialSource"));
        this.addDict(model, "paperNum", paramService.getParamBySecondOrganize("MatterDatum", "paperNum"));
        this.addDict(model, "jianmMs", paramService.getParamBySecondOrganize("MatterDatum", "jianmMs"));
        this.addDict(model, "isjianm", paramService.getParamBySecondOrganize("MatterDatum", "isjianm"));
        this.addDict(model, "isLack", paramService.getParamBySecondOrganize("MatterDatum", "isLack"));
        this.addDict(model, "source", paramService.getParamBySecondOrganize("MatterDatum", "source"));
        super.init(model, context);
    }

    @Override
    protected int viewAfter(Long id, Map<String, Object> model, MatterDatumEntity entity, Context context) throws AppException {
        List<MatterDatumFileEntity> matterDatumFileEntities = matterDatumFileService.find(new MatterDatumFileQuery().datumId(entity.getId()));
        entity.setDatumFileList(matterDatumFileEntities);
        return super.viewAfter(id, model, entity, context);
    }


    /**
     * @param id
     * @param model
     * @param entity
     * @param context
     * @return
     * @throws AppException
     */
    @Override
    protected int infoAfter(Long id, Map<String, Object> model, MatterDatumEntity entity, Context context) throws AppException {
        List<MatterDatumFileEntity> matterDatumFileEntities = matterDatumFileService.find(new MatterDatumFileQuery().datumId(entity.getId()));
        entity.setDatumFileList(matterDatumFileEntities);
        return super.infoAfter(id, model, entity, context);
    }


    /**
     * @param query
     * @param model
     * @param context
     * @throws AppException
     */
    @Override
    protected void doListBefore(MatterDatumEntity query, Map<String, Object> model, Context context) throws AppException {
        MDC.put("startTime", String.valueOf(System.currentTimeMillis()));
        if (ObjectUtils.isEmpty(query.getSize())) {
            query.setSize(20);
        }
        if (ObjectUtils.isEmpty(query.getOrderColList())) {
            query.getOrderColList().add(new OrderCol("id", OrderCol.DESCENDING));
        }
        super.doListBefore(query, model, context);
    }

    /**
     * @param query
     * @param model
     * @param context
     * @return
     * @throws AppException
     */
    @Override
    protected int doListAfter(MatterDatumEntity query, Map<String, Object> model, Context context) throws AppException {
        List<MatterDatumEntity> matterDatumEntities = (List<MatterDatumEntity>) model.get(KEY_RESULT_DATA);
        //去重复
        List<MatterDatumEntity> collect = matterDatumEntities.stream().distinct().collect(Collectors.toList());
        model.put(KEY_RESULT_DATA, collect);
        Map<String, String> map = MDC.getCopyOfContextMap();
        String startTime = map.getOrDefault("startTime", String.valueOf(System.currentTimeMillis()));
        long takeTime = (System.currentTimeMillis() - Long.parseLong(startTime));
        log.info("耗时：{}ms ", takeTime);
        return super.doListAfter(query, model, context);
    }


    /**
     * 查询的材料 名称去重 并且
     *
     * @param query
     * @return
     */
    @PostMapping(value = "matterlist")
    @UnAuth
    public Rest<Object> matterlist(@RequestBody MatterDatumEntity query) {
        Rest<Object> ret = new Rest<>();
        Map<String, Object> model = new HashMap<>();
        Context context = this.getContext();
        String busiDesc = "查询材料" + this.getModuleDesc();
        int code = VALUE_RESULT_SUCCESS;
        try {
            List<MatterDatumEntity> list = this.service.findMatterList(query, context);
            model.put(KEY_RESULT_DATA, list);
            model.put(MESSAGE_INFO, busiDesc + "成功");
            if (!ObjectUtils.isEmpty(getContext()) && !ObjectUtils.isEmpty(getContext().getUser())) {
                recordSysLog(request, busiDesc + " 【成功】");
            }
        } catch (Exception e) {
            code = VALUE_RESULT_FAILURE;
            this.doException(request, busiDesc, model, e);
        }
        this.init(model, context);
        ret.setCode(code);
        ret.setData(model);
        ret.setMsg(model.get(MESSAGE_INFO) == null ? "" : model.remove(MESSAGE_INFO).toString());
        return ret;
    }


    /**
     * 解密下载地址
     *
     * @param encryptId 文件加密id
     * @return
     */
    @GetMapping(value = "decodeDownloadUrl")
    @UnAuth
    public Rest<String> decodeDownloadUrl(@RequestParam(name = "encryptId") String encryptId) {
        Map<String, Object> model = new HashMap<>();
        String busiDesc = "查询材料" + this.getModuleDesc();
        try {
            String encryUrl = "http://www.sczwfw.gov.cn/jiq/interface/item/annex/encryptUrl?id=" + encryptId;
            String resp = HttpUtil.get(encryUrl);
            JSONObject obj = JSON.parseObject(resp);
            String code = obj.getString("code");
            String data = obj.getString("data");
            if ("0".equals(code)) {
                return Rest.ok("获取附件链接成功！", data);
            } else {
                return Rest.fail("获取链接失败");
            }
        } catch (Exception e) {
            this.doException(request, busiDesc, model, e);
            return Rest.fail(e.getMessage());
        }
    }

}