package com.cftech.authentication.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.authentication.model.Authentication;
import com.cftech.authentication.service.AuthenticationService;
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.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.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 AUTHENTICATION_VIEW = "qy:authentication:view"
 * 查看:public static final String AUTHENTICATION_EDIT = "qy:authentication:edit"
 *
 * @author Buyj
 * @date: 2020-11-23 16:56
 */
@Slf4j
@Controller
@RequestMapping("/a/authentication")
public class AuthenticationController {

    public static final String AUTHENTICATION_VIEW = "qy:authentication:view";
    public static final String AUTHENTICATION_EDIT = "qy:authentication:edit";

    @Autowired
    private AuthenticationService authenticationService;


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

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

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

    //获取列表数据
    @RequiresPermissions(value = AUTHENTICATION_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Authentication authentication, 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(authentication.getName())) {
            conds.like("name", authentication.getName());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = AUTHENTICATION_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Long accountId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountId);
        if (!StringUtils.isEmpty(authentication.getName())) {
            conds.like("name", authentication.getName());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);
        List<Authentication> list = authenticationService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Authentication.class, response).toExcel(list, "身份验证信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = AUTHENTICATION_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Authentication.class, response).toExcel(null, "身份验证信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = AUTHENTICATION_EDIT)
    @ResponseBody
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        JSONObject retJson = new JSONObject();
        Long accountId = UserUtils.getmpaccounts(request);
        StringBuffer sb = 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);
            ExcelKit.$Import().setEmptyCellValue("").readExcel(storeFile, rowData -> {
                Authentication authentication = new Authentication();
                authentication.setAccountsId(accountId);
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    authentication.setName(rowData.get(0));
                }
                if (!StringUtils.isEmpty(rowData.get(1))) {
                    if (rowData.get(1).length() == 15 || rowData.get(1).length() == 18){
                        authentication.setIdCard(rowData.get(1));
                    }else{
                        sb.append(rowData.get(0)+",");
                        return;
                    }

                }

                if (!StringUtils.isEmpty(rowData.get(2))) {
                    authentication.setDescription(rowData.get(2));
                }

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

        retJson.put("errorNo", "0");
        if(sb.length() > 0){
            retJson.put("errorMsg","部分导入失败，原因：未填写正确的身份证号码，导入失败名称："+sb.toString());
        }else{
            retJson.put("errorMsg", "导入成功");
        }
        return retJson;
    }

}
