package com.cftech.common.typeform.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.common.typeappform.model.TypeAppForm;
import com.cftech.common.typeform.model.Typeform;
import com.cftech.common.typeform.service.TypeformService;
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.MpTokenUtil;
import com.cftech.shop.qrcode.model.WxQrcode;
import com.cftech.shop.qrcode.service.WxQrcodeService;
import com.cftech.shop.qrcode.util.WxQrcodeUtil;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mp.api.qrcode.QrcodeDownload;
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 TYPEFORM_VIEW = "qy:typeform:view"
 * 查看:public static final String TYPEFORM_EDIT = "qy:typeform:edit"
 *
 * @author faye
 * @date: 2019-08-14 16:31
 */
@Slf4j
@Controller
@RequestMapping("/a/typeform")
public class TypeformController {

    public static final String TYPEFORM_VIEW = "qy:typeform:view";
    public static final String TYPEFORM_EDIT = "qy:typeform:edit";

    @Autowired
    private TypeformService typeformService;


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

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

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

    //获取列表数据
    @RequiresPermissions(value = TYPEFORM_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Typeform typeform, 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(typeform.getName())) {
            conds.like("name", typeform.getName());
        }
        if (!StringUtils.isEmpty(typeform.getPrice())) {
            conds.like("price", typeform.getPrice());
        }
        if (!StringUtils.isEmpty(typeform.getQrcode())) {
            conds.equal("qrcode", typeform.getQrcode());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = TYPEFORM_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, Typeform typeform) {
        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);
        if (!StringUtils.isEmpty(typeform.getName())) {
            conds.like("name", typeform.getName());
        }
        List<Typeform> list = typeformService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Typeform.class, response).toExcel(list, "申请类型单信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = TYPEFORM_VIEW)

    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Typeform.class, response).toExcel(null, "申请类型单信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = TYPEFORM_EDIT)
    @ResponseBody
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        JSONObject retJson = new JSONObject();
        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);
            ExcelKit.$Import().readExcel(storeFile, rowData -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    Typeform typeform = new Typeform();
                    typeform.setAccountsId(accountId);
                    typeform.setName(rowData.get(0));
                    typeform.setPrice(rowData.get(1));
                    //typeform.setQrcode(rowData.get(2));
                    typeformService.save(typeform);
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        retJson.put("errorNo", "0");
        retJson.put("errorMsg", "导入成功");
        return retJson;
    }





}
