package com.cftech.cms.distributor_area.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.cms.distributor_area.model.Distributor_area;
import com.cftech.cms.distributor_area.service.Distributor_areaService;
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.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 DISTRIBUTOR_AREA_VIEW = "qy:distributor_area:view"
 * 查看:public static final String DISTRIBUTOR_AREA_EDIT = "qy:distributor_area:edit"
 *
 * @author byj
 * @date: 2019-03-18 15:26
 */
@Slf4j
@Controller
@RequestMapping("/a/distributor_area")
public class Distributor_areaController {

    public static final String DISTRIBUTOR_AREA_VIEW = "qy:distributor_area:view";
    public static final String DISTRIBUTOR_AREA_EDIT = "qy:distributor_area:edit";

    @Autowired
    private Distributor_areaService distributor_areaService;
    @Autowired
    private CodingruleUtils codingruleUtils;


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

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

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

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

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

    //删除数据
    @RequiresPermissions(value = DISTRIBUTOR_AREA_EDIT)
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            distributor_areaService.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 = DISTRIBUTOR_AREA_EDIT)
    @ResponseBody
    public void templateExcel(HttpServletRequest request, HttpServletResponse response , Distributor_area distributor_area) {
        // 生成Excel并使用浏览器下载

        ExcelKit.$Export(Distributor_area.class, response).toExcel(null, "经销商地区");
    }

    //导入
    @RequestMapping(value = "/importExcel" , method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    @RequiresPermissions(value = DISTRIBUTOR_AREA_EDIT)
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        JSONObject retJson = new JSONObject();
        Long accountId = UserUtils.getmpaccounts(request);
        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);


            ExcelKit.$Import().setEmptyCellValue(null).readExcel(storeFile, rowData -> {
                Distributor_area distributor_area = new Distributor_area();
                Conds conds = new Conds();
                conds.equal("area_name",rowData.get(0));
                conds.equal("del_flag",0);
                Distributor_area distributorArea = distributor_areaService.fetchSearchByConds(conds);
                if(distributorArea!=null){
                    return;
                }else{
                    distributor_area.setArea_name(rowData.get(0));
                    distributor_area.setAccountsId(accountId);
                    distributor_areaService.save(distributor_area);
                }


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

        return retJson;
    }

}
