package com.cftech.common.appitems.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.common.appitems.model.Appitems;
import com.cftech.common.appitems.service.AppitemsService;
import com.cftech.common.promotionstock.model.SupplierStockDto;
import com.cftech.common.promotionstock.service.PromotionStockService;
import com.cftech.common.typeform.service.TypeformService;
import com.cftech.common.use.model.Use;
import com.cftech.common.use.service.UseService;
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.StringUtils;
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.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;
import java.util.concurrent.atomic.AtomicReference;


/**
 * 申请项Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String APPITEMS_VIEW = "qy:appitems:view"
 * 查看:public static final String APPITEMS_EDIT = "qy:appitems:edit"
 *
 * @author faye
 * @date: 2019-08-16 10:37
 */
@Slf4j
@Controller
@RequestMapping("/a/appitems")
public class AppitemsController {

    public static final String APPITEMS_VIEW = "qy:appitems:view";
    public static final String APPITEMS_EDIT = "qy:appitems:edit";

    @Autowired
    private AppitemsService appitemsService;
    @Autowired
    private CodingruleUtils codingruleUtils;

    @Autowired
    private TypeformService typeformService;

    @Autowired
    private UseService useService;


    //列表页面
    @RequiresPermissions(value = APPITEMS_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model,String typeform) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        model.addAttribute("typeform",StringUtils.isEmpty(typeform)?"1":typeform);
        return "appitems/appitemslist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = APPITEMS_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model,String typeform) {
        if (!StringUtils.isEmpty(id)) {
            Appitems appitems = appitemsService.fetchById(id);
            Conds conds = new Conds();
            conds.equal("au.appitem_id", id);
            List<Use> use = useService.fetchSearchByPageItemByUse(conds, null, 0, 0);
            String name = "";
            String ids = "";
            for (Use u : use) {
                name += u.getName() + ",";
                ids += u.getId() + ",";
            }
            if (name.length() > 0) {
                model.addAttribute("useId", ids.substring(0, ids.length() - 1));
                model.addAttribute("useName", name.substring(0, name.length() - 1));
            }
            model.addAttribute("data", appitems);
        }
        model.addAttribute("typeform",StringUtils.isEmpty(typeform)?"1":typeform);
        return "appitems/appitemsform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = APPITEMS_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Appitems appitems, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (appitems != null && appitems.getId() != null) {
                appitems.setUpdateBy(UserUtils.getUser().getId());
                String[] useIds = {};
                if (StringUtils.isNotBlank(appitems.getUseIds())) {
                    useIds = appitems.getUseIds().split(",");
                }
                useService.insertItemByUse(appitems, useIds);
                rtnJson.put("errorNo", 0);
            } else {
                if (StringUtils.isBlank(appitems.getNumber())) {
                    appitems.setNumber(codingruleUtils.getNumber(accountsId, Appitems.class.getName()));
                }

                appitems.setAccountsId(accountsId);
                appitems.setDelFlag(false);
                appitems.setAccountsId(UserUtils.getmpaccounts(request));
                appitems.setCreateBy(UserUtils.getUser().getId());
                appitems.setUpdateBy(UserUtils.getUser().getId());
                String[] useIds = {};
                if (StringUtils.isNotBlank(appitems.getUseIds())) {
                    useIds = appitems.getUseIds().split(",");
                }
                useService.insertItemByUse(appitems, useIds);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = APPITEMS_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Appitems appitems, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("ca.del_flag", Constants.DEL_FLAG_0);
        conds.equal("ca.accounts_id", accountsId);
        if (!StringUtils.isEmpty(appitems.getNumber())) {
            conds.like("ca.number", appitems.getNumber());
        }
        if (appitems.getUseId() != null) {
            conds.equal("au.use_id", appitems.getUseId());
        }
        if(appitems.getTypeform()!=null){
            conds.equal("ca.typeform", appitems.getTypeform());
        }
        if (!StringUtils.isEmpty(appitems.getName())) {
            conds.like("ca.name", appitems.getName());
        }
        Sort sort = new Sort("ca.create_time", OrderType.DESC);

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

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = APPITEMS_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, Appitems appitems) {
        Long accountId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("ca.del_flag", Constants.DEL_FLAG_0);
        conds.equal("ca.accounts_id", accountId);
        if (!StringUtils.isEmpty(appitems.getNumber())) {
            conds.like("ca.number", appitems.getNumber());
        }
        if (appitems.getUseId() != null) {
            conds.equal("ca.use_id", appitems.getUseId());
        }
        if(appitems.getTypeform()!=null){
            conds.equal("ca.typeform", appitems.getTypeform());
        }
        if (!StringUtils.isEmpty(appitems.getName())) {
            conds.like("ca.name", appitems.getName());
        }
        Sort sort = new Sort("ca.create_time", OrderType.DESC);
        List<Appitems> list = appitemsService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Appitems.class, response).toExcel(list, "申请项信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = APPITEMS_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Appitems.class, response).toExcel(null, "申请项信息");
    }

    @RequestMapping(value = "getfetchDataChild", method = {RequestMethod.POST})
    @ResponseBody
    public com.alibaba.fastjson.JSONObject getfetchDataChild(HttpServletRequest request) {
        com.alibaba.fastjson.JSONObject rtnJson = new com.alibaba.fastjson.JSONObject();
        com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
        Long accountsid = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("cd.sort", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("cd.del_flag", Constants.DEL_FLAG_0);
        conds.equal("cd.accounts_id", accountsid);
        List<Use> list = useService.fetchSearchByPage(conds, sort, 0, 0);
        com.alibaba.fastjson.JSONObject t = new com.alibaba.fastjson.JSONObject();
        t.put("id", 0);
        t.put("pId", -1);
        t.put("name", "申请用途");
        t.put("open", true);
        array.add(t);
        for (Use use : list) {
            com.alibaba.fastjson.JSONObject tmp = new com.alibaba.fastjson.JSONObject();
            tmp.put("id", use.getId());
            tmp.put("pId", 0);
            tmp.put("name", use.getName());
            array.add(tmp);
        }
        rtnJson.put("aaData", array);
        return rtnJson;
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = APPITEMS_EDIT)
    @ResponseBody
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model,Long typeform) {
        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);
        StringBuffer stringBuffer = new StringBuffer();
        AtomicReference<Integer> i = new AtomicReference<>(0);
        try {
            file.transferTo(storeFile);
            ExcelKit.$Import().readExcel(storeFile, rowData -> {
                Appitems appitems = new Appitems();
                appitems.setAccountsId(accountId);
                appitems.setNumber(rowData.get(0));
                String number = rowData.get(0);
                if (StringUtils.isNotBlank(number)) {
                    Conds itemConds = new Conds();
                    itemConds.equal("ca.number", number);
                    itemConds.equal("ca.del_flag", 0);
                    Appitems appitems1 = appitemsService.fetchSearchByConds(itemConds);
                    if (appitems1 != null) {//修改
                       appitems.setId(appitems1.getId());
                    }
                    appitems.setIsOnline(rowData.get(2));
                    appitems.setName(rowData.get(3));
                    appitems.setSpecifications(rowData.get(4));
                    appitems.setAuthenticStock(rowData.get(5));
                    appitems.setInventedStock(rowData.get(6));
                    appitems.setPrice(rowData.get(7));
                    if(StringUtils.isNotBlank(rowData.get(8))){
                        appitems.setDisStock(Integer.valueOf(rowData.get(8)));
                    }
                    if(StringUtils.isNotBlank(rowData.get(9))){
                        appitems.setSort(rowData.get(9));
                    }
                    appitems.setTypeform(typeform);
                    if (StringUtils.isNotBlank(rowData.get(1))) {//所属用途
                        String str = useIds(rowData.get(1));
                        if("1".equals(str)){
                            i.getAndSet(i.get() + 1);
                            stringBuffer.append("编号:"+number+",存在找不到的申请用途，请调整数据<br/>");
                            return;
                        }
                        useService.insertItemByUse(appitems, str.split(","));
                    }
                }

            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        retJson.put("errorNo", "0");
        retJson.put("errorMsg", "导入成功");
        if(!"".equals(stringBuffer.toString())){
            stringBuffer.insert(0,"<div style='overflow:scroll;height:200px'>");
            stringBuffer.append("</div>");
            retJson.put("errorMsg","<font color='red'>"+i+"</font>条数据未导入成功："+stringBuffer.toString());
        }
        return retJson;
    }

    @Autowired
    private PromotionStockService promotionStockService;

    @RequestMapping("/exportSupplierExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        List<SupplierStockDto> list = promotionStockService.getSupplierStockStatistics(null);
        ExcelKit.$Export(SupplierStockDto.class, response).toExcel(list, "供应商剩余货量实时统计");
    }


    public String useIds(String userNames) {
        String[] useIds = userNames.split(";");
        Conds conds = new Conds();
        conds.in("cd.name", useIds);
        List<Use> useList = useService.fetchSearchByPage(conds, null, 0, 0);
        if(useList!=null && useList.size()!=useIds.length){
            return "1";
        }
        String useId = "";
        for (Use u : useList) {
            useId += u.getId() + ",";
        }
       return useId;
    }

}
