package com.zcloud.controller.electronicFence;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.service.corp.CorpInfoService;
import com.zcloud.service.system.OfficeService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 说明：工种管理
 * 作者：wangxuan
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/deployOffice")
public class DeployOfficeController extends BaseController {


    @Resource
    private UsersService usersService;
    @Autowired
    private CorpInfoService corpInfoService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private InitPageDataUtil initPageDataUtil;

    /**
     * @Description: 列表
     * @Author: dearLin
     * @Date: 2024/1/30/030 9:38
     * @Param: [com.zcloud.entity.Page] [page]
     * @Return: java.lang.Object
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Page page) throws Exception {
        PageData pd = this.getPageData();
        String KEYWORDS = pd.getString("str");  // 关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) pd.put("str", KEYWORDS.trim());
        page.setPd(pd);
        PageData pageData = this.getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        List<PageData> dataList = officeService.listAll(pageData);
        return ReturnMap.ok().put("varList",dataList);
//        PageData data = corpInfoService.findById(pageData);
//        try {
//            if ("1".equals(data.getString("PERSONNEL_POSITION"))) {
//                List<PageData> dataList = officeService.listAll(pageData);
//                returnMap.put("varList", dataList);
//                returnMap.put("page", page);
//                return returnMap;
//            }
//
//            // 否则执行远程调用
//            JSONObject body = PLSUtil.GeneralList("/deploy/office/list", pageData);
//            if (body != null) {
//                List<JSONObject> list = body.getJSONArray("rows").toJavaList(JSONObject.class);
//                returnMap.put("varList", list);
//                page.setTotalResult(body.getIntValue("total"));
//                returnMap.put("page", page);
//            } else {
//                // 远程调用失败时执行的逻辑
//                returnMap.put("webSiteStatus", "1");
//                returnMap.put("varList", new ArrayList<>());
//                returnMap.put("page", page);
//            }
//        } catch (Exception e) {
//            // 捕获远程调用异常，执行现有逻辑
//            returnMap.put("webSiteStatus", "1");
//            returnMap.put("varList", new ArrayList<>());
//            returnMap.put("page", page);
//        }
//
//        return returnMap;
    }

    /**
     * @Description: 新增
     * @Author: dearLin
     * @Date: 2024/3/4/004 10:43
     * @Param: [] []
     * @Return: java.lang.Object
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Object save() throws Exception {
        PageData pageData = this.getPageData();
        ReturnMap returnMap = new ReturnMap();

        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        // 获取 corpInfo 信息
        PageData data = corpInfoService.findById(pageData);
        if ("1".equals(data.getString("PERSONNEL_POSITION"))) {
            PageData pd = new PageData();
            initPageDataUtil.initSave(pd);
            pd.put("THUMBNAIL", pageData.getString("thumbnail"));
            pd.put("REMARK", pageData.getString("remark"));
            pd.put("STATUS", pageData.getString("status"));
            pd.put("WORK_NAME", pageData.getString("officeName"));
            pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
            officeService.save(pd);
            return ReturnMap.ok();
        }

        try {
            JSONObject body = PLSUtil.GeneralPost("/deploy/office", pageData, Jurisdiction.getCORPINFO_ID());
            if (body != null && "200".equals(body.getString("code"))) {
                try {
                    PageData pageDataForList = new PageData();
                    pageDataForList.put("pageNum", "1");
                    // 当前页，可以根据需要设置
                    pageDataForList.put("pageSize", "100");
                    // 每页大小，可以根据需要调整
                    pageDataForList.put("status", "0");
                    // 只获取正常状态的工种

                    // 调用获取工种列表的接口
                    JSONObject officeListResponse = PLSUtil.GeneralList("/deploy/office/list", pageDataForList);

                    // 处理返回的工种列表数据
                    if (officeListResponse != null && "200".equals(officeListResponse.getString("code"))) {
                        JSONArray officeList = officeListResponse.getJSONArray("rows");
                        Long poid = null;
                        for (int i = 0; i < officeList.size(); i++) {
                            JSONObject office = officeList.getJSONObject(i);
                            String WORK_NAME = office.getString("WORK_NAME");
                            if (WORK_NAME != null && !WORK_NAME.isEmpty() && WORK_NAME.equals(pageData.getString("WORK_NAME"))) {
                                poid = office.getLong("id");
                                break;
                            }
                        }
                        if (poid != null) {
                            PageData pd = new PageData();
                            pd.put("WORK_ID", poid);    //主键
                            pd.put("CREATTIME", new Date());
                            pd.put("ISDELETE", "0");
                            pd.put("THUMBNAIL", pageData.getString("thumbnail"));
                            pd.put("REMARK", pageData.getString("remark"));
                            pd.put("STATUS", pageData.getString("status"));
                            pd.put("WORK_NAME", pageData.getString("WORK_NAME"));
                            initPageDataUtil.initSave(pd);
                            pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                            officeService.save(pd);
                            return ReturnMap.ok();
                        }
                        return ReturnMap.error("未找到匹配的工种信息");
                    }
                } catch (Exception e) {
                    returnMap.put("webSiteStatus", "1");
                }
                returnMap.putAll(body);
            } else {
                // 远程调用失败
                returnMap.put("webSiteStatus", "1");
            }
        } catch (Exception e) {
            returnMap.put("webSiteStatus", "1");
            return returnMap;
        }
        return returnMap;
    }


    /**
     * @Description: 修改
     * @Author: dearLin
     * @Date: 2024/3/4/004 10:43
     * @Param: [] []
     * @Return: java.lang.Object
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Object edit() throws Exception {
        PageData pageData = this.getPageData();
        ReturnMap returnMap = new ReturnMap();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        // 获取企业信息
        PageData data = corpInfoService.findById(pageData);
        if ("0".equals(data.getString("PERSONNEL_POSITION"))) {
            try {
                JSONObject body = PLSUtil.GeneralPut("/deploy/office", pageData, Jurisdiction.getCORPINFO_ID());
                if (body == null || !"200".equals(body.getString("code"))) {
                    return ReturnMap.ok().put("webSiteStatus", "1");
                }
            } catch (Exception e) {
                return ReturnMap.ok().put("webSiteStatus", "1");
            }
        }
        initPageDataUtil.initEdit(pageData);
        officeService.edit(pageData);
        // 修改单位里所有用户得工种名字
        usersService.editUserWorkName(pageData);
        return returnMap;
    }


    /**
     * @Description: 删除
     * @Author: dearLin
     * @Date: 2024/3/4/004 10:43
     * @Param: [] []
     * @Return: java.lang.Object
     */
    @RequestMapping(value = "/remove")
    @ResponseBody
    public Object remove() throws Exception {
        PageData pageData = this.getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        PageData data = corpInfoService.findById(pageData);
        ReturnMap returnMap = new ReturnMap();
        String[] split = pageData.getString("DATA_IDS").split(",");
        PageData query = new PageData();
        query.put("CORPINFO_ID",Jurisdiction.getCORPINFO_ID());
        query.put("DATA_IDS",split);
        int count = usersService.hasUserUseWord(query);
        if (count != 0) return ReturnMap.error("该工种有用户正在使用！请修改后进行删除。");
        if ("1".equals(data.getString("PERSONNEL_POSITION"))) {
            officeService.deleteAll(query);
            return ReturnMap.ok();
        }
        try {
            JSONObject body = PLSUtil.GeneralDelete("/deploy/office/", pageData.get("DATA_IDS"), Jurisdiction.getCORPINFO_ID());
            if (body != null) {
                if (!"200".equals(body.getString("code"))) {
                    return ReturnMap.error(body.getString("msg"));
                }
                pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                pageData.put("list", pageData.getString("DATA_IDS").split(","));
                usersService.removeUserWorkName(pageData);
                returnMap.putAll(body);
            } else {
                returnMap.put("webSiteStatus", "1");
            }
        } catch (Exception e) {
            returnMap.put("webSiteStatus", "1");
            return returnMap;
        }
        return returnMap;
    }


    /**
     * @Description: 详情
     * @Author: dearLin
     * @Date: 2024/3/4/004 10:43
     * @Param: [] []
     * @Return: java.lang.Object
     */
    @RequestMapping(value = "/goEdit")
    @ResponseBody
    public Object goEdit() throws Exception {
        PageData pageData = this.getPageData();
        ReturnMap returnMap = new ReturnMap();
        JSONObject body = PLSUtil.GeneralGetById("/deploy/office/", pageData.get("id"), Jurisdiction.getCORPINFO_ID());
        if (body != null) {
            returnMap.putAll(body);
        }
        return returnMap;
    }
}

