package com.cftech.behavior.qrcode.record.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.behavior.qrcode.record.model.QrcodeRecord;
import com.cftech.behavior.qrcode.record.service.QrcodeRecordService;
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.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
 *
 * 权限字符串说明:
 * 查看:public static final String QRCODERECORD_VIEW = "qy:qrcodeRecord:view"
 * 查看:public static final String QRCODERECORD_EDIT = "qy:qrcodeRecord:edit"
 *
 * @author faye
 * @date: 2017-09-25 11:51
 */
@Slf4j
@Controller
@RequestMapping("/a/qrcodeRecord")
public class QrcodeRecordController {

    public static final String QRCODERECORD_VIEW = "qy:qrcodeRecord:view";
    public static final String QRCODERECORD_EDIT = "qy:qrcodeRecord:edit";

    @Autowired
    private QrcodeRecordService qrcodeRecordService;
    @Autowired
    private CodingruleUtils codingruleUtils;


    //列表页面
    @RequiresPermissions(value = QRCODERECORD_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.POST,RequestMethod.GET})
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "qrcodeRecord/qrcodeRecordlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = QRCODERECORD_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.POST,RequestMethod.GET})
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            QrcodeRecord qrcodeRecord = qrcodeRecordService.fetchById(id);
            model.addAttribute("data", qrcodeRecord);
        }
        return "qrcodeRecord/qrcodeRecordform";
    }

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

    //获取列表数据
    @RequiresPermissions(value = QRCODERECORD_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, QrcodeRecord qrcodeRecord, 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(qrcodeRecord.getNumber())) {
            conds.like("number", qrcodeRecord.getNumber());
        }
        if (!StringUtils.isEmpty(qrcodeRecord.getType())) {
            conds.like("type", qrcodeRecord.getType());
        }
        if (!StringUtils.isEmpty(qrcodeRecord.getTicket())) {
            conds.like("ticket", qrcodeRecord.getTicket());
        }
        if (!StringUtils.isEmpty(qrcodeRecord.getEmpname())) {
            conds.like("empname", qrcodeRecord.getEmpname());
        }
        if (!StringUtils.isEmpty(qrcodeRecord.getKeywords())) {
            conds.like("keywords", qrcodeRecord.getKeywords());
        }
        if (!StringUtils.isEmpty(qrcodeRecord.getMobile())) {
            conds.like("mobile", qrcodeRecord.getMobile());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

    @RequestMapping(value = "/exportExcel",method = {RequestMethod.POST,RequestMethod.GET})
    @RequiresPermissions(value = QRCODERECORD_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<QrcodeRecord> list = qrcodeRecordService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(QrcodeRecord.class, response).toExcel(list, "扫码记录信息");
    }

    @RequestMapping(value = "/templateExcel",method = {RequestMethod.POST,RequestMethod.GET})
    @RequiresPermissions(value = QRCODERECORD_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(QrcodeRecord.class, response).toExcel(null, "扫码记录信息");
    }

    @RequestMapping(value = "/importExcel",method = {RequestMethod.POST,RequestMethod.GET})
    @RequiresPermissions(value = QRCODERECORD_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        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))) {
                    QrcodeRecord qrcodeRecord = new QrcodeRecord();
                    qrcodeRecord.setAccountsId(accountId);

                    qrcodeRecord.setNumber(rowData.get(0));


                    qrcodeRecord.setType(rowData.get(1));


                    qrcodeRecord.setTicket(rowData.get(2));


                    qrcodeRecord.setEmpname(rowData.get(3));


                    qrcodeRecord.setKeywords(rowData.get(4));


                    qrcodeRecord.setMobile(rowData.get(5));

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

        return list(request, model);
    }

}
