package com.cftech.base.org.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.base.org.model.Position;
import com.cftech.base.org.model.Qyuser;
import com.cftech.base.org.model.vo.PositionVO;
import com.cftech.base.org.service.PositionService;
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.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;

/**
 * 权限字符串说明:
 * 查看:public static final String POSITION_VIEW = "qy:position:view"
 * 查看:public static final String POSITION_EDIT = "qy:position:edit"
 * positionWeb
 * Created by Neil 14/02/2017.
 */
@Slf4j
@Controller
@RequestMapping("/a/position")
public class PositionController {

    /**
     * positionService
     */
    @Autowired
    private PositionService positionService;
    @Autowired
    private QyuserService qyuserService;

    //返回列表页面
    @RequiresPermissions(value = PermissionSign.POSITION_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
    public String positionList(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "managerposition/positionlist";
    }

    //返回编辑页面（新增、修改）
    @RequiresPermissions(value = PermissionSign.POSITION_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.GET,RequestMethod.POST})
    public String form(HttpServletRequest request, String id, Model model) {

        if (!StringUtils.isEmpty(id)) {
            Position position = positionService.fetchById(id);
            model.addAttribute("data", position);
            model.addAttribute("accountId", position.getAccountsId());
        } else {
            Long accountId = UserUtils.getmpaccounts(request);
            model.addAttribute("accountId", accountId);
        }
        return "managerposition/positionadd";
    }

    //提交编辑页面（新增、修改）
    @RequiresPermissions(value = PermissionSign.POSITION_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject positionListformData(Position position, Model model, HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        try {
            if (position != null && position.getId() != null) {
                position.setUpdateBy(UserUtils.getUser().getId());
                Position parentPosition = null;
                if (position.getParentId() != 0) {
                    parentPosition = positionService.fetchById(position.getParentId());
                    position.setParentIds(parentPosition.getParentIds() + position.getId() + ",");
                } else {
                    position.setParentIds("0," + position.getId() + ",");
                }
                positionService.update(position);
                rtnJson.put("errorNo", 0);
            } else {
                Position parentPosition = null;
                if (!StringUtils.isEmpty(position.getParentId())) {
                    parentPosition = positionService.fetchById(position.getParentId());
                }

                position.setParentIds(parentPosition == null ? 0 + "," : parentPosition.getParentIds());
                position.setDelFlag(false);
                position.setStatus("0");
                position.setAccountsId(UserUtils.getmpaccounts(request));
                position.setCreateBy(UserUtils.getUser().getId());
                position.setUpdateBy(UserUtils.getUser().getId());
                positionService.save(position);
                position.setParentIds(position.getParentIds() + position.getId() + ",");
                positionService.update(position);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = PermissionSign.POSITION_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Position position, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if (!StringUtils.isEmpty(position.getName())) {
            conds.like("t.name", position.getName());
        }
        Sort sort = new Sort("t.number", OrderType.ASC);
        User user = UserUtils.getUser();
        Qyuser qyuser = qyuserService.fetchById(user.getUserid());
        Long positionId = qyuser.getPositionId();
        List<PositionVO> list = positionService.fetchSearchVOByPage(positionId, conds, sort, iDisplayStart, iDisplayLength);

        Conds myCond = new Conds();
        myCond.equal("del_flag", Constants.DEL_FLAG_0);
        myCond.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(position.getName())) {
            myCond.like("name", position.getName());
        }

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

    //删除数据
    @RequiresPermissions(value = PermissionSign.POSITION_EDIT)
    @RequestMapping(value = "/delete",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            positionService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    @RequestMapping(value = "/exportExcel",method = {RequestMethod.GET,RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.POSITION_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("create_time", 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 positionId = qyuser.getPositionId();
        List<Position> positions = positionService.fetchSearchByPage(positionId, conds, sort, 0, 0);

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

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

    @RequestMapping(value = "/importExcel",method = {RequestMethod.GET,RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.POSITION_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        if (file == null) {
            return positionList(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))) {
                    Position position = new Position();
                    position.setAccountsId(accountId);
                    position.setNumber(rowData.get(0));
                    position.setName(rowData.get(1));

                    Position parentPosition = null;
                    if (!StringUtils.isEmpty(rowData.get(2))) {
                        parentPosition = positionService.findByAccountIdAndNumber(accountId, rowData.get(2));
                    }

                    if (parentPosition != null) {
                        position.setParentId(new Long(rowData.get(2)));
                    }

                    position.setParentIds(parentPosition == null ? 0 + "," : parentPosition.getParentIds());
                    position.setCreateBy(UserUtils.getUser().getId());
                    position.setUpdateBy(UserUtils.getUser().getId());
                    positionService.save(position);
                    position.setParentIds(position.getParentIds() + position.getId() + ",");
                    positionService.update(position);

                }

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


        return positionList(request, model);
    }
    //获取所有列表数据，不考虑权限
    @RequiresPermissions(value = PermissionSign.POSITION_VIEW)
    @RequestMapping(value = "/listDataNoAuth",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listDataNoAuth(int iDisplayStart, int iDisplayLength, Position position, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if (!StringUtils.isEmpty(position.getName())) {
            conds.like("t.name", position.getName());
        }
        Sort sort = new Sort("t.number", OrderType.ASC);
//        User user = UserUtils.getUser();
//        Qyuser qyuser = qyuserService.fetchById(user.getUserid());
        //Long positionId = qyuser.getPositionId();
        Long positionId = 0L;
        List<PositionVO> list = positionService.fetchSearchVOByPage(positionId, conds, sort, iDisplayStart, iDisplayLength);

        Conds myCond = new Conds();
        myCond.equal("del_flag", Constants.DEL_FLAG_0);
        myCond.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(position.getName())) {
            myCond.like("name", position.getName());
        }

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


    @RequestMapping(value = "treeData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject getTreeData(HttpServletRequest request) {
        Long accountId = UserUtils.getmpaccounts(request);
        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 positionId = qyuser.getPositionId();
        if (positionId == null) positionId = 0L;
        List<Position> positions = positionService.fetchSearchByPage(positionId, conds, sort, 0, 0);
        JSONObject t = new JSONObject();
        t.put("id", 0);
        t.put("pId", -1);
        t.put("name", "职位树");
        t.put("open", true);
        array.add(t);
        for (Position position : positions) {
            JSONObject tmp = new JSONObject();
            tmp.put("id", position.getId());
            if (positionId == position.getId()) {
                tmp.put("pId", 0);
            } else {
                tmp.put("pId", position.getParentId());
            }
            tmp.put("name", position.getName());
            array.add(tmp);
        }
        rtnJson.put("aaData", array);
        return rtnJson;
    }
    //获取全局职位树
    @RequestMapping(value = "treeDataNoAuth",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject getTreeDataNoAuth(HttpServletRequest request) {
        Long accountId = UserUtils.getmpaccounts(request);
        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 positionId = qyuser.getPositionId();
        Long positionId = 0L;
        List<Position> positions = positionService.fetchSearchByPage(positionId, conds, sort, 0, 0);
        JSONObject t = new JSONObject();
        t.put("id", 0);
        t.put("pId", -1);
        t.put("name", "职位树");
        t.put("open", true);
        array.add(t);
        for (Position position : positions) {
            JSONObject tmp = new JSONObject();
            tmp.put("id", position.getId());
            if (positionId == position.getId()) {
                tmp.put("pId", 0);
            } else {
                tmp.put("pId", position.getParentId());
            }
            tmp.put("name", position.getName());
            array.add(tmp);
        }
        rtnJson.put("aaData", array);
        return rtnJson;
    }
}