package com.cftech.base.org.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.org.api.QyTagUtil;
import com.cftech.base.org.model.Qytag;
import com.cftech.base.org.service.QytagService;
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.StringUtils;
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.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 QYTAG_VIEW = "qy:qytag:view"
 * 查看:public static final String QYTAG_EDIT = "qy:qytag:edit"
 * qytagWeb
 * Created by Neil 14/02/2017.
 */
@Slf4j
@Controller
@RequestMapping("/a/qytag")
public class QytagController {

    /**
     * qytagService
     */
    @Autowired
    private QytagService qytagService;

    @Autowired
    private QyTagUtil qyTagUtil;

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

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

        if (StringUtils.isNotBlank(id)) {
            Qytag qytag = qytagService.fetchById(id);
            model.addAttribute("data", qytag);
            model.addAttribute("accountId", qytag.getAccountsId());
        } else {
            Long accountId = UserUtils.getmpaccounts(request);
            model.addAttribute("accountId", accountId);
        }
        return "managerqytag/qytagadd";
    }

    //提交编辑页面（新增、修改）
    @RequiresPermissions(value = PermissionSign.QYTAG_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject qytagListformData(Qytag qytag, Model model, HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        try {
            if (qytag != null && qytag.getId() != null) {
                qytag.setUpdateBy(UserUtils.getUser().getId());

                if (StringUtils.isBlank(qytag.getWxtagId())) {
                    int synRet = qyTagUtil.create(qytag);
                    if (synRet == -1 || synRet == 0) {
                        log.error("同步微信端失败，{}", qytag.toString());
                    } else {
                        qytag.setWxtagId("" + synRet);
                    }
                } else {
                    //update
                    if (!qyTagUtil.update(qytag)) {
                        log.error("tag update更新微信端失败，{}", qytag.toString());
                    }
                }

                qytagService.update(qytag);
                rtnJson.put("errorNo", 0);
            } else {
                //新增
                qytag.setDelFlag(false);
                qytag.setAccountsId(UserUtils.getmpaccounts(request));
                qytag.setCreateBy(UserUtils.getUser().getId());
                qytag.setUpdateBy(UserUtils.getUser().getId());
                int synRet = qyTagUtil.create(qytag);
                if (synRet == -1 || synRet == 0) {
                    log.error("同步微信端失败，{}", qytag.toString());
                } else {
                    qytag.setWxtagId("" + synRet);
                }
                qytagService.save(qytag);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = PermissionSign.QYTAG_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Qytag qytag, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if (StringUtils.isNotBlank(qytag.getName())) {
            conds.like("name", qytag.getName());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);
        List<Qytag> list = qytagService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer userCounts = qytagService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", userCounts);
        rtnJson.put("iTotalDisplayRecords", userCounts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = PermissionSign.QYTAG_EDIT)
    @RequestMapping(value = "/delete",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            Qytag qytag = qytagService.fetchById(id);
            if (!qyTagUtil.delete(qytag)) {
                log.error("tag delete 同步微信端失败，{}", qytag.toString());
            }
            qytagService.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.QYTAG_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);
        List<Qytag> qytags = qytagService.fetchSearchByPage(conds, sort, 0, 0);

        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(Qytag.class, response).toExcel(qytags, "企业标签信息");
    }

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

    @RequestMapping(value = "/importExcel",method = {RequestMethod.GET,RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.QYTAG_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        if (file == null) {
            return qytagList(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))) {
                    Qytag qytag = new Qytag();
                    qytag.setAccountsId(accountId);
                    qytag.setName(rowData.get(1));
                    qytag.setCreateBy(UserUtils.getUser().getId());
                    qytag.setUpdateBy(UserUtils.getUser().getId());
                    int synRet = qyTagUtil.create(qytag);
                    if (synRet == -1 || synRet == 0) {
                        log.error("同步微信端失败，{}", qytag.toString());
                    } else {
                        qytag.setWxtagId("" + synRet);
                    }
                    qytagService.save(qytag);
                }

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


        return qytagList(request, model);
    }

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

    @RequestMapping(value = "/syncusers",method = {RequestMethod.GET,RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.QYTAG_EDIT)
    @ResponseBody
    public JSONObject syncusers(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        // 同步微信端的标签，下拉到本地为主
        JSONObject retObj = qyTagUtil.syncUsers(accountId);
        log.info("同步结果: {}", retObj.toJSONString());
        return retObj;
    }
}