package com.dcsoft.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.Constants;
import com.dcsoft.common.core.enums.exception.CommonExceptionEnum;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.system.domain.SysEquipment;
import com.dcsoft.system.domain.SysPeopleEquipment;
import com.dcsoft.system.service.*;
import com.dcsoft.system.uniubi.service.ISysApiService;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.system.domain.SysEmpowerRecord;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.utils.poi.ExcelUtil;
import com.dcsoft.common.core.web.page.TableDataInfo;

/**
 * 授权记录Controller
 *
 * @author nichun
 * @date 2023-03-08
 */
@Slf4j
@RestController
@RequestMapping("/empowerRecord")
public class SysEmpowerRecordController extends BaseController
{
    @Autowired
    private ISysEmpowerRecordService sysEmpowerRecordService;

    @Autowired
    private ISysApiService sysApiService;

    @Autowired
    private ISysEquipmentService equipmentService;

    @Autowired
    private ISysRuleService ruleService;

    @Autowired
    private ISysPeopleService peopleService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysSdkService sdkService;

    @Autowired
    private ISysPeopleEquipmentService peopleEquipmentService;

    @Autowired
    private ISysPeopleService sysPeopleService;

    /**
     * 卡权限删除接口
     */
    public static final String delete = "/cardinfo/delete";

    /**
     * 查询授权记录列表
     */
    @RequiresPermissions("system:empowerRecord:list")
    @GetMapping("/list")
    public TableDataInfo list(SysEmpowerRecord sysEmpowerRecord)
    {
        startPage();
        List<SysEmpowerRecord> list = sysEmpowerRecordService.selectSysEmpowerRecordList(sysEmpowerRecord);
        return getDataTable(list);
    }

    /**
     * 导出授权记录列表
     */
    @RequiresPermissions("system:empowerRecord:export")
    @Log(title = "授权记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysEmpowerRecord sysEmpowerRecord)
    {
        List<SysEmpowerRecord> list = sysEmpowerRecordService.selectSysEmpowerRecordList(sysEmpowerRecord);
        ExcelUtil<SysEmpowerRecord> util = new ExcelUtil<SysEmpowerRecord>(SysEmpowerRecord.class);
        util.exportExcel(response, list, "授权记录数据");
    }

    /**
     * 获取授权记录详细信息
     */
    @RequiresPermissions("system:empowerRecord:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysEmpowerRecordService.selectSysEmpowerRecordById(id));
    }

    /**
     * 新增授权记录
     */
    @RequiresPermissions("system:empowerRecord:add")
    @Log(title = "授权记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysEmpowerRecord sysEmpowerRecord)
    {
        return toAjax(sysEmpowerRecordService.insertSysEmpowerRecord(sysEmpowerRecord));
    }

    /**
     * 修改授权记录
     */
    @RequiresPermissions("system:empowerRecord:edit")
    @Log(title = "授权记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysEmpowerRecord sysEmpowerRecord)
    {
        return toAjax(sysEmpowerRecordService.updateSysEmpowerRecord(sysEmpowerRecord));
    }

    /**
     * 删除授权记录
     */
    @RequiresPermissions("system:empowerRecord:remove")
    @Log(title = "授权记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        if("true".equals(cloud)){
            for(Long id:ids){
                SysEmpowerRecord record=sysEmpowerRecordService.selectSysEmpowerRecordById(id);
                String data=sysApiService.authDeviceRevoke(equipmentService.selectSysEquipmentById(record.getEquipmentId()),peopleService.selectSysPeopleById(record.getPeopleId()));
                JSONObject json= JSONObject.parseObject(data);
                if(!"1".equals(json.get("result")+"")){
                    return error(json.get("msg")+"");
                }
            }
        }else{
            for(Long id:ids){
                SysEmpowerRecord record=sysEmpowerRecordService.selectSysEmpowerRecordById(id);
                SysEquipment equipment=equipmentService.selectSysEquipmentById(record.getEquipmentId());
                List<SysPeopleEquipment> peopleEquipmentList = peopleEquipmentService.selectSysPeopleEquipmentByPeopleId(record.getPeopleId());
                for(SysPeopleEquipment peopleEquipment:peopleEquipmentList){
                    sdkService.personDelete(peopleEquipment.getGuid(), equipment.getIp(), equipment.getPassword());
                }

                if(5L == equipment.getProductId()){
                    String doorNo = sysPeopleService.selectDoorNo(id);
                    SysEquipment sysEquipment = new SysEquipment();
                    sysEquipment.setIp(equipment.getIp());
                    sysEquipment.setPassword(equipment.getPassword());
                    sysEquipment.setDoorNo(StringUtils.isEmpty(doorNo) ? "1" : doorNo);
                    deleteLadder(sysEquipment);
                }
            }
        }
        return toAjax(sysEmpowerRecordService.deleteSysEmpowerRecordByIds(ids));
    }

    private void deleteLadder(SysEquipment sysEquipment) {
        log.info("梯控删除:" + sysEquipment);
        log.info("梯控删除地址:" + "http://" + sysEquipment.getIp() + ":8090" +  delete);
        Map<String, Object> map = new HashMap<>();
        map.put("idcardnum", sysEquipment.getDoorNo());
        map.put("pass", sysEquipment.getPassword());
        String body = HttpUtil.createPost("http://" + sysEquipment.getIp() + ":8090" +  delete).timeout(5000).body(JSON.toJSONString(map)).execute().body();
        log.info("梯控删除卡号接口返回:" + body);
        JSONObject object = JSONObject.parseObject(body);
        if(!Constants.CODE.equals(object.get("msg"))) {
            log.error("梯控删除卡号接口异常码:" + object.get("msg").toString());
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "梯控删除卡号接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage());
        }
    }

    /**
     * 查询授权管理记录详细
     */
    @GetMapping(value = "forbidRecordApi/{ids}/{type}")
    public AjaxResult forbidRecordApi(@PathVariable List<Long> ids, @PathVariable("type") String type) {
        Boolean flag=false;
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        if("true".equals(cloud)) {
            for (Long id : ids) {
                flag = true;
                SysEmpowerRecord record = sysEmpowerRecordService.selectSysEmpowerRecordById(id);
                record.setStatus(type);
                if ("1".equals(type)) {//禁用
                    String data = sysApiService.authDeviceRevoke(equipmentService.selectSysEquipmentById(record.getEquipmentId()), peopleService.selectSysPeopleById(record.getPeopleId()));
                    JSONObject json = JSONObject.parseObject(data);
                    if (!"1".equals(json.get("result") + "")) {
                        return error(json.get("msg") + "");
                    }
                } else {
                    String data = sysApiService.authDevice(ruleService.selectSysRuleById(record.getRuleId()), peopleService.selectSysPeopleById(record.getPeopleId()), equipmentService.selectSysEquipmentById(record.getEquipmentId()));
                    JSONObject json = JSONObject.parseObject(data);
                    if (!"1".equals(json.get("result") + "")) {
                        return error(json.get("msg") + "");
                    }
                }
                sysEmpowerRecordService.updateSysEmpowerRecord(record);
            }
        }else{
            for (Long id : ids) {
                flag = true;
                SysEmpowerRecord record = sysEmpowerRecordService.selectSysEmpowerRecordById(id);
                record.setStatus(type);
                if ("1".equals(type)) {//禁用
                    SysEquipment equipment=equipmentService.selectSysEquipmentById(record.getEquipmentId());
                    List<SysPeopleEquipment>  peopleEquipmentList= peopleEquipmentService.selectSysPeopleEquipmentByPeopleId(record.getPeopleId());
                    for(SysPeopleEquipment peopleEquipment:peopleEquipmentList){
                        sdkService.personDelete(peopleEquipment.getGuid(), equipment.getIp(), equipment.getPassword());
                    }
                } else {
                    String data = sdkService.authDevice(ruleService.selectSysRuleById(record.getRuleId()), peopleService.selectSysPeopleById(record.getPeopleId()), equipmentService.selectSysEquipmentById(record.getEquipmentId()));
                    JSONObject json = JSONObject.parseObject(data);
                    if (!"1".equals(json.get("result") + "")) {
                        return error(json.get("msg") + "");
                    }
                }
                sysEmpowerRecordService.updateSysEmpowerRecord(record);
            }
        }
        return  flag ? AjaxResult.success() : AjaxResult.error();
    }

}
