package com.xueyi.system.device.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xueyi.common.cache.utils.SourceUtil;
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.datasource.annotation.Master;
import com.xueyi.common.log.annotation.Log;
import com.xueyi.common.log.enums.BusinessType;
import com.xueyi.common.security.annotation.RequiresPermissions;
import com.xueyi.common.web.annotation.TenantIgnore;
import com.xueyi.common.web.entity.controller.BaseController;
import com.xueyi.system.api.device.domain.dto.DmDeviceTenantMergeDto;
import com.xueyi.system.api.device.domain.po.DmDeviceTenantMergePo;
import com.xueyi.system.api.device.domain.vo.DeviceTenantSourceMergeVo;
import com.xueyi.system.api.digitalmans.domain.dto.DmManDeviceDto;
import com.xueyi.system.api.digitalmans.domain.po.DmManDevicePo;
import com.xueyi.system.api.model.Source;
import com.xueyi.system.api.organize.domain.dto.SysEnterpriseDto;
import com.xueyi.system.device.domain.query.DmDeviceTenantMergeQuery;
import com.xueyi.system.device.mapper.DmDeviceTenantMergeMapper;
import com.xueyi.system.device.service.IDmDeviceTenantMergeService;
import com.xueyi.system.device.service.impl.DmDeviceTenantMergeServiceImpl;
import com.xueyi.system.digitalmans.domain.query.DmManDeviceQuery;
import com.xueyi.system.digitalmans.service.IDmManDeviceService;
import com.xueyi.system.organize.service.ISysEnterpriseService;
import com.xueyi.tenant.api.source.domain.po.TeSourcePo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * 设备租户（企业）关联管理 业务处理
 *
 * @author xueyi
 */
@RestController
@RequestMapping("/device")
@Master
public class DmDeviceTenantMergeController extends BaseController<DmDeviceTenantMergeQuery, DmDeviceTenantMergeDto, IDmDeviceTenantMergeService> {

    @Autowired
    IDmManDeviceService dmManDeviceService;
    /** 定义节点名称 */
    @Override
    protected String getNodeName() {
        return "设备租户（企业）关联" ;
    }

    @Autowired
    private DmDeviceTenantMergeServiceImpl deviceTenantMergeService;

    @Autowired
    private DmDeviceTenantMergeMapper dmDeviceTenantMergeMapper;

    @Autowired
    ISysEnterpriseService enterpriseService;



    @GetMapping("/inner/selectMerge")
    @TenantIgnore(tenantLine = true)
    public R<DmDeviceTenantMergePo> selectTenant(String devId) {

        return R.ok(deviceTenantMergeService.selectByDevId(devId));
    }

    @GetMapping("/inner/selectSourceByTenantId")
    @TenantIgnore(tenantLine = true)
    public R<TeSourcePo> selectSourceByTenantId(@RequestParam(required = true) Long tenantId) {

        return R.ok(deviceTenantMergeService.selectSourceByTenantId(tenantId));
//        return null;
    }

    @GetMapping("/inner/selectSourceMerge")
    @TenantIgnore(tenantLine = true)
    public DeviceTenantSourceMergeVo selectSourceMerge(@RequestParam(required = true) String devId) {

//        DmDeviceTenantMergePo dmDeviceTenantMergePo = deviceTenantMergeService.selectByDevId(devId);

        DmManDevicePo dmManDevicePo = dmManDeviceService.getOne(devId);

        DeviceTenantSourceMergeVo vo = new DeviceTenantSourceMergeVo();

       if (null != dmManDevicePo &&  null!= dmManDevicePo.getTId()) {
           vo.setTenantId(dmManDevicePo.getTId());
           TeSourcePo teSourcePo = deviceTenantMergeService.selectSourceByTenantId(dmManDevicePo.getTId());
           vo.setSourceSlave("slave");
           if (null!= teSourcePo &&  StringUtils.isNotEmpty(teSourcePo.getSlave())) {
               vo.setSourceSlave(teSourcePo.getSlave());
           }
       }
       return vo;
    }

    @GetMapping("/inner/selectDevSNSourceMerge/{devId}/{devSN}")
    @TenantIgnore(tenantLine = true)
    R<DeviceTenantSourceMergeVo> selectDeviceSNTenantSourceMerge(@RequestParam(value = "devId") String devId,@RequestParam(value = "devSN") String devSN) {
        if (devSN != null && devSN !="") {
            // 判断是否是改租户绑定
            DmDeviceTenantMergePo dmDeviceTenantMergePo = deviceTenantMergeService.selectByDevSn(devSN);
            if (dmDeviceTenantMergePo == null) {
                return R.fail("激活码错误，请确认输入是否正确");
            }
            if (dmDeviceTenantMergePo.getDevId() == null || dmDeviceTenantMergePo.getDevId().equalsIgnoreCase("")) {
                DmDeviceTenantMergeDto dto = new DmDeviceTenantMergeDto();
                dto.setId(dmDeviceTenantMergePo.getId());
                dto.setDevSn(dmDeviceTenantMergePo.getDevSn());
                dto.setTenantId(dmDeviceTenantMergePo.getTenantId());
                // 绑定设备号
                dto.setDevId(devId);
                super.baseService.update(dto);
                DmManDeviceQuery query = new DmManDeviceQuery();
                query.setManCode(devSN);
                DmManDeviceDto dmManDeviceDto = new DmManDeviceDto();

                List<DmManDeviceDto> deviceDtos = dmManDeviceService.selectList(query);
                if (deviceDtos.size() > 0) {
                    DmManDeviceDto devDto = deviceDtos.get(0);
                    devDto.setDeviceId(devId);
                    dmManDeviceService.update(devDto);
                }
                SysEnterpriseDto enterpriseDto = enterpriseService.selectById(dmDeviceTenantMergePo.getTenantId());
                Source source = SourceUtil.getSourceCache(enterpriseDto.getStrategyId());
                TeSourcePo teSourcePo = new TeSourcePo();
                DeviceTenantSourceMergeVo vo = new DeviceTenantSourceMergeVo();
                vo.setTenantId(enterpriseDto.getId());
                vo.setSourceSlave(source.getMaster());
                return R.ok(vo);
            }
            return R.fail("激活码已被激活过，请更换激活码");
        }
        return R.fail("激活码为空，请输入激活码");
    }

    /**
     * 查询设备租户（企业）关联列表
     */
    @Override
    @GetMapping("/list")
    @RequiresPermissions(Auth.DM_DEVICE_TENANT_MERGE_LIST)
    public AjaxResult list(DmDeviceTenantMergeQuery dmDeviceTenantMerge) {
        return super.list(dmDeviceTenantMerge);
    }

    /**
     * 查询设备租户（企业）关联详细
     */
    @Override
    @GetMapping(value = "/{id}")
    @RequiresPermissions(Auth.DM_DEVICE_TENANT_MERGE_SINGLE)
    public AjaxResult getInfo(@PathVariable Serializable id) {
        return super.getInfo(id);
    }

    /**
     * 设备租户（企业）关联新增
     */
    @Override
    @PostMapping
    @RequiresPermissions(Auth.DM_DEVICE_TENANT_MERGE_ADD)
    @Log(title = "设备租户（企业）关联管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated({V_A.class}) @RequestBody DmDeviceTenantMergeDto dmDeviceTenantMerge) {
        return super.add(dmDeviceTenantMerge);
    }

    /**
     * 设备租户（企业）关联修改
     */
    @Override
    @PutMapping
    @RequiresPermissions(Auth.DM_DEVICE_TENANT_MERGE_EDIT)
    @Log(title = "设备租户（企业）关联管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated({V_E.class}) @RequestBody DmDeviceTenantMergeDto dmDeviceTenantMerge) {
        return super.edit(dmDeviceTenantMerge);
    }

    /**
     * 设备租户（企业）关联批量删除
     */
    @Override
    @DeleteMapping("/batch/{idList}")
    @RequiresPermissions(Auth.DM_DEVICE_TENANT_MERGE_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_DEVICE_TENANT_MERGE_LIST = "device:device:list";
        /** 系统 - 设备租户（企业）关联管理 - 详情 */
        String DM_DEVICE_TENANT_MERGE_SINGLE = "device:device:single";
        /** 系统 - 设备租户（企业）关联管理 - 新增 */
        String DM_DEVICE_TENANT_MERGE_ADD = "device:device:add";
        /** 系统 - 设备租户（企业）关联管理 - 修改 */
        String DM_DEVICE_TENANT_MERGE_EDIT = "device:device:edit";
        /** 系统 - 设备租户（企业）关联管理 - 删除 */
        String DM_DEVICE_TENANT_MERGE_DEL = "device:device:delete";
    }
}
