package com.dcsoft.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.core.utils.poi.ExcelUtil;
import com.dcsoft.common.core.utils.uuid.IdUtils;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.web.page.TableDataInfo;
import com.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.service.*;
import com.dcsoft.system.uniubi.domain.Person;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 离职管理Controller
 *
 * @author nichun
 * @date 2023-09-09
 */
@RestController
@RequestMapping("/peopleLeave")
public class SysPeopleLeaveController extends BaseController
{
    @Autowired
    private ISysPeopleLeaveService sysPeopleLeaveService;

    @Autowired
    private ISysPeopleService sysPeoplService;

    @Autowired
    protected ISysSdkService sdkService;

    @Autowired
    private ISysEquipmentService equipmentService;

    @Autowired
    private ISysEmpowerRecordService empowerRecordService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysBranchService sysBranchService;

    @Autowired
    private ISysRuleService sysRuleService;


    /**
     * 查询离职管理列表
     */
    @RequiresPermissions("system:peopleLeave:list")
    @GetMapping("/list")
    public TableDataInfo list(SysPeopleLeave sysPeopleLeave)
    {
        startPage();
        List<SysPeopleLeave> list = sysPeopleLeaveService.selectSysPeopleLeaveList(sysPeopleLeave);
        return getDataTable(list);
    }

    /**
     * 查询人员
     * @param sysPeopleLeave
     * @return
     */
    @GetMapping("/queryPeopleList")
    public AjaxResult queryPeopleList(SysPeopleLeave sysPeopleLeave) {
        List<SysPeopleLeave> list = sysPeopleLeaveService.selectSysPeopleLeaveList(sysPeopleLeave);
        return success(list);
    }

    /**
     * 导出离职管理列表
     */
    @RequiresPermissions("system:peopleLeave:export")
    @Log(title = "离职管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPeopleLeave sysPeopleLeave)
    {
        List<SysPeopleLeave> list = sysPeopleLeaveService.selectSysPeopleLeaveList(sysPeopleLeave);
        ExcelUtil<SysPeopleLeave> util = new ExcelUtil<SysPeopleLeave>(SysPeopleLeave.class);
        util.exportExcel(response, list, "离职管理数据");
    }

    /**
     * 获取离职管理详细信息
     */
    @RequiresPermissions("system:peopleLeave:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysPeopleLeaveService.selectSysPeopleLeaveById(id));
    }

    /**
     * 新增离职管理
     */
    @RequiresPermissions("system:peopleLeave:add")
    @Log(title = "离职管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysPeopleLeave sysPeopleLeave)
    {
        if ("1".equals(sysPeopleLeave.getStatus())){
            if(sysPeopleLeave.getPeopleId()!=null){
                sysPeoplService.deleteSysPeopleById(sysPeopleLeave.getPeopleId());
                //删除设备人员
                SysPeople people = sysPeoplService.selectSysPeopleById(sysPeopleLeave.getPeopleId());
                if(StringUtils.isNotEmpty(people.getGuid())){
                    SysEquipment equipment=new SysEquipment();
                    equipment.setFlag("0");
                    List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
                    for(SysEquipment e:list){
                        sdkService.personDelete(people.getGuid(),e.getIp(),e.getPassword());
                    }
                }
            }
        }
        return toAjax(sysPeopleLeaveService.insertSysPeopleLeave(sysPeopleLeave));
    }

    /**
     * 修改离职管理
     */
    @RequiresPermissions("system:peopleLeave:edit")
    @Log(title = "离职管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysPeopleLeave sysPeopleLeave)
    {
        if ("1".equals(sysPeopleLeave.getStatus())){
            if(sysPeopleLeave.getPeopleId()!=null){
                sysPeoplService.deleteSysPeopleById(sysPeopleLeave.getPeopleId());
                //删除设备人员
                SysPeople people = sysPeoplService.selectSysPeopleById(sysPeopleLeave.getPeopleId());
                if(StringUtils.isNotEmpty(people.getGuid())){
                    SysEquipment equipment=new SysEquipment();
                    equipment.setFlag("0");
                    List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
                    for(SysEquipment e:list){
                        sdkService.personDelete(people.getGuid(),e.getIp(),e.getPassword());
                    }
                }
            }
        }
        return toAjax(sysPeopleLeaveService.updateSysPeopleLeave(sysPeopleLeave));
    }

    /**
     * 删除离职管理
     */
    @RequiresPermissions("system:peopleLeave:remove")
    @Log(title = "离职管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysPeopleLeaveService.deleteSysPeopleLeaveByIds(ids));
    }

    @PostMapping("/peopleLeave")
    public void peopleLeave()
    {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        SysPeopleLeave   sysPeopleLeave=new SysPeopleLeave();
        sysPeopleLeave.setType("0");
        sysPeopleLeave.setStatus("0");
        List<SysPeopleLeave> leaveList=sysPeopleLeaveService.selectSysPeopleLeaveList(sysPeopleLeave);
        for(SysPeopleLeave peopleLeave:leaveList){
            if(peopleLeave.getPeopleId()!=null){
                sysPeoplService.deleteSysPeopleById(peopleLeave.getPeopleId());
                //删除设备人员
                SysPeople people = sysPeoplService.selectSysPeopleById(peopleLeave.getPeopleId());
                empowerRecordService.deleteSysEmpowerRecordByPeopleId(people.getId());
                if(StringUtils.isNotEmpty(people.getGuid())){
                    SysEquipment equipment=new SysEquipment();
                    equipment.setFlag("0");
                    List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
                    for(SysEquipment e:list){
                        sdkService.personDelete(people.getGuid(),e.getIp(),e.getPassword());
                    }
                }
            }
            peopleLeave.setStatus("1");
            sysPeopleLeaveService.updateSysPeopleLeave(peopleLeave);
        }
    }

    /**
     * 恢复人员
     *
     * @return
     */
    @PostMapping("/recoveryPeople")
    public AjaxResult recoveryPeople(String id) {
        SysPeople sysPeople = sysPeoplService.selectSysPeopleByUserId(Long.valueOf(id));
        //注册设备进行注册
        if(StringUtils.isNotEmpty(sysPeople.getAvatar())) {//是否上传头像，检测照片是否合格
            SysEquipment equipment=new SysEquipment();
            equipment.setIsCj("1");
            equipment.setFlag("0");
            List<SysEquipment> list=equipmentService.selectSysEquipmentList(equipment);
            if(list.size()>0){
                //人员是否注册
                String ip=list.get(0).getIp();
                String pass=list.get(0).getPassword();
                if(org.apache.commons.lang3.StringUtils.isEmpty(sysPeople.getGuid())){
                    Person person=new Person();
                    person.setName(sysPeople.getName());
                    person.setiDNumber(sysPeople.getIdcard());
                    person.setPhone(sysPeople.getPhone());
                    String data=sdkService.personCreate(person,ip,pass);
                    JSONObject json= JSONObject.parseObject(data);
                    if("1".equals(json.get("result")+"")) {
                        JSONObject obj= (JSONObject) json.get("data");
                        String admitGuid=obj.get("id")+"";
                        sysPeople.setGuid(admitGuid);
                    }else{
                        return error(json.get("msg")+"");
                    }
                }else{//更新人员信息
                    sdkService.personDelete(sysPeople.getGuid(),ip,pass);
                    Person person=new Person();
                    person.setId(sysPeople.getGuid());
                    person.setName(sysPeople.getName());
                    person.setiDNumber(sysPeople.getIdcard());
                    person.setPhone(sysPeople.getPhone());
                    String data=sdkService.personCreate(person,ip,pass);
                    JSONObject json= JSONObject.parseObject(data);
                    if("1".equals(json.get("result")+"")) {
                    }else{
                        return error(json.get("msg")+"");
                    }
                }
                //人像是否注册
                String datas = sdkService.imageCreateUrl(sysPeople.getGuid(), sysPeople.getAvatar(), ip, pass);
                JSONObject jsons = JSONObject.parseObject(datas);
                if ("1".equals(jsons.get("result")+"")) {
                    if(jsons.get("data")!=null){
                        String faceGuid = jsons.get("data")+"";
                        sysPeople.setFaceGuid(faceGuid);
                    }
                }else{
                    return error(jsons.get("msg")+"");
                }
                //照片检测后删除注册设备人员
                sdkService.personDelete(sysPeople.getGuid(),ip,pass);
            }else{
                Long userId= SecurityUtils.getUserId();
                SysUser user=userService.selectUserById(userId);
                if(user.getEquipmentId()!=null){
                    SysEquipment equipments = equipmentService.selectSysEquipmentById(user.getEquipmentId());
                    String ip = equipments.getIp();
                    String pass = equipments.getPassword();
                    String flag = equipments.getFlag();
                    if("0".equals(flag)){
                        Person person=new Person();
                        person.setName(sysPeople.getName());
                        person.setiDNumber(sysPeople.getIdcard());
                        person.setPhone(sysPeople.getPhone());
                        String data=sdkService.personCreate(person,ip,pass);
                        JSONObject json= JSONObject.parseObject(data);
                        if("1".equals(json.get("result")+"")) {
                            JSONObject obj= (JSONObject) json.get("data");
                            String admitGuid=obj.get("id")+"";
                            sysPeople.setGuid(admitGuid);
                        }else{
                            return error(json.get("msg")+"");
                        }
                        String datas = sdkService.imageCreateUrl(sysPeople.getGuid(), sysPeople.getAvatar(), ip, pass);
                        JSONObject jsons = JSONObject.parseObject(datas);
                        if ("1".equals(jsons.get("result")+"")) {
                            if(jsons.get("data")!=null){
                                String faceGuid = jsons.get("data")+"";
                                sysPeople.setFaceGuid(faceGuid);
                            }
                        }else{
                            return error(jsons.get("msg")+"");
                        }
                        //照片检测后删除注册设备人员
                        sdkService.personDelete(sysPeople.getGuid(),ip,pass);
                    }else {
                        return error("默认设备设备已离线");
                    }
                }
            }
        }else{
            sysPeople.setGuid(IdUtils.simpleUUID());
        }

        //下发设备
        if(sysPeople.getBranchId()!=null){
            SysBranch branch=sysBranchService.selectSysBranchById(sysPeople.getBranchId());
            if (branch.getRuleId()!= null) {
                //添加人员授权信息
                SysRule rule=sysRuleService.selectSysRuleById(branch.getRuleId());
                String data=sdkService.authDeviceNew(rule,sysPeople);
                if("".equals(data)){
                    return AjaxResult.error("该规则未绑定设备!");
                }
                sysPeople.setDown(1L);
            }
        }
        sysPeople.setDelFlag(0L);
        int i = sysPeoplService.updateSysPeople(sysPeople);
        return toAjax(i);
    }


    @Log(title = "离职人员", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysPeopleLeave> util = new ExcelUtil<>(SysPeopleLeave.class);
        List<SysPeopleLeave> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = sysPeopleLeaveService.importPeople(userList, updateSupport, operName);
        return success(message);
    }

}
