package com.cftech.cms.distributor.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.cms.distributor.model.Distributor;
import com.cftech.cms.distributor.model.DistributorDto;
import com.cftech.cms.distributor.service.DistributorService;
import com.cftech.cms.distributor_area.model.Distributor_area;
import com.cftech.cms.distributor_area.service.Distributor_areaService;
import com.cftech.cms.distributor_type.model.Distributor_type;
import com.cftech.cms.distributor_type.service.Distributor_typeService;
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_VIEW = "qy:distributor:view"
 * 查看:public static final String DISTRIBUTOR_EDIT = "qy:distributor:edit"
 *
 * @author byj
 * @date: 2019-03-18 16:08
 */
@Slf4j
@Controller
@RequestMapping("/a/distributor")
public class DistributorController {

    public static final String DISTRIBUTOR_VIEW = "qy:distributor:view";
    public static final String DISTRIBUTOR_EDIT = "qy:distributor:edit";

    @Autowired
    private DistributorService distributorService;
    @Autowired
    private CodingruleUtils codingruleUtils;
    @Autowired
    private Distributor_typeService distributor_typeService;
    @Autowired
    private Distributor_areaService distributor_areaService;;


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

    //编辑页面（新增、修改）
    @RequiresPermissions(value = DISTRIBUTOR_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Distributor distributor = distributorService.fetchById(id);
            model.addAttribute("data", distributor);
            if(!StringUtils.isEmpty(distributor.getType_id())){
                Distributor_type type = distributor_typeService.fetchById(distributor.getType_id());
                if(type.isDelFlag()){
                }else{
                    model.addAttribute("type_name",type.getType_name());
                }

            }
            if(!StringUtils.isEmpty(distributor.getArea_id())){
                Distributor_area area = distributor_areaService.fetchById(distributor.getArea_id());
                if(area.isDelFlag()){
                }else{
                    model.addAttribute("area_name",area.getArea_name());
                }
            }
        }
        return "distributor/distributorform";
    }

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

    //获取列表数据
    @RequiresPermissions(value = DISTRIBUTOR_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Distributor distributor, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("d.del_flag", Constants.DEL_FLAG_0);
        conds.equal("d.accounts_id", accountsId);
        if(!StringUtils.isEmpty(distributor.getCompany())){
            conds.like("d.company",distributor.getCompany());
        }
        if(!StringUtils.isEmpty(distributor.getPhone())){
            conds.like("d.phone",distributor.getPhone());
        }
        List<DistributorDto> list =null;
        Sort sort = new Sort("d.create_time", OrderType.DESC);
        try {
             list = distributorService.selectDistributor(conds, sort, iDisplayStart, iDisplayLength);
        }catch (Exception e){
            e.printStackTrace();
        }

        Integer counts = distributorService.selectDistributorCount(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

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

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

    //导入
    @RequestMapping(value = "/importExcel" , method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    @RequiresPermissions(value = DISTRIBUTOR_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 distributor= new Distributor();
            Long accountsId = UserUtils.getmpaccounts(request);
            distributor.setCompany(rowData.get(0));
            distributor.setPhone(rowData.get(1));
            distributor.setFax(rowData.get(2));
            distributor.setAddress_detail(rowData.get(3));
            distributor.setAddress(rowData.get(4));
            distributor.setEmail(rowData.get(5));
            distributor.setLongitude(rowData.get(6));
            distributor.setLatitude(rowData.get(7));
            distributor.setAccountsId(accountsId);
            if(!StringUtils.isEmpty(rowData.get(8))){
                Conds conds= new Conds();
                conds.equal("type_name",rowData.get(8));
                List<Distributor_type> list = distributor_typeService.fetchSearchByPage(conds,null,0,0);
                if(list!=null&&list.size()>0){
                    distributor.setType_id(list.get(0).getId());
                }
            }
            if(!StringUtils.isEmpty(rowData.get(9))){
                Conds conds = new Conds();
                conds.equal("area_name",rowData.get(9));
                List<Distributor_area> list = distributor_areaService.fetchSearchByPage(conds,null,0,0);
                if(list!=null&&list.size()>0){
                    distributor.setArea_id(list.get(0).getId());
                }
            }
            distributorService.save(distributor);

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

        return retJson;
    }

}
