package com.cftech.product.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.product.model.Product;
import com.cftech.product.service.ProductService;
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.productclassify.model.Productclassify;
import com.cftech.productclassify.service.ProductclassifyService;
import com.cftech.productintowareroom.model.ProductIntoWareroom;
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 PRODUCT_VIEW = "qy:product:view"
 * 查看:public static final String PRODUCT_EDIT = "qy:product:edit"
 *
 * @author Buyj
 * @date: 2020-09-24 15:07
 */
@Slf4j
@Controller
@RequestMapping("/a/product")
public class ProductController {

    public static final String PRODUCT_VIEW = "qy:product:view";
    public static final String PRODUCT_EDIT = "qy:product:edit";

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductclassifyService productclassifyService;

    @Autowired
    private CodingruleUtils codingruleUtils;


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

    //编辑页面（新增、修改）
    @RequiresPermissions(value = PRODUCT_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Product product = productService.fetchById(id);
            if (!StringUtils.isEmpty(product.getClassifyId())) {
                product.setClassifyName(productclassifyService.fetchById(product.getClassifyId()).getClassifyName());
            }

            model.addAttribute("data", product);
        }
        return "product/productform";
    }

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

    //获取列表数据
    @RequiresPermissions(value = PRODUCT_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Product product, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("a.del_flag", Constants.DEL_FLAG_0);
        conds.equal("a.accounts_id", accountsId);
        if(!StringUtils.isEmpty(product.getProductName())){
            conds.like("a.product_name",product.getProductName());
        }

        if(!StringUtils.isEmpty(product.getClassifyName())){
            conds.like("b.classify_name",product.getClassifyName());
        }
        Sort sort = new Sort("a.create_time", OrderType.DESC);

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

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = PRODUCT_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response ,Product product) {
        Long accountId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("a.del_flag", 0);
        conds.equal("a.accounts_id", accountId);
        if(!StringUtils.isEmpty(product.getProductName())){
            conds.like("a.product_name",product.getProductName());
        }

        if(!StringUtils.isEmpty(product.getClassifyName())){
            conds.like("a.classify_name",product.getClassifyName());
        }
        Sort sort = new Sort("a.create_time", OrderType.DESC);
        List<Product> list = productService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Product.class, response).toExcel(list, "产品信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = PRODUCT_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Product.class, response).toExcel(null, "产品信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = PRODUCT_EDIT)
    @ResponseBody
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        JSONObject retJson = new JSONObject();
        StringBuffer sbClassify = new StringBuffer();
        boolean classify = true;
        Long accountId = UserUtils.getmpaccounts(request);
        String ruKuNumber = codingruleUtils.getNumber(accountId, ProductIntoWareroom.class.getName());
        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 -> {
                Product product = new Product();
                if(!StringUtils.isEmpty(rowData.get(0))){
                    Conds conds = new Conds();
                    conds.equal("a.classify_number",rowData.get(0));
                    conds.equal("a.del_flag","0");
                    Productclassify productClassifyParent = productclassifyService.fetchSearchByConds(conds);
                    if(productClassifyParent != null){
                        //产品分类ID
                        product.setClassifyId(String.valueOf(productClassifyParent.getId()));
                        product.setClassifyNumber(rowData.get(0));
                    }
                }
                product.setAccountsId(accountId);
                //产品编码
                product.setProductNumber(rowData.get(1));
                //产品名称
                product.setProductName(rowData.get(2));
                // 通用名
                product.setCommonName(rowData.get(3));
                //剂型
                product.setDosagaFrom(rowData.get(4));
                //规格
                product.setFormat(rowData.get(5));
                //批准文号
                product.setApproveNumber(rowData.get(6));
                //生产企业
                product.setManufacturer(rowData.get(7));
                //推荐计量
                product.setRecommendMeasure(rowData.get(8));
                //药品简介
                product.setDescription(rowData.get(9));
                //温馨提示
                product.setTips(rowData.get(10));
                //服用类型
                product.setTakeType(rowData.get(11));
                //服用频率
                product.setTakeFrequency(rowData.get(12));
                //服用数量
                product.setTakeAmount(rowData.get(13));
                //库存
                if(StringUtils.isEmpty(rowData.get(14)) || rowData.get(14).contains("-")){
                    sbClassify.append(rowData.get(1));
                    return;
                }else{
                    product.setStock(Long.valueOf(rowData.get(14)));
                }
                //价格
                if(!StringUtils.isEmpty(rowData.get(15))){
                    product.setPrice(Double.valueOf(rowData.get(15)));
                }
                //是否为处方药
                product.setIsRs(rowData.get(16));
                //生成本次导入的入库编码
                product.setRuKuNumber(ruKuNumber);
                product.setCreateBy(UserUtils.getUser().getId());
                product.setUpdateBy(UserUtils.getUser().getId());
                productService.saveProduct(product);

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

        retJson.put("errorNo", "0");
        if(sbClassify.length()>0){
            retJson.put("errorMsg", "部分导入失败,产品编码有："+sbClassify.toString()+"; 失败原因：库存不能为空或者为负数");
        }else{
            retJson.put("errorMsg", "导入成功");
        }

        return retJson;
    }

}
