package lingtao.net.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lingtao.net.Factory.PricingStrategy;
import lingtao.net.Factory.PricingStrategyFactory;
import lingtao.net.bean.Msg;
import lingtao.net.bean.Product;
import lingtao.net.bean.SysDictSearchPro;
import lingtao.net.bean.SysUser;
import lingtao.net.service.PriceService;
import lingtao.net.service.ProductService;
import lingtao.net.service.QuoteLogService;
import lingtao.net.util.HuaFangPriceUtil;
import lingtao.net.vo.PricingListVo;
import lingtao.net.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private QuoteLogService quoteLogService;

    @Autowired
    private PriceService priceService;

    // 价格跳转页面
    @RequestMapping("/product/index")
    public void index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.sendRedirect(request.getContextPath() + "/views/system/product/product.jsp");
    }

    /**
     * 查询所有价格
     */
    @RequestMapping("/getProductList")
    @ResponseBody
    private Msg IPList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", defaultValue = "10") Integer limit, Product product) {
        PageHelper.startPage(page, limit);
        List<Product> list = productService.getProductList(product);
        PageInfo<Product> pageInfo = new PageInfo<Product>(list);
        return Msg.success().add("list", pageInfo);
    }

    /**
     * 修改价格
     */
    @RequestMapping("/updatePriceById")
    public Msg updatePriceById(@RequestParam(value = "proId") int proId, @RequestParam(value = "field") String field,
                               @RequestParam(value = "value") String value) {
        return productService.updatePriceById(proId, field, value);
    }

    /**
     * 计算价格
     *
     * @param product
     * @return
     */
    @RequestMapping("/getThanSum")
    public Msg thanPrice(Product product, HttpServletRequest request) {
        SysUser user = (SysUser) request.getSession().getAttribute("USER_SESSION");
    /*if (StringUtils.isEmpty(product.getWangwang().trim()) && user.getRole().contains("999")
        && !user.getRole().contains("1049")) {
      return Msg.fail("请填写客户旺旺！");
    }*/
        if ("帆布".equals(product.getProTypeValue())) {
            if ("套餐".equals(product.getStickerKind())) {
                product.setCount(1);
            }
        } else {
            if (StringUtils.isEmpty(product.getCount()) || product.getCount() <= 0) {
                return Msg.fail("数量必须大于0");
            }
        }
        // 透明不干胶进去后kindValue 会为1，记录起来，查询日志
        String toumingKind = "";
        if ("0".equals(product.getProTypeValue()) && "2".equals(product.getKindValue())) {
            toumingKind = product.getKindValue();
        }
        if ("18".equals(product.getProTypeValue()) && "4".equals(product.getKindValue())) {
            product.setCount(Integer.valueOf(request.getParameter("count1")));
        }
        product.setRole(user.getRole());

        if ("菜单".equals(product.getProTypeLabel())) {
            if (product.getSize1() != null) {
                product.setSize(product.getSize1().replace(",", ""));
            }
            String s = request.getParameter("kindValue5");
            product.setKind1Value(s);
            product.setSize(request.getParameter("ui_menu_size"));
        } else if ("4".equals(product.getProTypeValue()) && "9".equals(product.getKind())) {
            product.setSize(request.getParameter("ui_shk_size"));
        }

        if (user.getRole().indexOf("1010") > -1) {
            if ("0".equals(product.getKindValue()) && "专版打印".equals(product.getStickerKind())) {
                double len = Double.valueOf(product.getSize().substring(0, product.getSize().indexOf("*")));
                double wid = Double.valueOf(product.getSize().substring(product.getSize().indexOf("*") + 1));
                if ((len <= 5 && wid < 4) || (len < 4 && wid <= 5)) {
                    product.setSize("5*4");
                }
            }
        } else {
            if (product.getNumber() != null && product.getNumber() > 1) {
//                if ("专版打印".equals(product.getStickerKind()) || "少数量".equals(product.getCouponKind())) {
                if (request.getParameter("desType") != null && !"".equals(request.getParameter("desType"))) {
                    product.setP(Integer.valueOf(request.getParameter("desType")));
                }
//                }
            }
        }
        List<Product> proList = productService.getThanPrice(product, user.getRole());

        if (proList == null) {
            return Msg.fail("暂无报价");
        }
        //银瑾单独报价
        if (user.getRole().indexOf("1010") > -1) {
            double otherPrice = 0;
      /*if("5".equals(product.getKind())) {
        for (Product list : proList) {
          list.setPrice(list.getPrice() + 30);
        }
      }else if("帆布".equals(product.getProTypeValue())) {
        for (Product list : proList) {
          otherPrice = Math.floor(list.getPrice() + 5);
          list.setPrice(otherPrice > 40 ? otherPrice : 40);
          if(product.getNumber() > 1) {
            list.setPrice(Math.floor(list.getPrice() + 2 * (product.getNumber()-1)));
          }
        }
      }else */
            if ("22".equals(product.getProTypeValue())) {
                for (Product list : proList) {
                    list.setPrice(list.getPrice() + 50);
                }
            } else if ("桌布".equals(product.getProTypeValue())) {
                for (Product list : proList) {
                    list.setPrice(list.getPrice() + 30);
                }
            } else if ("13".equals(product.getProTypeValue())) {
                for (Product list : proList) {
                    list.setPrice(list.getPrice() + 80);
                }
            } else if ("亚克力".equals(product.getProTypeValue())) {
                for (Product list : proList) {
                    list.setPrice(list.getPrice() + 40);
                }
            } else if ("11".equals(product.getProTypeValue())) {
                for (Product list : proList) {
                    list.setPrice(list.getPrice() + 50);
                }
            } else if ("0".equals(product.getProTypeValue())) {
                if ("0".equals(product.getKindValue()) && "常用种类".equals(product.getStickerKind())) {
                    double len = Double.valueOf(product.getSize().substring(0, product.getSize().indexOf("*")));
                    ;
                    double wid = Double.valueOf(product.getSize().substring(product.getSize().indexOf("*") + 1));
                    if ((len <= 5 && wid < 4) || (len < 4 && wid <= 5)) {
                        double priceArr[] = {45, 50, 75, 90, 170, 260, 440, 620, 810, 1000};
                        double countArr[] = {500, 1000, 2000, 3000, 5000, 10000, 20000, 30000, 40000, 50000};
                        for (Product list : proList) {
                            for (int i = 0; i < countArr.length; i++) {
                                if (countArr[i] < list.getCount()) {
                                    continue;
                                }
                                list.setPrice(priceArr[i]);
                                break;
                            }

                        }
                    }
                } else if ("11".equals(product.getKindValue()) || "布纹纸超白".equals(product.getKindValue())) {
                    for (Product list : proList) {
                        list.setPrice(Math.floor(list.getPrice() * 1.5));
                    }
                } else if ("拉丝金".equals(product.getKindValue()) || "拉丝银".equals(product.getKindValue())) {
                    for (Product list : proList) {
                        list.setPrice(Math.floor(list.getPrice() + 60));
                    }
                }
            } else if ("金属标".equals(product.getProTypeValue()) && "UV转印贴".equals(product.getKind())) {
                for (Product list : proList) {
                    if (list.getCount() > 500) {
                        list.setPrice(Math.floor(list.getPrice() * 0.95));
                    } else {
                        list.setPrice(Math.floor(list.getPrice() * 0.9));
                    }
                }
            } else if ("服装吊牌".equals(product.getProTypeValue()) && "异形模切".equals(product.getCraftQie())) {
                for (Product list : proList) {
                    list.setPrice(list.getPrice() + 50);
                }
            }
        }

        if ("0".equals(product.getProTypeValue())) {
            if ("5".equals(product.getKindValue()) && proList == null) {
                if (StringUtils.isEmpty(product.getAotu())) {
                    return Msg.fail("哑金不干胶该尺寸无法制作,最大做到 39*27 cm");
                } /*else {
          return Msg.fail("哑金不干胶带凹凸工艺该尺寸无法制作         (1*1CM至11*11CM;10*6至12*8CM;20*4以内)");
        }*/
            } else if ("易碎纸不干胶".equals(product.getKindValue()) && proList == null) {
                return Msg.fail("易碎纸不干胶该尺寸无法制作,最大做到 42*38 cm");
            } else if (("拉丝金".equals(product.getKindValue()) || "拉丝银".equals(product.getKindValue()))
                    && proList == null) {
                return Msg.fail("拉丝金/银该尺寸无法制作,最大做到 42*38 cm");
            } else if ("格底珠光膜".equals(product.getKindValue()) && proList == null) {
                return Msg.fail("格底珠光膜该尺寸无法制作,最大做到 42*38 cm");
            }
            if (proList == null) {
                if ("少数量".contentEquals(product.getStickerKind())) {
                    return Msg.fail("少数量最大做到 42*28.5 cm");
                }
                /*return Msg.fail("该工艺、该尺寸无法制作，请单独报价");*/
            }
        } else if ("20".equals(product.getProTypeValue())) {
            if (proList == null && "0".equals(product.getKindValue())) {
                return Msg.fail("双插盒该尺寸展开超过650*500MM，请另行报价");
            } else if (proList == null && "1".equals(product.getKindValue())) {
                return Msg.fail("飞机盒该尺寸展开超过900*600MM，请另行报价");
            }
        }

        if (!StringUtils.isEmpty(toumingKind)) {
            product.setKindValue(toumingKind);
        }
        // 插入操作日志
//        String log = quoteLogService.log(product, request, proList);
        if (user == null) {
            return Msg.fail("登录信息失效~请刷新页面！");
        }

        // 把角色存入，前台判断，区分不同价格
        for (Product p : proList) {
//            p.setPrice(Math.ceil(p.getPrice() * 1.3));
            p.setRole(user.getRole());
        }

        if (product.getKindValue() != null) {//判断是否大店报不干胶价格
      /*if(product.getKindValue().equals("0")) {
        double width = 0, length = 0;
        if(product.getWidth() != null) {
          width = product.getWidth();
        }
        if(product.getLength() != null) {
          length = product.getLength();
        }
        String role = user.getRole();
        if(length < width) {
          length = product.getWidth();
          width = product.getLength();
        }
        if(width == 0 && length == 0) {
        }else if((length <= 5 && width <= 4)) {
          String tang = product.getCraftTang();
          if(AStickersPrice.f_getRole(role) == 1 && tang == null) {
            List<Product> price = new ArrayList<Product>();
            if(length == 1 && width == 1) {
              int priceArr[] = {30, 35, 50, 55, 65, 90, 135, 185, 235, 285};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 2 && width == 1) {
              int priceArr[] = {35, 40, 55, 60, 70, 95, 140, 190, 240, 290};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 3 && width == 1) {
              int priceArr[] = {35, 40, 55, 70, 80, 125, 205, 290, 370, 455};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 4 && width == 1) {
              int priceArr[] = {35, 40, 55, 70, 80, 125, 205, 290, 370, 455};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 5 && width == 1) {
              int priceArr[] = {35, 40, 55, 70, 80, 125, 205, 290, 370, 455};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 2 && width == 2) {
              int priceArr[] = {35, 40, 55, 70, 80, 125, 205, 290, 370, 455};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 3 && width == 2) {
              int priceArr[] = {35, 40, 55, 70, 80, 125, 205, 290, 370, 455};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 4 && width == 2) {
              int priceArr[] = {35, 40, 55, 70, 110, 170, 290, 410, 535, 665};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 5 && width == 2) {
              int priceArr[] = {35, 40, 55, 70, 110, 170, 290, 410, 535, 665};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 3 && width == 3) {
              int priceArr[] = {35, 40, 55, 70, 110, 170, 290, 410, 535, 665};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 4 && width == 3) {
              int priceArr[] = {35, 40, 55, 70, 110, 170, 290, 410, 535, 665};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 5 && width == 3) {
              int priceArr[] = {35, 40, 55, 70, 110, 170, 290, 410, 535, 665};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 4 && width == 4) {
              int priceArr[] = {35, 40, 55, 70, 110, 170, 290, 410, 535, 665};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }else if(length == 5 && width == 4) {
              int priceArr[] = {35, 40, 55, 70, 150, 240, 420, 600, 790, 980};
              price = f_getPrice( priceArr, product.getCount(), product.getCraftMo());
            }

            if (proList.size() >= 4) {
              proList = proList.subList(0, 4);
            }

            for(int i = 0; i < price.size(); i ++){
              if(product.getNumber() > 1) {
                proList.get(i).setPrice(price.get(i).getPrice() * product.getNumber());
              }else {
                proList.get(i).setPrice(price.get(i).getPrice());
              }
            }
          }
        }
      }elseif(user.getRole().indexOf("1033") > 0 && product.getProTypeValue().equals("17")) {
        if(product.getKindValue().equals("6")) {
          for (Product products : proList) {
            products.setPrice(Math.floor(products.getPrice() * 0.88));
          }
        }
      } */
        }


        return Msg.success().add("proList", proList);
    }

    @RequestMapping("/getProductPrice")
    public Msg getProductPrice(Product product, HttpServletRequest request) {
        SysUser user = (SysUser) request.getSession().getAttribute("USER_SESSION");


        if (StringUtils.isEmpty(product.getCount()) || product.getCount() <= 0) {
            return Msg.fail("数量必须大于0");
        }
        String size = product.getSize();

        if (("17".equals(product.getProTypeValue()) && "6".equals(product.getKindValue())) || ("手拉旗".equals(product.getProTypeValue()) && "常规".equals(product.getStickerKind()))) {
            if (!StringUtils.isEmpty(size)) {
                String sizeList[] = size.split(",");
                size = sizeList[0];
            }
            product.setLength(Double.valueOf(size));
        } else if (!StringUtils.isEmpty(size)) {
            product.setLength(Double.valueOf(size.substring(0, size.indexOf("*"))));
            String other_size = size;
            if (size.contains(",")) {
                size = size.split(",")[0];
            }
            if (size.indexOf(("*"), size.indexOf("*") + 1) == -1) {
                product.setWidth(Double.valueOf(size.substring(size.indexOf("*") + 1)));
            } else {
                product.setWidth(Double.valueOf(size.substring(size.indexOf("*") + 1, size.indexOf(("*"), size.indexOf("*") + 1))));
                product.setLength(Math.abs(Double.parseDouble(size.substring(size.indexOf(("*"), size.indexOf("*") + 1) + 1))));
            }
        }
        product.setRole(user.getRole());
        PricingStrategy pricingStrategy = PricingStrategyFactory.getStrategy(product.getProTypeValue());
        assert pricingStrategy != null;
        PricingListVo listvo = pricingStrategy.calculatePrice(product, user.getRole());
        if (listvo.getCode() != 0) {
            return Msg.fail(listvo.getMsg());
        }
        List<ProductVo> proList = listvo.getProList();
        if (proList == null || proList.size() == 0 || proList.get(0).getPrice() == 0) {
            return Msg.fail("暂无报价");
        }
        PricingListVo result = priceService.getAddressPrice(product, proList);

        if (result.getCode() != 0) {
            return Msg.fail(result.getMsg());
        }
        proList = result.getProList();

        String log = quoteLogService.log(product, request, new ArrayList<>());

        if ("登陆失效".equals(log)) {
            return Msg.fail("登录信息失效~请刷新页面！");
        }

        // 把角色存入，前台判断，区分不同价格
        for (ProductVo p : proList) {
            p.setRole(user.getRole());
        }

        return Msg.success().add("proList", proList);
    }

    @RequestMapping("/getProductCastPrice")
    public Msg getProductCastPrice(Product product, HttpServletRequest request) {
        SysUser user = (SysUser) request.getSession().getAttribute("USER_SESSION");

        if (StringUtils.isEmpty(product.getCount()) || product.getCount() <= 0) {
            return Msg.fail("数量必须大于0");
        }
        String size = product.getSize();

        if (!StringUtils.isEmpty(size)) {
            product.setLength(Double.valueOf(size.substring(0, size.indexOf("*"))));
            String other_size = size;
            if (size.contains(",")) {
                size = size.split(",")[0];
            }
            if (size.indexOf(("*"), size.indexOf("*") + 1) == -1) {
                product.setWidth(Double.valueOf(size.substring(size.indexOf("*") + 1)));
            } else {
                product.setWidth(Double.valueOf(size.substring(size.indexOf("*") + 1, size.indexOf(("*"), size.indexOf("*") + 1))));
                product.setLength(Math.abs(Double.parseDouble(size.substring(size.indexOf(("*"), size.indexOf("*") + 1) + 1))));
            }
        }
        product.setRole(user.getRole());

        PricingListVo listvo = priceService.getCostPrice(product);
        if (listvo.getCode() != 0) {
            return Msg.fail(listvo.getMsg());
        }
        List<ProductVo> proList = listvo.getProList();
        if (proList == null || proList.size() == 0 || proList.get(0).getPrice() == 0) {
            return Msg.fail("暂无报价");
        }

        if (listvo.getCode() != 0) {
            return Msg.fail(listvo.getMsg());
        }
        proList = listvo.getProList();

        // 把角色存入，前台判断，区分不同价格
        for (ProductVo p : proList) {
            p.setRole(user.getRole());
        }

        return Msg.success().add("proList", proList);
    }

  /*public List<Product> f_getPrice( int priceArr[], int count, String craftMo) {
    List<Product> list = new ArrayList<Product>();
    Product p = new Product();
    int countArr[] = { 500, 1000, 2000, 3000, 5000, 10000, 20000, 30000, 40000, 50000 };
    for(int i = 0; i < countArr.length; i++) {
      if(countArr[i] < count || list.size() > 3) {
        continue;
      }
      p = new Product();
      p.setCount(countArr[i]);
      if(craftMo.equals("覆哑膜")) {
        p.setPrice(Math.ceil(Double.valueOf(priceArr[i]) * 1.2));
      }else {
        p.setPrice(Double.valueOf(priceArr[i]));
      }

      list.add(p);
    }

    return list;
  }*/

    /**
     * 根据产品种类获取材质
     *
     * @param proTypeValue
     * @return
     */
    @RequestMapping(value = "/getKindsByPro")
    public Map<String, String> kindList(@RequestParam("proTypeValue") String proTypeValue) {
        Map<String, String> map = new HashMap<String, String>();
        List<Product> proList = productService.getKindsByPro(proTypeValue);
        for (Product product : proList) {
            map.put(product.getKindValue(), product.getKindLabel());
        }
        return map;
    }

    /**
     * 根据用户搜索的产品名称获取产品
     */
    @RequestMapping(value = "/getSearchPro")
    public List<SysDictSearchPro> searchPro(@RequestParam("likeProTypeLabel") String likeProTypeLabel)
            throws Exception {
        List<SysDictSearchPro> proList = productService.searchPro(likeProTypeLabel);
        return proList;
    }

    /**
     * 价格文件上传
     */
    @RequestMapping(value = "/priceUpload")
    public Msg uploadExcel(@RequestParam("file") MultipartFile file) throws Exception {
        System.out.println("进来了");
        productService.ajaxUploadExcel(file);
        return Msg.success();
    }

}
