package com.dcsoft.system.controller;

import com.alibaba.fastjson.JSONObject;
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.model.LoginUser;
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.apache.commons.lang3.StringUtils;
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.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 人员管理Controller
 *
 * @author nichun
 * @date 2023-03-08
 */
@RestController
@RequestMapping("/sysPeopleOther")
public class SysPeopleOtherController extends BaseController
{
    @Autowired
    private ISysPeopleOtherService sysPeopleOtherService;

    @Autowired
    protected ISysSdkService sdkService;

    @Autowired
    protected ISysPeopleEquipmentService peopleEquipmentService;

    @Autowired
    private ISysBranchService sysBranchService;

    @Autowired
    protected ISysEquipmentService equipmentService;

    @Autowired
    private ISysPeopleService sysPeopleService;

    /**
     * 查询人员管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysPeopleOther sysPeople)
    {
        List<SysPeopleOther> list = sysPeopleOtherService.selectSysPeopleOtherList(sysPeople);
        return getDataTable(list);
    }

    @GetMapping("/queryPeopleList")
    public AjaxResult queryPeopleList(SysPeopleOther sysPeople) {
        List<SysPeopleOther> list = sysPeopleOtherService.queryPeopleList(sysPeople);
        return success(list);
    }

    /**
     * 导出人员管理列表
     */
    @RequiresPermissions("system:sysPeopleOther:export")
    @Log(title = "人员管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPeopleOther sysPeople)
    {
        List<SysPeopleOther> list = sysPeopleOtherService.selectSysPeopleOtherLists(sysPeople);
        ExcelUtil<SysPeopleOther> util = new ExcelUtil<SysPeopleOther>(SysPeopleOther.class);
        util.exportExcel(response, list, "人员管理数据");
    }

    /**
     * 获取人员管理详细信息
     */
    @RequiresPermissions("system:sysPeopleOther:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysPeopleOtherService.selectSysPeopleOtherById(id));
    }

    /**
     * 新增人员管理
     */
    @RequiresPermissions("system:sysPeopleOther:add")
    @Log(title = "人员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysPeopleOther sysPeople) throws ExecutionException, InterruptedException {
        sysPeople.setGuid(IdUtils.simpleUUID());
        return toAjax(sysPeopleOtherService.insertSysPeopleOther(sysPeople));
    }


    /**
     * 修改人员管理
     */
    @RequiresPermissions("system:sysPeopleOther:edit")
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysPeopleOther sysPeople)
    {
        //照片未注册人员注册照片
        if(StringUtils.isNotEmpty(sysPeople.getAvatar())){
            if(StringUtils.isEmpty(sysPeople.getFaceGuid())){
                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();
                    Person person=new Person();
                    person.setName(sysPeople.getName());
                    person.setiDNumber(sysPeople.getIdcard());
                    person.setPhone(sysPeople.getPhone());
                    person.setId(sysPeople.getGuid());
                    String data=sdkService.personCreate(person,ip,pass);

                    //查看是否有底图，有底图就注册
                    SysPeopleOther sysPeopleOther = sysPeopleOtherService.selectSysPeopleOtherById(sysPeople.getId());
                    if(StringUtils.isNotEmpty(sysPeopleOther.getAvatar())){
                        sdkService.imageCreateUrl(sysPeople.getGuid(), sysPeopleOther.getAvatar(), ip, pass);
                    }

                    //人像是否注册
                    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);
                            //照片检测后删除注册设备人员
                            sdkService.personDelete(sysPeople.getGuid(),ip,pass);
                        }
                    }else{
                        //照片检测后删除注册设备人员
                        sdkService.personDelete(sysPeople.getGuid(),ip,pass);
                        return error(jsons.get("msg")+"");
                    }

                }
            }
        }
        return toAjax(sysPeopleOtherService.updateSysPeopleOther(sysPeople));
    }




    /**
     * 删除人员管理
     */
    @RequiresPermissions("system:sysPeopleOther:remove")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        SysEquipment equipment=new SysEquipment();
        equipment.setFlag("0");
        equipment.setIsCj("0");
        equipment.setProductId(3L);
        List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
        if(list.size()>0){
            for(Long id:ids){//下发到设备上
                SysPeopleOther people=sysPeopleOtherService.selectSysPeopleOtherById(id);
                for(SysEquipment e:list){
                    String ip=e.getIp();
                    String pass=e.getPassword();
                    sdkService.personDelete(people.getGuid(),ip,pass);
                    //保存下发记录
                    peopleEquipmentService.deleteSysPeopleEquipmentByOtherId(people.getId());
                }
            }
        }
        //暂未处理离线设备人员数据删除
        return toAjax(sysPeopleOtherService.deleteSysPeopleOtherByIds(ids));
    }


    @Log(title = "人员信息", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:sysPeopleOther:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysPeopleOther> util = new ExcelUtil<SysPeopleOther>(SysPeopleOther.class);
        List<SysPeopleOther> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = sysPeopleOtherService.importPeople(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<SysPeopleOther> util = new ExcelUtil<SysPeopleOther>(SysPeopleOther.class);
        util.importTemplateExcel(response, "第三方人员信息数据");
    }

    @GetMapping("/branchTree")
    public AjaxResult branchTree(SysBranch space)
    {
        //获取当前登录用户的所属部门
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysBranch parent =sysBranchService.selectSysBranchByDeptId(loginUser.getSysUser().getDept().getDeptId());
        space.setParentId(parent.getId());
        return success(sysBranchService.selectSysBranchList(space));
    }


    /**
     * 新增人员管理
     */
    @Log(title = "第三方人员管理", businessType = BusinessType.INSERT)
    @PostMapping("/addOther")
    public AjaxResult addOther(@RequestBody SysPeopleOther sysPeople) throws ExecutionException, InterruptedException {
        //注册设备进行注册
        if(org.apache.commons.lang3.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")+"");
                    }
                }
                //人像是否注册
                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{
                sysPeople.setGuid(IdUtils.simpleUUID());
            }
        }else{
            sysPeople.setGuid(IdUtils.simpleUUID());
        }

        return toAjax(sysPeopleOtherService.insertSysPeopleOther(sysPeople));
    }

    @GetMapping("/down/{ids}")
    public AjaxResult down(@PathVariable Long[] ids)
    {

        SysEquipment equipment=new SysEquipment();
        equipment.setFlag("0");
        equipment.setIsCj("0");
        equipment.setProductId(3L);
        List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
        if(list.size()>0){
            for(Long id:ids){//下发到设备上
                SysPeopleOther people=sysPeopleOtherService.selectSysPeopleOtherById(id);
                Long down=0L;
                try {
                    if(StringUtils.isNotEmpty(people.getGuid())){//人员
                        Person person=new Person();
                        person.setId(people.getGuid());
                        person.setName(people.getName());
                        person.setiDNumber(people.getIdcard());
                        person.setPhone(people.getPhone());

                        for(SysEquipment e:list){
                            String ip=e.getIp();
                            String pass=e.getPassword();
                            sdkService.personDelete(people.getGuid(),ip,pass);
                            sdkService.personCreate(person,ip,pass);
                            if(StringUtils.isNotEmpty(people.getFaceGuid())){//人脸
                                sdkService.imageCreateUrl(people.getGuid(),people.getFaceGuid(),people.getAvatar(), e.getIp(), e.getPassword());
                            }
                            down++;
                            //保存下发记录
                            SysPeopleEquipment sysPeopleEquipment=new SysPeopleEquipment();
                            sysPeopleEquipment.setOtherId(people.getId());
                            sysPeopleEquipment.setEquipmentId(e.getId());
                            sysPeopleEquipment.setGuid(people.getGuid());
                            sysPeopleEquipment.setFaceGuid(people.getFaceGuid());
                            peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                people.setDown(down);
                sysPeopleOtherService.updateSysPeopleOther(people);
            }
        }
        return toAjax(1);
    }

}
