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

import com.mortals.framework.exception.AppException;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.base.system.role.model.RoleQuery;
import com.mortals.xhx.base.system.role.model.RoleUserEntity;
import com.mortals.xhx.base.system.role.model.RoleUserQuery;
import com.mortals.xhx.base.system.role.service.RoleService;
import com.mortals.xhx.base.system.role.service.RoleUserService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.module.model.model.ModelQuery;
import com.mortals.xhx.module.model.service.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mortals.framework.web.BaseCRUDJsonPhpController;
import com.mortals.xhx.module.workman.model.WorkmanEntity;
import com.mortals.xhx.module.workman.model.WorkmanQuery;
import com.mortals.xhx.module.workman.service.WorkmanService;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

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

import com.alibaba.fastjson.JSONObject;

import java.util.Arrays;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 工作人员
 *
 * @author zxfei
 * @date 2022-01-20
 */
@RestController
@RequestMapping("workman")
public class WorkmanController extends BaseCRUDJsonPhpController<WorkmanService, WorkmanForm, WorkmanEntity, Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleUserService roleUserService;
    @Autowired
    private ModelService modelService;

    public WorkmanController() {
        super.setFormClass(WorkmanForm.class);
        super.setModuleDesc("工作人员");
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, WorkmanForm form, Map<String, Object> model, Context context) {
        this.addDict(model, "politicalstatus", paramService.getParamBySecondOrganize("Workman", "politicalstatus"));
        this.addDict(model, "dangyuan", paramService.getParamBySecondOrganize("Workman", "dangyuan"));
        this.addDict(model, "starlevel", paramService.getParamBySecondOrganize("Workman", "starlevel"));
        this.addDict(model, "online", paramService.getParamBySecondOrganize("Workman", "online"));

        Map<String, String> userCollect = userService.find(new UserQuery(), getContext()).stream()
                .filter(f -> !this.service.find(new WorkmanQuery()).stream().map(WorkmanEntity::getSystemUserId).collect(Collectors.toSet()).contains(f.getId()))
                .collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getRealName(), (o, n) -> n));
        WorkmanEntity workmanEntity = (WorkmanEntity) model.get(KEY_RESULT_ENTITY);
        if (!ObjectUtils.isEmpty(workmanEntity) && !ObjectUtils.isEmpty(workmanEntity.getSystemUserId())) {
            UserEntity userEntity = userService.get(workmanEntity.getSystemUserId());
            if (!ObjectUtils.isEmpty(userEntity)) {
                userCollect.put(userEntity.getId().toString(), userEntity.getRealName());
            }
        }

        Map<String, String> roleCollect = roleService.find(new RoleQuery())
                .stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName(), (o, n) -> n));

        this.addDict(model, "systemUserId", userCollect);
        this.addDict(model, "roleId", roleCollect);
        this.addDict(model, "modelIds", modelService.find(new ModelQuery()).stream().collect(Collectors.toMap(x->x.getId().toString(), y->y.getModelName())));


        super.init(request, response, form, model, context);
    }

    /**
     * 查询工作人员
     */
    @PostMapping(value = "list")
    public String list(@RequestBody WorkmanQuery query) {
        try {
            WorkmanForm form = new WorkmanForm();
            form.setQuery(query);
            return super.list(form);
        } catch (Exception e) {
            log.error("查询工作人员列表错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 新增工作人员
     */
    @PostMapping(value = "add")
    public String add() {
        try {
            WorkmanForm form = new WorkmanForm();
            return super.add(form);
        } catch (Exception e) {
            log.error("新增工作人员错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 编辑工作人员
     */
    @GetMapping(value = "edit")
    public String edit(Long id) {
        try {
            WorkmanForm form = new WorkmanForm();
            form.setId(new Long[]{id});
            return super.edit(form);
        } catch (Exception e) {
            log.error("工作人员模块错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 保存工作人员
     */
    @PostMapping(value = "save")
    public String save(@RequestBody WorkmanEntity entity) {
        try {
            WorkmanForm form = new WorkmanForm();
            form.setWorkman(entity);
            return super.save(form);
        } catch (Exception e) {
            log.error("工作人员模块错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 删除工作人员
     */
    @GetMapping(value = "delete")
    public String delete(String id) {
        try {
            WorkmanForm form = new WorkmanForm();
            String[] split = id.split(",");
            Long[] ids = Arrays.asList(split).stream().map(Long::parseLong).toArray(Long[]::new);
            form.setId(ids);
            return super.delete(form);
        } catch (Exception e) {
            log.error("删除工作人员错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 查看工作人员
     */
    @GetMapping(value = "info")
    public String info(Long id) {
        try {
            WorkmanForm form = new WorkmanForm();
            form.setId(new Long[]{id});
            return super.view(form);
        } catch (Exception e) {
            log.error("查看工作人员错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }


    /**
     * 工作人员导入模板下载
     */
    @PostMapping(value = "downloadTemplate")
    public void downloadTemplate() {
        try {
            super.downloadTemplate();
        } catch (Exception e) {
            log.error("工作人员导入模板下载错误", e);
        }
    }

    /**
     * 工作人员导出
     */
    @PostMapping(value = "importData")
    public String importData(MultipartFile file, boolean updateSupport) {
        try {
            return super.importData(file, updateSupport);
        } catch (Exception e) {
            log.error("工作人员导入错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 工作人员导出
     */
    @PostMapping("exportExcel")
    public void exportExcel(@RequestBody WorkmanQuery query) {
        try {
            WorkmanForm form = new WorkmanForm();
            form.setQuery(query);
            super.exportExcel(form);
        } catch (Exception e) {
            log.error("工作人员导出错误", e);
        }
    }

    @Override
    protected int editAfter(HttpServletRequest request, HttpServletResponse response, WorkmanForm form, Map<String, Object> model, WorkmanEntity entity, Context context) throws AppException {
        buildWorkman(entity);
        return super.editAfter(request, response, form, model, entity, context);
    }

    @Override
    protected int viewAfter(HttpServletRequest request, HttpServletResponse response, WorkmanForm form, Map<String, Object> model, WorkmanEntity entity, Context context) throws AppException {
        buildWorkman(entity);
        return super.viewAfter(request, response, form, model, entity, context);
    }

    private void buildWorkman(WorkmanEntity entity) {
        UserEntity userEntity = userService.get(entity.getSystemUserId());
        if (!ObjectUtils.isEmpty(userEntity)) {
            entity.setLoginName(userEntity.getLoginName());
            entity.setLoginPwd(userEntity.getLoginPwd());
            RoleUserQuery roleUserQuery = new RoleUserQuery();
            roleUserQuery.setUserId(userEntity.getId());
            RoleUserEntity roleUserEntity = roleUserService.selectOne(roleUserQuery);
            if (!ObjectUtils.isEmpty(roleUserEntity)) {
                entity.setRoleId(roleUserEntity.getRoleId());
            }
        }
    }
}