package com.cftech.showroom.explainer.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.core.poi.OnReadDataHandler;
import com.cftech.showroom.explainer.model.Explainer;
import com.cftech.showroom.explainer.service.ExplainerService;
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.showroom.sdepartment.model.Sdepartment;
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;


/**
 * 展厅申请讲解人Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String EXPLAINER_VIEW = "qy:explainer:view"
 * 查看:public static final String EXPLAINER_EDIT = "qy:explainer:edit"
 *
 * @author lisw
 * @date: 2019-07-31 15:46
 */
@Slf4j
@Controller
@RequestMapping("/a/explainer")
public class ExplainerController {

    public static final String EXPLAINER_VIEW = "qy:explainer:view";
    public static final String EXPLAINER_EDIT = "qy:explainer:edit";

    @Autowired
    private ExplainerService explainerService;
    @Autowired
    private CodingruleUtils codingruleUtils;


    //列表页面
    @RequiresPermissions(value = EXPLAINER_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "explainer/explainerlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = EXPLAINER_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Explainer explainer = explainerService.fetchById(id);
            model.addAttribute("data", explainer);
        }
        return "explainer/explainerform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = EXPLAINER_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Explainer explainer, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (explainer != null && explainer.getId() != null) {
                explainer.setUpdateBy(UserUtils.getUser().getId());
                explainerService.update(explainer);
                rtnJson.put("errorNo", 0);
            } else {
                explainer.setNo(codingruleUtils.getNumber(accountsId,Explainer.class.getName()));
                explainer.setAccountsId(accountsId);
                explainer.setDelFlag(false);
                explainer.setAccountsId(UserUtils.getmpaccounts(request));
                explainer.setCreateBy(UserUtils.getUser().getId());
                explainer.setUpdateBy(UserUtils.getUser().getId());
                explainerService.save(explainer);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = EXPLAINER_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Explainer explainer, 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.isEmpty(explainer.getNumber())) {
            conds.like("number", explainer.getNumber());
        }
        if (!StringUtils.isEmpty(explainer.getName())) {
            conds.like("name", explainer.getName());
        }
        if (!StringUtils.isEmpty(explainer.getEmail())) {
            conds.like("email", explainer.getEmail());
        }
        if (!StringUtils.isEmpty(explainer.getHeadImage())) {
            conds.equal("head_image", explainer.getHeadImage());
        }
        Sort sort = new Sort("sort", OrderType.ASC);

        List<Explainer> list = explainerService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = explainerService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

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


    //下载模板
    @RequestMapping(value = "/templateExcel", method = {RequestMethod.GET, RequestMethod.POST})
    @RequiresPermissions(value = EXPLAINER_VIEW)
    @ResponseBody
    public void templateExcel(HttpServletRequest request, HttpServletResponse response, Explainer explainer) {
        // 生成Excel并使用浏览器下载

        ExcelKit.$Export(Explainer.class, response).toExcel(null, "品牌大使信息");
    }


    @RequestMapping(value = "/exportExcel", method = {RequestMethod.GET, RequestMethod.POST})
    @RequiresPermissions(value = EXPLAINER_VIEW)
    @ResponseBody
    public void exportInviteCodeExcel(HttpServletRequest request, HttpServletResponse response, Sdepartment sdepartment) {
        // 生成Excel并使用浏览器下载
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(sdepartment.getNumber())) {
            conds.like("number", sdepartment.getNumber());
        }
        if (!StringUtils.isEmpty(sdepartment.getName())) {
            conds.like("name", sdepartment.getName());
        }
        Sort sort = new Sort("sort", OrderType.ASC);

        List<Explainer> list = explainerService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Explainer.class, response).toExcel(list, "品牌大使信息");
    }


    //导入
    @RequestMapping(value = "/importExcel", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @RequiresPermissions(value = EXPLAINER_EDIT)
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model, Long id) {
        JSONObject retJson = new JSONObject();
        Long accountId = UserUtils.getmpaccounts(request);
        Long userId = UserUtils.getUser().getId();
        StringBuffer stringBuffer = new StringBuffer();
        if (file == null) {
            retJson.put("errorNo", "1");
            retJson.put("errorMsg", "未选择导入文件");
            return retJson;
        }
        // 构造临时路径来存储上传的文件
        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);
            int i = 0;
            ExcelKit.$Import().setEmptyCellValue(null).readExcel(storeFile, new OnReadDataHandler() {
                @Override
                public void handler(List<String> rowData) {
                    Explainer explainer = new Explainer();
                    if (!StringUtils.isEmpty(rowData.get(0))) {
                        if (!StringUtils.isEmpty(rowData.get(1))) {
                            explainer.setName(rowData.get(1));
                        }
                        if (!StringUtils.isEmpty(rowData.get(2))) {
                            explainer.setEmail(rowData.get(2));
                        }
                        if (!StringUtils.isEmpty(rowData.get(3))) {
                            explainer.setNumber(rowData.get(3));
                        }
                        if (!StringUtils.isEmpty(rowData.get(4))) {
                            explainer.setDescription(rowData.get(4));
                        }
                        if (!StringUtils.isEmpty(rowData.get(5))) {
                            explainer.setSort(rowData.get(5));
                        }
                        if (!StringUtils.isEmpty(rowData.get(6))) {
                            explainer.setStatus(rowData.get(6));
                        }
                        explainer.setUpdateBy(userId);
                        Conds conds = new Conds();
                        conds.equal("no", rowData.get(0));
                        Explainer explainerTemp = explainerService.fetchSearchByConds(conds);
                        if (explainerTemp != null) {
                            explainer.setId(explainerTemp.getId());
                            explainerService.update(explainer);
                        } else {
                            explainer.setCreateBy(userId);
                            explainer.setAccountsId(accountId);
                            explainerService.save(explainer);
                        }
                    }

                }
            });
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        }
        retJson.put("errorNo", "0");
        retJson.put("errorMsg", "导入成功");
        return retJson;
    }

}
