package com.xueyi.system.staff.controller;

import com.alibaba.fastjson2.JSONObject;
import com.xueyi.common.cache.utils.SourceUtil;
import com.xueyi.common.core.constant.basic.SecurityConstants;
import com.xueyi.common.core.context.SecurityContextHolder;
import com.xueyi.common.core.utils.core.ObjectUtil;
import com.xueyi.common.core.utils.core.StrUtil;
import com.xueyi.common.core.utils.file.FileTypeUtil;
import com.xueyi.common.core.utils.file.MimeTypeUtil;
import com.xueyi.common.core.web.result.AjaxResult;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.core.web.validate.V_A;
import com.xueyi.common.core.web.validate.V_E;
import com.xueyi.common.log.annotation.Log;
import com.xueyi.common.log.enums.BusinessType;
import com.xueyi.common.security.annotation.InnerAuth;
import com.xueyi.common.security.annotation.Logical;
import com.xueyi.common.security.annotation.RequiresPermissions;
import com.xueyi.common.web.entity.controller.BaseController;
import com.xueyi.file.api.domain.SysFile;
import com.xueyi.file.api.feign.RemoteFileService;
import com.xueyi.nlt.api.netty.domain.vo.DmWebSocketMessageVo;
import com.xueyi.nlt.api.nlt.feign.RemoteIntentService;
import com.xueyi.system.api.model.Source;
import com.xueyi.system.api.organize.domain.dto.SysEnterpriseDto;
import com.xueyi.system.api.staff.domain.dto.DmStaffDto;
import com.xueyi.system.api.staff.domain.po.DmStaffPo;
import com.xueyi.system.authority.service.ISysLoginService;
import com.xueyi.system.organize.service.ISysEnterpriseService;
import com.xueyi.system.staff.domain.query.DmStaffQuery;
import com.xueyi.system.api.staff.domain.vo.DmStaffFeature;
import com.xueyi.system.staff.service.IDmStaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 人员管理 业务处理
 *
 * @author xueyi
 */
@RestController
@RequestMapping("/staff")
public class DmStaffController extends BaseController<DmStaffQuery, DmStaffDto, IDmStaffService> {

    @Autowired
    IDmStaffService dmStaffService;

    @Autowired
    ISysLoginService loginService;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private RemoteIntentService remoteIntentService;

    @Autowired
    ISysEnterpriseService enterpriseService;

    /** 定义节点名称 */
    @Override
    protected String getNodeName() {
        return "人员" ;
    }

    /**
     * 获取人员列表 | 内部调用
     */
    @InnerAuth
    @GetMapping("/inner/{devId}/{timestamp}")
    public R<List<DmStaffFeature>> listInner(@RequestParam(value = "devId") String devId, @RequestParam(value = "timestamp") String timestamp) {
        System.out.println("/inner/list");
        return R.ok(dmStaffService.selectStaffListByTimestamp(devId,timestamp));
        //return success(dmStaffService.selectStaffListByTimestamp(deviceVo));
    }

    /**
     * 获取人员列表 | 内部调用
     */
    @GetMapping("/inner/tenantId/{enterpriseName}")
    public R<SysEnterpriseDto> tenantIdInner(@RequestParam(value = "enterpriseName") String enterpriseName) {
        //根据数字人id、设备id获取租户id
        return R.ok(loginService.loginByEnterpriseName(enterpriseName));
    }

    /**
     * 查询人员列表
     */
    @Override
    @GetMapping("/list")
    @RequiresPermissions(Auth.DM_STAFF_LIST)
    public AjaxResult list(DmStaffQuery dmStaff) {
        List<DmStaffPo> list = dmStaffService.selectStaffList(dmStaff);
        //return AjaxResult.success(list);
        return super.list(dmStaff);
    }

    /**
     * 查询人员详细
     */
    @Override
    @GetMapping(value = "/{id}")
    @RequiresPermissions(Auth.DM_STAFF_SINGLE)
    public AjaxResult getInfo(@PathVariable Serializable id) {
        return super.getInfo(id);
    }

    /**
     * 人员新增
     */
    @Override
    @PostMapping
    @RequiresPermissions(Auth.DM_STAFF_ADD)
    @Log(title = "人员管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated({V_A.class}) @RequestBody DmStaffDto dmStaff) {
        Long tenantId = Long.parseLong(String.valueOf(SecurityContextHolder.getLocalMap().get("enterprise_id")));
        SysEnterpriseDto enterpriseDto = enterpriseService.selectById(tenantId);
        Source source = SourceUtil.getSourceCache(enterpriseDto.getStrategyId());

        AjaxResult result = super.add(dmStaff);
        if (dmStaff.getBirthDate() != null) {
            DmWebSocketMessageVo vo = new DmWebSocketMessageVo();
            JSONObject birthJson = new JSONObject();
            birthJson.put("name",dmStaff.getUserName());
            birthJson.put("orderId",dmStaff.getId());
            birthJson.put("years",new Date().getYear() - dmStaff.getBirthDate().getYear());
            birthJson.put("timestamp",dmStaff.getBirthDate().getTime());
            vo.setTemplate("birthday");
            vo.setFormat(birthJson);
            System.out.println(birthJson.toJSONString());
            remoteIntentService.sendMessage(vo,tenantId,source.getMaster(), SecurityConstants.INNER);
        }
        if (dmStaff.getHireDate() != null) {
            DmWebSocketMessageVo vo2 = new DmWebSocketMessageVo();
            JSONObject hireJson = new JSONObject();
            hireJson.put("name",dmStaff.getUserName());
            hireJson.put("orderId",dmStaff.getId());
            hireJson.put("years",new Date().getYear() - dmStaff.getHireDate().getYear());
            hireJson.put("timestamp",dmStaff.getHireDate().getTime());
            vo2.setTemplate("hireDate");
            vo2.setFormat(hireJson);
            System.out.println(hireJson.toJSONString());
            remoteIntentService.sendMessage(vo2,tenantId,source.getMaster(), SecurityConstants.INNER);
        }
        return result;
    }

    /**
     * 人员修改
     */
    @Override
    @PutMapping
    @RequiresPermissions(Auth.DM_STAFF_EDIT)
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated({V_E.class}) @RequestBody DmStaffDto dmStaff) {
        Long tenantId = Long.parseLong(String.valueOf(SecurityContextHolder.getLocalMap().get("enterprise_id")));
        SysEnterpriseDto enterpriseDto = enterpriseService.selectById(tenantId);
        Source source = SourceUtil.getSourceCache(enterpriseDto.getStrategyId());
        if (dmStaff.getBirthDate() != null) {
            DmWebSocketMessageVo vo = new DmWebSocketMessageVo();
            JSONObject birthJson = new JSONObject();
            birthJson.put("name",dmStaff.getUserName());
            birthJson.put("orderId",dmStaff.getId());
            birthJson.put("years",new Date().getYear() - dmStaff.getBirthDate().getYear());
            birthJson.put("timestamp",dmStaff.getBirthDate().getTime());
            vo.setTemplate("birthday");
            vo.setFormat(birthJson);
            System.out.println(birthJson.toJSONString());
            remoteIntentService.sendMessage(vo,tenantId,source.getMaster(), SecurityConstants.INNER);
        }
        if (dmStaff.getHireDate() != null) {
            DmWebSocketMessageVo vo2 = new DmWebSocketMessageVo();
            JSONObject hireJson = new JSONObject();
            hireJson.put("name",dmStaff.getUserName());
            hireJson.put("orderId",dmStaff.getId());
            hireJson.put("years",new Date().getYear() - dmStaff.getHireDate().getYear());
            hireJson.put("timestamp",dmStaff.getHireDate().getTime());
            vo2.setTemplate("hireDate");
            vo2.setFormat(hireJson);
            System.out.println(hireJson.toJSONString());
            remoteIntentService.sendMessage(vo2,tenantId,source.getMaster(), SecurityConstants.INNER);
        }
        return super.edit(dmStaff);
    }

    /**
     * 人员修改状态
     */
    @Override
    @PutMapping("/status")
    @RequiresPermissions(value = {Auth.DM_STAFF_EDIT, Auth.DM_STAFF_ES}, logical = Logical.OR)
    @Log(title = "人员管理", businessType = BusinessType.UPDATE_STATUS)
    public AjaxResult editStatus(@RequestBody DmStaffDto dmStaff) {
        return super.editStatus(dmStaff);
    }

    /**
     * 人员批量删除
     */
    @Override
    @DeleteMapping("/batch/{idList}")
    @RequiresPermissions(Auth.DM_STAFF_DEL)
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
    public AjaxResult batchRemove(@PathVariable List<Long> idList) {
        return super.batchRemove(idList);
    }

    /**
     * 获取人员选择框列表
     */
    @Override
    @GetMapping("/option")
    public AjaxResult option() {
        return super.option();
    }

    interface Auth {
        /** 系统 - 人员管理 - 列表 */
        String DM_STAFF_LIST = "staff:staff:list";
        /** 系统 - 人员管理 - 详情 */
        String DM_STAFF_SINGLE = "staff:staff:single";
        /** 系统 - 人员管理 - 新增 */
        String DM_STAFF_ADD = "staff:staff:add";
        /** 系统 - 人员管理 - 修改 */
        String DM_STAFF_EDIT = "staff:staff:edit";
        /** 系统 - 人员管理 - 修改状态 */
        String DM_STAFF_ES = "staff:staff:es";
        /** 系统 - 人员管理 - 删除 */
        String DM_STAFF_DEL = "staff:staff:delete";
    }
    /**
     * 头像上传
     */
    @PostMapping("/upload")
    @Log(title = "人员管理 - 上传头像", businessType = BusinessType.UPDATE)
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            String extension = FileTypeUtil.getExtension(file);
            if (!StrUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.IMAGE_EXTENSION)) {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtil.IMAGE_EXTENSION) + "格式");
            }
            R<SysFile> fileResult = remoteFileService.uploadFace(file);
            if (ObjectUtil.isNull(fileResult) || ObjectUtil.isNull(fileResult.getData()))
                return error("文件服务异常，请联系管理员！");
            String url = fileResult.getData().getUrl();
            // 预留人脸识别与图像质量监测接口，如果监测异常返回错误

            AjaxResult ajax = success();
            ajax.put(AjaxResult.URL_TAG, url);
            return ajax;
        }
        return error("上传图片异常，请联系管理员！");
    }


}
