package com.xueyi.system.digitalmans.controller;

import com.xueyi.common.core.context.SecurityContextHolder;
import com.xueyi.common.core.utils.core.StrUtil;
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.RequiresPermissions;
import com.xueyi.common.web.entity.controller.BaseController;
import com.xueyi.modules.auth.api.domain.vo.IntentionReqDto;
import com.xueyi.system.api.digitalmans.domain.dto.DmSkillDto;
import com.xueyi.system.api.digitalmans.domain.po.DmSkillPo;
import com.xueyi.system.api.staff.domain.po.DmStaffPo;
import com.xueyi.system.digitalmans.domain.dto.DmCustomMadeDto;
import com.xueyi.system.digitalmans.domain.dto.DmDigitalmanDto;
import com.xueyi.system.digitalmans.domain.dto.DmDigitalmanExtDto;
import com.xueyi.system.digitalmans.domain.query.DmDigitalmanExtQuery;
import com.xueyi.system.digitalmans.domain.query.DmDigitalmanQuery;
import com.xueyi.system.digitalmans.domain.query.DmSkillQuery;
import com.xueyi.system.digitalmans.service.IDmDigitalmanExtService;
import com.xueyi.system.digitalmans.service.IDmDigitalmanService;
import com.xueyi.system.digitalmans.service.IDmSkillService;
import com.xueyi.system.staff.mapper.DmStaffMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.List;

/**
 * 访客管理 业务处理
 *
 * @author xueyi
 */
@RestController
@RequestMapping("/skill")
public class DmSkillController extends BaseController<DmSkillQuery, DmSkillDto, IDmSkillService> {

    @Autowired
    IDmSkillService skillService;

    @Autowired
    IDmDigitalmanExtService digitalmanExtService;

    @Autowired
    IDmDigitalmanService digitalmanService;
    /** 定义节点名称 */
    @Override
    protected String getNodeName() {
        return "技能" ;
    }

    /**
     * 获取技能列表 | 内部调用
     */

    @InnerAuth
    @GetMapping("/inner/{devId}/{timestamp}")
    public R<List<DmSkillDto>> skilllistInner(@RequestParam(value = "devId") String devId, @RequestParam(value = "timestamp") String timestamp) {
        System.out.println(devId);
        DmDigitalmanExtQuery manQuery = new DmDigitalmanExtQuery();
        manQuery.setDeviceId(devId);
//        List<DmDigitalmanExtDto> dto = digitalmanExtService.selectListByDeviceId(manQuery);
        String enterpriseId = String.valueOf(SecurityContextHolder.getLocalMap().get("enterprise_id"));
        System.out.println("enterpriseId:"+enterpriseId);
        List<DmDigitalmanExtDto> dto = digitalmanExtService.selectList(new DmDigitalmanExtQuery());
        if (dto!= null && dto.size() > 0) {
            DmDigitalmanExtDto dId = null;
            for (DmDigitalmanExtDto item : dto) {
                System.out.println(item.getId());
                if (item.getDeviceId() != null && item.getDeviceId().equalsIgnoreCase(devId)) {
                    dId = item;
                }
            }
            DmDigitalmanQuery query = new DmDigitalmanQuery();
            query.setManCode(dId.getManCode());
            List<DmDigitalmanDto> dto1 = digitalmanService.selectList(query);
            if (dto1 != null && dto1.size() > 0)
                return R.ok(skillService.selectSkillListByTimestamp(dto1.get(0).getId(),timestamp));
        }

        //return R.ok(skillService.selectSkillListByTimestamp(dto.get(0).getManCode(),timestamp));
        return R.fail("同步数据失败");
        //return success(dmStaffService.selectStaffListByTimestamp(deviceVo));
    }

    @Autowired
    private DmStaffMapper staffMapper;

    @InnerAuth
    @PostMapping("/inner/auth")
    public AjaxResult skillAuth(@Valid @RequestBody IntentionReqDto intentionReqDto) {
        System.out.println(intentionReqDto.getDevId());
        DmSkillPo dto = skillService.selectSkillByCode(intentionReqDto.getSkillCode());
        if (dto == null) {
            return AjaxResult.error("技能不存在");
        }

        String auth = dto.getAuth();
        DmStaffPo staffPo = staffMapper.selectById(intentionReqDto.getStaffId());

        if (staffPo == null) {
            return AjaxResult.error("指定ID的员工不存在");
        }

        String type =  intentionReqDto.getStaffType();
        if (StrUtil.isNotEmpty(type)) {
            type = staffPo.getUserType();
        }
        if (StringUtils.isNotEmpty(auth) && (auth.equals(type) || auth.startsWith(type+",") || auth.indexOf(","+type+",")!=-1 || auth.endsWith(","+type))){
            return AjaxResult.success(dto);
        } else {
            return AjaxResult.error("权限不足");
        }
    }


    /**
     * 查询访客列表
     */
    @Override
    @GetMapping("/list")
    @RequiresPermissions(Auth.DM_SKILL_LIST)
    public AjaxResult list(DmSkillQuery dmSkillQuery) {
        return super.list(dmSkillQuery);
    }

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

    /**
     * 技能新增
     */
    @Override
    @PostMapping
    @RequiresPermissions(Auth.DM_SKILL_ADD)
    @Log(title = "技能管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated({V_A.class}) @RequestBody DmSkillDto dmVisitors) {
        return super.add(dmVisitors);
    }

    /**
     * 新增定制技能
     */
    @PostMapping(value = "/custom")
    @Log(title = "新增定制技能", businessType = BusinessType.INSERT)
    public AjaxResult addCustom( @RequestBody DmCustomMadeDto customMadeDto) {
        return toAjax(super.baseService.customInsert(customMadeDto));
    }

    /**
     * 访客修改
     */
    @Override
    @PutMapping
    @RequiresPermissions(Auth.DM_SKILL_EDIT)
    @Log(title = "技能管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated({V_E.class}) @RequestBody DmSkillDto dmVisitors) {
        return super.edit(dmVisitors);
    }

    /**
     * 技能批量删除
     */
    @Override
    @DeleteMapping("/batch/{idList}")
    @RequiresPermissions(Auth.DM_SKILL_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_SKILL_LIST = "skill:skills:list";
        /** 系统 - 技能管理 - 详情 */
        String DM_SKILL_SINGLE = "skill:skills:single";
        /** 系统 - 技能管理 - 新增 */
        String DM_SKILL_ADD = "skill:skills:add";
        /** 系统 - 技能管理 - 修改 */
        String DM_SKILL_EDIT = "skill:skills:edit";
        /** 系统 - 技能管理 - 删除 */
        String DM_SKILL_DEL = "skill:skills:delete";
    }
}
