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

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.module.basics.model.BasicsDatumEntity;
import com.mortals.xhx.module.basics.model.BasicsDatumQuery;
import com.mortals.xhx.module.basics.model.BasicsEntity;
import com.mortals.xhx.module.basics.model.BasicsQuery;
import com.mortals.xhx.module.basics.service.BasicsDatumService;
import com.mortals.xhx.module.basics.service.BasicsService;
import com.mortals.xhx.utils.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>Title: 一件事基础表</p>
 * <p>Description: BasicsController  </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 *
 * @author zxfei
 * @version 1.0.0
 */
@RestController
@RequestMapping("basics")
public class BasicsController extends BaseCRUDJsonMappingController<BasicsService, BasicsForm, BasicsEntity, Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private BasicsDatumService basicsDatumService;


    public BasicsController() {
        super.setFormClass(BasicsForm.class);
        super.setModuleDesc("一件事基础表");
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, BasicsForm form, Map<String, Object> model, Context context) {
        this.addDict(model, "isMust", YesNoEnum.getEnumMap());
        this.addDict(model, "iszzsb", YesNoEnum.getEnumMap());
        this.addDict(model, "materialType", paramService.getParamByFirstOrganize(Constant.Param_materialType));
        this.addDict(model, "electronicgs", paramService.getParamByFirstOrganize(Constant.Param_electronicgs));
        this.addDict(model, "materialSourceSm", paramService.getParamByFirstOrganize(Constant.Param_materialSourceSm));
        this.addDict(model, "paperGg", paramService.getParamByFirstOrganize(Constant.Param_paperGg));
        this.addDict(model, "jianmMs", paramService.getParamByFirstOrganize(Constant.Param_jianmMs));
        this.addDict(model, "sealWay", paramService.getParamByFirstOrganize(Constant.Param_sealWay));


    }

    @Override
    protected void doListBefore(HttpServletRequest request, HttpServletResponse response, BasicsForm form, Map<String, Object> model, Context context) throws AppException {
        form.getQuery().setValid(YesNoEnum.NO.getValue());
    }

    /**
     * 查看二维码
     */
    @PostMapping(value = "viewQrCode")
    public String viewQrCode(BasicsForm form) {
        JSONObject jsonObject = new JSONObject();
        try {
            if (form == null || form.getEntity() == null || form.getEntity().getId() == null) {
                throw new AppException("二维码为空");
            }
            String qrCodeUrl = paramService.getValueByKey("qrcode");
            //http://sncs.wx3.com.cn/wx.html#/chatroom?id=26&title=我要打广告
            BasicsEntity entity = service.get(form.getEntity().getId(), null);
            String qrCode = qrCodeUrl + "?id=" + entity.getId() + "&title=" + entity.getTname();
            jsonObject.put("qrCode", "data:image/png;base64," + QRCodeUtil.encode(qrCode, null, false));
            jsonObject.put("qrCodeUrl", qrCode);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        } catch (Exception e) {
            log.error("查看二维码错误", e);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
        }

        return jsonObject.toJSONString();
    }


    @Override
    protected int saveAfter(HttpServletRequest request, HttpServletResponse response, BasicsForm form, Map<String, Object> model, Context context) throws AppException {
        String oneDatumIds = request.getParameter("entity.oneDatumIds");
        Long id = (Long) model.get("id");
        List<BasicsDatumEntity> list = new ArrayList<>();
        if (!ObjectUtils.isEmpty(oneDatumIds)) {
            list = Arrays.asList(oneDatumIds.split(",")).stream().map(item -> {
                BasicsDatumEntity entity = new BasicsDatumEntity();
                entity.setBasicsId(id);
                entity.setOneDatumIds(Long.parseLong(item));
                entity.setCreateUser(this.getCurUser().getLoginName());
                entity.setCreateTime(new Date());
                return entity;
            }).collect(Collectors.toList());
        }
        if (form.getEntity().newEntity()) {
            //新增 保存关联材料信息
            int num = basicsDatumService.save(list,context);
        } else {
            //更新 通过id找到关联项，插入不存在的关联  删除提交中没有的想
            List<BasicsDatumEntity> oldList = this.basicsDatumService.find(new BasicsDatumQuery().basicsId(id));
            basicsDatumService.updateBatch(oldList,list,context);
        }
        return super.saveAfter(request, response, form, model, context);
    }

    @Override
    public String delete(BasicsForm form) {
        if (form.getId() != null && form.getId().length != 0) {
            JSONObject ret = new JSONObject();
            int code = VALUE_RESULT_SUCCESS;
            String busiDesc = "删除" + this.getModuleDesc();
            try {
                BasicsEntity entity = new BasicsEntity();
                entity.setId(form.getId()[0]);
                entity.setValid(YesNoEnum.YES.getValue());
                entity.setUpdateTime(new Date());
                entity.setUpdateUser(this.getCurUser().getLoginName());
                this.service.update(entity);
                this.recordSysLog(request, busiDesc + " 【成功】");
            } catch (Exception e) {
                log.error("删除异常", e);
                this.doException(request, busiDesc, null, e);
                code = VALUE_RESULT_FAILURE;
            }

            ret.put("code", Integer.valueOf(code));
            ret.put("msg", "删除成功");
            return ret.toJSONString();
        } else {
            return this.createFailJsonResp("请至少选择一条记录");
        }
    }
}