package com.cftech.activity.market.sign.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.activity.market.sign.model.Sign;
import com.cftech.activity.market.sign.model.SignDto;
import com.cftech.activity.market.sign.service.SignService;
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.DateFormatUtils;
import com.cftech.sys.model.User;
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.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 SIGN_VIEW = "qy:sign:view"
 * 查看:public static final String SIGN_EDIT = "qy:sign:edit"
 *
 * @author faye
 * @date: 2017-08-28 13:39
 */
@Slf4j
@Controller
@RequestMapping("/a/sign")
public class SignController {

    public static final String SIGN_VIEW = "qy:sign:view";
    public static final String SIGN_EDIT = "qy:sign:edit";

    @Autowired
    private SignService signService;


    //列表页面
    @RequiresPermissions(value = SIGN_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model,Long activityid,Long storeid) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        model.addAttribute("activityid",activityid);
        model.addAttribute("storeid",storeid);
        return "sign/signlist";
    }

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

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

    //获取列表数据
    @RequiresPermissions(value = SIGN_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, SignDto sign, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("s.del_flag", Constants.DEL_FLAG_0);
        conds.equal("s.accounts_id", accountsId);
        if (!StringUtils.isEmpty(sign.getPhone())) {
            conds.like("s.phone", sign.getPhone());
        }
        if (!StringUtils.isEmpty(sign.getName())) {
            conds.like("s.name", sign.getName());
        }
        if (!StringUtils.isEmpty(sign.getOpenid())) {
            conds.like("s.openid", sign.getOpenid());
        }
        if (!StringUtils.isEmpty(sign.getActivityid())) {
            conds.equal("s.activityName", sign.getActivityName());
        }
        if (!StringUtils.isEmpty(sign.getEnrollTime())) {
            conds.equal("s.enroll_time", sign.getEnrollTime());
        }
        if (!StringUtils.isEmpty(sign.getSignTime())) {
            conds.equal("s.sign_time", sign.getSignTime());
        }
        User user=UserUtils.getStoreUser();
        String storeids=user.getStoreids();
        if(com.cftech.core.util.StringUtils.isNotBlank(storeids)){
            String[] arr=storeids.split(",");
            if(arr.length==0){
                conds.in("s.storeid",new String[]{""});
            }else{
                conds.in("s.storeid",arr);
            }
        }else{
            conds.equal("s.storeid","-1");
        }

        if(sign.getStoreid()!=null){
            conds.equal("s.storeid",sign.getStoreid());
        }
        if(sign.getActivityid()!=null){
            conds.equal("s.activityid",sign.getActivityid());
        }
        Sort sort = new Sort("s.create_time", OrderType.DESC);

        List<SignDto> list = signService.fetchSearchByPageVo(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = signService.countVo(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = SIGN_VIEW)
    public void exportExcel(SignDto sign,HttpServletRequest request, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("s.create_time", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("s.del_flag", 0);
        conds.equal("s.accounts_id", accountId);

        User user=UserUtils.getStoreUser();
        String storeids=user.getStoreids();
        if(com.cftech.core.util.StringUtils.isNotBlank(storeids)){
            String[] arr=storeids.split(",");
            if(arr.length==0){
                conds.in("s.storeid",new String[]{""});
            }else{
                conds.in("s.storeid",arr);
            }
        }else{
            conds.equal("s.storeid","-1");
        }

        if (!StringUtils.isEmpty(sign.getPhone())) {
            conds.like("s.phone", sign.getPhone());
        }
        if (!StringUtils.isEmpty(sign.getName())) {
            conds.like("s.name", sign.getName());
        }
        if (!StringUtils.isEmpty(sign.getOpenid())) {
            conds.like("s.openid", sign.getOpenid());
        }
        if (!StringUtils.isEmpty(sign.getActivityid())) {
            conds.equal("s.activityName", sign.getActivityName());
        }
        if (!StringUtils.isEmpty(sign.getEnrollTime())) {
            conds.equal("s.enroll_time", sign.getEnrollTime());
        }
        if (!StringUtils.isEmpty(sign.getSignTime())) {
            conds.equal("s.sign_time", sign.getSignTime());
        }
        if(sign.getStoreid()!=null){
            conds.equal("s.storeid",sign.getStoreid());
        }
        if(sign.getActivityid()!=null){
            conds.equal("s.activityid",sign.getActivityid());
        }
        List<SignDto> list = signService.fetchSearchByPageVo(conds, sort, 0, 0);
        ExcelKit.$Export(SignDto.class, response).toExcel(list, "市场活动签到信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = SIGN_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Sign.class, response).toExcel(null, "市场活动签到信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = SIGN_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model,Long activityid,Long storeid) {
        Long accountId = UserUtils.getmpaccounts(request);
        if (file == null) {
            return list(request, model,activityid,storeid);
        }
// 构造临时路径来存储上传的文件
        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))) {
                    Sign sign = new Sign();
                    sign.setAccountsId(accountId);

                    sign.setUserid(!StringUtils.isEmpty(rowData.get(0))?Long.valueOf(rowData.get(0)):null);


                    sign.setPhone(rowData.get(1));


                    sign.setName(rowData.get(2));


                    sign.setOpenid(rowData.get(3));


                    sign.setActivityid(!StringUtils.isEmpty(rowData.get(4))?Long.valueOf(rowData.get(4)):null);


                    sign.setEnrollTime(DateFormatUtils.getDateFormat(rowData.get(5)));


                    sign.setSignTime(DateFormatUtils.getDateFormat(rowData.get(6)));

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

        return list(request, model, activityid, storeid);
    }

}
