package com.cftech.base.org.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.base.org.api.QyOrgUtil;
import com.cftech.base.org.model.OrgUnit;
import com.cftech.base.org.model.Orgtype;
import com.cftech.base.org.model.Qyuser;
import com.cftech.base.org.model.vo.OrgUnitVO;
import com.cftech.base.org.service.OrgUnitService;
import com.cftech.base.org.service.OrgtypeService;
import com.cftech.base.org.service.QyuserService;
import com.cftech.core.poi.ExcelKit;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.SystemConfig;
import com.cftech.sys.model.User;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/a/orgunit")
public class OrgUnitController {

    @Autowired
    private OrgUnitService orgUnitService;
    @Autowired
    private QyuserService qyuserService;
    @Autowired
    private OrgtypeService orgtypeService;
    @Autowired
    private QyOrgUtil qyOrgUtil;
    @Autowired
    private CodingruleUtils codingruleUtils;

    private final static String rootOrgName = SystemConfig.p.getProperty("ROOT_ORG_NAME");

    private final static String qyAccounts = SystemConfig.p.getProperty("AIDEA_QY_ACCOUNTS");

    //返回列表页面
    @RequiresPermissions(value = PermissionSign.ORGUNIT_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
    public String list(HttpServletRequest request, Model model) {
        model.addAttribute("accountId", qyAccounts);
        return "managerorgunit/orgunitlist";
    }

    //返回编辑页面（新增、修改）
    @RequiresPermissions(value = PermissionSign.ORGUNIT_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.GET,RequestMethod.POST})
    public String form(HttpServletRequest request, String id, Model model) {
        Long accountsId = Long.parseLong(qyAccounts);
        Sort sort = new Sort("number", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("del_flag", 0);


        if (!StringUtils.isEmpty(id)) {

            OrgUnit orgUnit = orgUnitService.fetchById(id);
            String parentOrgName = "";
            if (orgUnit.getParentId() == 0) {
                parentOrgName = rootOrgName;
            } else {
                OrgUnit parentOrgUnit = orgUnitService.fetchById(orgUnit.getParentId());
                parentOrgName = parentOrgUnit.getOrgName();
            }
            if (orgUnit.getOrgtypeId() != null) {
                Orgtype orgtype = orgtypeService.fetchById(orgUnit.getOrgtypeId());
                model.addAttribute("orgtypeName", orgtype.getName());
            }
            model.addAttribute("data", orgUnit);
            model.addAttribute("parentName", parentOrgName);
            model.addAttribute("accountId", orgUnit.getAccountsId());
            conds.equal("accounts_id", orgUnit.getAccountsId());
        } else {
            model.addAttribute("accountId", accountsId);
            conds.equal("accounts_id", accountsId);
        }
        List<Orgtype> orgtypes = orgtypeService.fetchSearchByPage(conds, sort, 0, 0);

        model.addAttribute("orgtypes", orgtypes);
        return "managerorgunit/orgunitadd";
    }

    //提交编辑页面（新增、修改）
    @RequiresPermissions(value = PermissionSign.ORGUNIT_EDIT)
    @RequestMapping(value = "/formData")
    @ResponseBody
    public JSONObject formData(OrgUnit orgUnit, Model model, HttpServletRequest request) {
        Long accountsId = Long.parseLong(qyAccounts);
        JSONObject rtnJson = new JSONObject();
        try {
            if (orgUnit != null && orgUnit.getId() != null) {
                //do update
                orgUnit.setUpdateBy(UserUtils.getUser().getId());
                OrgUnit parentOrgUnit = null;

                if (orgUnit.getParentId() != 0) {
                    parentOrgUnit = orgUnitService.fetchById(orgUnit.getParentId());
                    orgUnit.setParentIds(parentOrgUnit.getParentIds() + orgUnit.getId() + ",");
                } else {
                    orgUnit.setParentId(1L);
                    orgUnit.setParentIds("0,1," + orgUnit.getId() + ",");
                }

                //同步至企业号
                if (!StringUtils.isEmpty(orgUnit.getWxorgId())) {
                    boolean flag = qyOrgUtil.move(orgUnit, parentOrgUnit);
                    if (!flag) {
                        log.error("同步微信端出错," + orgUnit.toString());
                        rtnJson.put("errorNo", 2);
                        return rtnJson;
                    }
                } else {
                    if (!qyOrgUtil.update(orgUnit)) {
                        log.error("同步微信端出错," + orgUnit.toString());
                    }
                }

                orgUnitService.updateCache(orgUnit);
                rtnJson.put("errorNo", 0);
            } else {
                orgUnit.setAccountsId(accountsId);
                orgUnit.setNumber(codingruleUtils.getNumber(accountsId, OrgUnit.class.getName()));
                // do create
                OrgUnit parentOrgUnit = null;
                if (!StringUtils.isEmpty(orgUnit.getParentId())) {
                    parentOrgUnit = orgUnitService.fetchById(orgUnit.getParentId());
                } else {
                    orgUnit.setParentId(1L);
                }

                orgUnit.setDelFlag(false);
                orgUnit.setStatus("0");
                orgUnit.setParentIds(parentOrgUnit == null ? "0,1," : parentOrgUnit.getParentIds());
                orgUnit.setCreateBy(UserUtils.getUser().getId());
                orgUnit.setUpdateBy(UserUtils.getUser().getId());
                orgUnitService.saveCache(orgUnit);

                int wxorgid = qyOrgUtil.create(orgUnit, parentOrgUnit);
                if (wxorgid == -1 || wxorgid == 0) {
                    rtnJson.put("errorNo", 1);
                    throw new Exception("同步微信端出错");
                } else {
                    orgUnit.setWxorgId("" + wxorgid);
                }

                orgUnit.setParentIds(orgUnit.getParentIds() + orgUnit.getId() + ",");
                orgUnitService.updateCache(orgUnit);


                rtnJson.put("errorNo", 0);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = PermissionSign.ORGUNIT_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, OrgUnit orgUnit, HttpServletRequest request) {
        Long accountsId = Long.parseLong(qyAccounts);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if(!StringUtils.isEmpty(orgUnit.getNumber())){
        	conds.equal("t.number", orgUnit.getNumber());
        }  
        if (!StringUtils.isEmpty(orgUnit.getOrgName())) {
            conds.like("t.org_name", orgUnit.getOrgName());
        }
        Long orgId = null;
        if (orgUnit.getId() != null) {
            orgId = orgUnit.getId();
        } else {
            //用户
            User user = UserUtils.getUser();
            Qyuser qyuser = qyuserService.fetchById(user.getUserid());
            orgId = qyuser.getOrgId();
        }


        Sort sort = new Sort("t.create_time", OrderType.DESC);
        List<OrgUnitVO> list = orgUnitService.fetchSearchVOByPage(orgId, conds, sort, iDisplayStart, iDisplayLength);

        Conds myCond = new Conds();
        myCond.equal("del_flag", Constants.DEL_FLAG_0);
        myCond.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(orgUnit.getOrgName())) {
            myCond.like("org_name", orgUnit.getOrgName());
        }
//        if (!StringUtils.isEmpty(orgUnit.getIsAdminUnit())) {
//            myCond.equal("isadminunit", orgUnit.getIsAdminUnit());
//        }
//        if (!StringUtils.isEmpty(orgUnit.getIsSalesUnit())) {
//            myCond.equal("issalesunit", orgUnit.getIsSalesUnit());
//        }

        Integer counts = orgUnitService.count(orgId, myCond);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = PermissionSign.ORGUNIT_EDIT)
    @RequestMapping(value = "/delete",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            OrgUnit orgUnit = orgUnitService.fetchById(id);
            boolean flag = qyOrgUtil.delete(orgUnit);
            if (flag) {
                orgUnitService.delete(id);
                rtnJosn.put("errorNo", 0);
            } else {
                rtnJosn.put("errorNo", 1);
            }
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    @RequestMapping(value = "/exportExcel",method = {RequestMethod.GET,RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.ORGUNIT_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        Long accountId = Long.parseLong(qyAccounts);
        Sort sort = new Sort("parent_id", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("t.del_flag", 0);
        conds.equal("t.accounts_id", accountId);
//        User user = UserUtils.getUser();
//        Qyuser qyuser = qyuserService.fetchById(user.getUserid());
//        Long orgId = qyuser.getOrgId();
        List<OrgUnit> orgunits = orgUnitService.fetchSearchByPage(null, conds, sort, 0, 0);

        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(OrgUnit.class, response).toExcel(orgunits, "组织信息");
    }

    @RequestMapping(value = "/templateExcel",method = {RequestMethod.GET,RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.ORGUNIT_EDIT)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(OrgUnit.class, response).toExcel(null, "组织信息");
    }

    @RequestMapping(value = "/importExcel",method = {RequestMethod.GET,RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.ORGUNIT_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = Long.parseLong(qyAccounts);
        if (file == null) {
            return list(request, model);
        }
        // 构造临时路径来存储上传的文件
        String uploadPath = System.getProperty("java.io.tmpdir");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String fileName = file.getOriginalFilename();
        String filePath = uploadPath + File.separator + fileName;
        File storeFile = new File(filePath);
        try {
            file.transferTo(storeFile);
            ExcelKit.$Import().readExcel(storeFile, rowData -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    OrgUnit orgUnit = new OrgUnit();
                    orgUnit.setAccountsId(accountId);
                    if (!StringUtils.isEmpty(rowData.get(0))) {
                        orgUnit.setNumber(rowData.get(0));
                    } else {
                        orgUnit.setNumber(codingruleUtils.getNumber(accountId, OrgUnit.class.getName()));
                    }

                    orgUnit.setOrgName(rowData.get(1));
                    OrgUnit parentOrgUnit = null;
                    if (!StringUtils.isEmpty(rowData.get(2))) {
                        parentOrgUnit = orgUnitService.findByAccountIdAndNumber(accountId, rowData.get(2));
                    }
                    if (parentOrgUnit != null) {
                        orgUnit.setParentId(new Long(rowData.get(2)));
                    }
                    Orgtype orgtype = null;
                    if (!StringUtils.isEmpty(rowData.get(3))) {
                        orgtype = orgtypeService.findByAccountIdAndNumber(accountId, rowData.get(3));
                    }
                    if (orgtype != null) {
                        orgUnit.setOrgtypeId(orgtype.getId());
                    }
                    if (!StringUtils.isEmpty(rowData.get(4))) {
                        orgUnit.setIsAdminUnit(rowData.get(4).equals("是") ? true : false);
                    }
                    if (!StringUtils.isEmpty(rowData.get(5))) {
                        orgUnit.setIsSalesUnit(rowData.get(5).equals("是") ? true : false);
                    }
                    orgUnit.setParentIds(parentOrgUnit == null ? 0 + "," : parentOrgUnit.getParentIds());
                    orgUnit.setCreateBy(UserUtils.getUser().getId());
                    orgUnit.setUpdateBy(UserUtils.getUser().getId());
                    orgUnitService.saveCache(orgUnit);
                    //去除weixin同步的内容
//                    int wxorgid = qyOrgUtil.create(orgUnit, parentOrgUnit);
//                    if (wxorgid == -1 || wxorgid == 0) {
//                        log.error("同步微信端出错: {}", orgUnit.toString());
//                    } else {
//                        orgUnit.setWxorgId("" + wxorgid);
//                    }
                    orgUnit.setParentIds(orgUnit.getParentIds() + orgUnit.getId() + ",");
                    orgUnitService.updateCache(orgUnit);
                }

            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }


        return list(request, model);
    }

    @RequestMapping(value = "treeData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject getTreeData(HttpServletRequest request) {
        Long accountId = Long.parseLong(qyAccounts);
        JSONObject rtnJson = new JSONObject();
        JSONArray array = new JSONArray();
        Sort sort = new Sort("parent_id", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("del_flag",0);
        conds.equal("accounts_id", accountId);
        //用户
        User user = UserUtils.getUser();
        Qyuser qyuser = qyuserService.fetchById(user.getUserid());
        Long orgId = qyuser.getOrgId();
        List<OrgUnit> orgUnits = orgUnitService.fetchSearchByPage(orgId, conds, sort, 0, 0);
        JSONObject t = new JSONObject();
        t.put("id", 0);
        t.put("pId", -1);
        t.put("name", rootOrgName);
        t.put("open",true);
        array.add(t);
        for(OrgUnit orgUnit : orgUnits){
            JSONObject tmp = new JSONObject();
            tmp.put("id", orgUnit.getId());
            if (orgUnit.getId() == orgId) {
                tmp.put("pId", 0);
            } else {
                tmp.put("pId", orgUnit.getParentId());
            }
            tmp.put("name", orgUnit.getOrgName());
            array.add(tmp);
        }
        rtnJson.put("aaData", array);
        return rtnJson;
    }


    @RequestMapping(value = "treeDataNoAuth",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject treeDataNoAuth(HttpServletRequest request) {
        Long accountId = Long.parseLong(qyAccounts);
        JSONObject rtnJson = new JSONObject();
        JSONArray array = new JSONArray();
        Sort sort = new Sort("parent_id", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("t.del_flag",0);
        conds.equal("t.accounts_id", accountId);
        //用户
//        User user = UserUtils.getUser();
//        Qyuser qyuser = qyuserService.fetchById(user.getUserid());
        Long orgId = 0L;//qyuser.getOrgId();
        List<OrgUnit> orgUnits = orgUnitService.fetchSearchByPage(orgId, conds, sort, 0, 0);
        JSONObject t = new JSONObject();
        t.put("id", 0);
        t.put("pId", -1);
        t.put("name", rootOrgName);
        t.put("open",true);
        array.add(t);
        for(OrgUnit orgUnit : orgUnits){
            JSONObject tmp = new JSONObject();
            tmp.put("id", orgUnit.getId());
            if (orgUnit.getId() == orgId) {
                tmp.put("pId", 0);
            } else {
                tmp.put("pId", orgUnit.getParentId());
            }
            tmp.put("name", orgUnit.getOrgName());
            array.add(tmp);
        }
        rtnJson.put("aaData", array);
        return rtnJson;
    }


    //获取列表数据
    @RequiresPermissions(value = PermissionSign.ORGUNIT_VIEW)
    @RequestMapping(value = "/listDataNoAuth",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listDataNoAuth(int iDisplayStart, int iDisplayLength, OrgUnit orgUnit, HttpServletRequest request) {
        Long accountId = Long.parseLong(qyAccounts);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountId);
        if(!StringUtils.isEmpty(orgUnit.getNumber())){
            conds.equal("t.number", orgUnit.getNumber());
        }
        if (!StringUtils.isEmpty(orgUnit.getOrgName())) {
            conds.like("t.org_name", orgUnit.getOrgName());
        }
        Long orgId = null;
        if (orgUnit.getId() != null) {
            orgId = orgUnit.getId();
        } else {
            //用户
//            User user = UserUtils.getUser();
//            Qyuser qyuser = qyuserService.fetchById(user.getUserid());
            orgId = 0L;//qyuser.getOrgId();
        }


        Sort sort = new Sort("t.create_time", OrderType.DESC);
        List<OrgUnitVO> list = orgUnitService.fetchSearchVOByPage(orgId, conds, sort, iDisplayStart, iDisplayLength);

        Conds myCond = new Conds();
        myCond.equal("del_flag", Constants.DEL_FLAG_0);
        myCond.equal("accounts_id", accountId);
        if (!StringUtils.isEmpty(orgUnit.getOrgName())) {
            myCond.like("org_name", orgUnit.getOrgName());
        }
//        if (!StringUtils.isEmpty(orgUnit.getIsAdminUnit())) {
//            myCond.equal("isadminunit", orgUnit.getIsAdminUnit());
//        }
//        if (!StringUtils.isEmpty(orgUnit.getIsSalesUnit())) {
//            myCond.equal("issalesunit", orgUnit.getIsSalesUnit());
//        }

        Integer counts = orgUnitService.count(orgId, myCond);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }



    @RequestMapping(value = "/sync",method = {RequestMethod.GET,RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.ORGUNIT_EDIT)
    @ResponseBody
    public JSONObject sync(HttpServletRequest request, Model model) {
        Long accountId = Long.parseLong(qyAccounts);
        // 同步微信端的部门，下拉到本地为主
        JSONObject retObj = qyOrgUtil.sync(accountId);
        log.info("同步结果: {}", retObj.toJSONString());
        return retObj;
    }
}
