package com.sifang.modules.supply.stock.controller;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.config.JedisCacheService;
import com.sifang.modules.q7link.dao.CrmSupplyMaterialProjectDao;
import com.sifang.modules.q7link.service.CrmSupplyMaterialProjectPriceService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.service.CrmSupplyMaterialBrandService;
import com.sifang.modules.supply.setting.service.CrmSupplyMaterialSettingService;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.stock.service.SupplyMaterialService;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.stock.vo.PriceVo;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import com.sifang.modules.task.DateTask;
import net.sf.json.JSONObject;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/material")
public class SupplyMaterialController extends BaseExceptionController {

    @Autowired
    private SupplyMaterialService materialService;
    @Autowired
    CrmSupplyMaterialSettingService supplyMaterialSettingService;
    @Autowired
    private CrmSupplyMaterialBrandService brandService;
    @Autowired
    private CrmSupplyMaterialProjectPriceService materialProjectPriceService;
    @Autowired
    private CrmSupplyMaterialProjectDao projectDao;

    @Resource
    private JedisCacheService redis;

    /**
     * 供应商库存页面
    */
    @RequestMapping(value = "findMaterialList")
    public String findMaterialList(HttpServletRequest request, Model model){
        MaterialUtils.returnModelMaterial(model,"3","");
        return "modules/supply/material/findMaterialList";
    }


    @ResponseBody
    @RequestMapping(value = "findMaterialPage")
    public Object findMaterialPage(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        materialService.findMaterialPage(page,map);
        return page.renderJson();
    }

    /**
     * 导入弹框
    */
    @RequestMapping(value = "importMaterialForm")
    public String importMaterialForm(){
        return "modules/supply/material/importMaterial";
    }

    /**
     * 新增
    */
    @RequestMapping(value = "addMateriaForm")
    public String addMateriaForm(Model model){
        //获取物料类型
        model.addAttribute("types",MaterialUtils.findMaterialType());
        List<Record> brands= brandService.getAllMaterialBrand();
        model.addAttribute("brands",brands);
        return "modules/supply/material/addMateria";
    }

    @ResponseBody
    @RequestMapping(value = "saveMaterial")
    public Result saveMaterial(HttpServletRequest request, SupplyMaterial material){
        materialService.saveOreditMaterial(material);
       return  Result.ok();
    }

    /**
     * 修改
     */
    @RequestMapping(value = "editMateriaForm")
    public String editMateriaForm(Model model,HttpServletRequest request){
        //获取物料类型
        model.addAttribute("types",MaterialUtils.findMaterialType());
        String id = request.getParameter("id");
        SupplyMaterial material = materialService.getById(id);
        model.addAttribute("material",material);
        List<Record> unitList = supplyMaterialSettingService.listMaterialUnit(material.getMaterialTypeId());
        model.addAttribute("unitList",unitList);
        model.addAttribute("brands", brandService.getListByTypeId(material.getMaterialTypeId()));
        return "modules/supply/material/editMateria";
    }

    /**
     * 查看详情
    */
    @RequestMapping(value = "detailMaterial")
    public String detailMaterial(HttpServletRequest request,Model model){

        String id = request.getParameter("id");

        SupplyMaterial material = materialService.getById(id);
        model.addAttribute("material",material);
        MaterialUtils.returnModelMaterial(model,"1","");
        return "modules/supply/material/materiaForm";
    }

    /**
     * 删除
    */
    @ResponseBody
    @RequestMapping(value = "deleteMaterial")
    public Result deleteMaterial(HttpServletRequest request){
        String ids = request.getParameter("ids");
        if(StringUtil.isBlank(ids)){
            return Result.fail("2003","参数为空");
        }
        return  materialService.deleteMaterial(ids);
    }
    /**
     * 同步物品定时任务
     */
    @ResponseBody
    @RequestMapping(value = "synchronize")
    public Result synchronize(HttpServletRequest request){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String  synchronize =redis.get("synchronizeProject");
                    System.out.println("synchronize--->>>>"+synchronize);
                    if(StringUtil.isBlank(synchronize)){
                        redis.setex("synchronizeProject",15000,"1");
                        try {
                            DateTask task= new DateTask();
                            task.queryMaterialInfo();
                        }catch (Exception e){
                            e.printStackTrace();
                        }finally {
                            redis.setex("synchronizeProject",1,"1");
                        }

                    }
                } catch (Exception r) {
                    r.printStackTrace();
                }

            }
        }).start();


        return  Result.ok();
    }

    /**
     * 修改
     */
    @RequestMapping(value = "synchronizeProject")
    public String synchronizeProject(Model model,HttpServletRequest request){
        String  synchronizeProjectTime="";//redis.get("synchronizeProjectTime");
        String querysql="select CAST(max(create_time)  AS CHAR) as  createTime from crm_supply_material_project_price";
        List<Record> records = Db.find(querysql);
        for(Record rd:records){
            synchronizeProjectTime=rd.get("createTime");
        }
        String  synchronize =redis.get("synchronizeProject");
        model.addAttribute("synchronizeProjectTime", StringUtil.isNotBlank(synchronizeProjectTime)?"上次同步时间："+synchronizeProjectTime:"");
        model.addAttribute("msg", StringUtil.isNotBlank(synchronize)&&"1".equals(synchronize)?"物料价格正在同步中":"");
        model.addAttribute("synchronize", synchronize);
        return "modules/supply/material/synchronizeProject";
    }



    /**
     * 禁用
     */
    @ResponseBody
    @RequestMapping(value = "disableMaterial")
    public Result disableMaterial(HttpServletRequest request,String id){
        if(StringUtil.isBlank(id)){
            return Result.fail("2003","参数为空");
        }
        return  materialService.disableMaterial(id);
    }

    /**
     * 启用
     */
    @ResponseBody
    @RequestMapping(value = "enableMaterial")
    public Result enableMaterial(HttpServletRequest request,String id){
        if(StringUtil.isBlank(id)){
            return Result.fail("2003","参数为空");
        }
        return  materialService.enableMaterial(id);
    }


    @ResponseBody
    @RequestMapping(value = "checkImportMaterial")
    public Object checkImportMaterial(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        Map<String, Object> retMap = materialService.checkImportMaterial(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }


    @RequestMapping(value = "importMaterial")
    @ResponseBody
    public JSONObject importMaterial(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        Map<String, Object> retMap = materialService.importMaterial(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    /**
     * 根据物料编号 或者物料描述查询物料
    */
    @ResponseBody
    @RequestMapping("findMaterialByCode")
    public Object findMaterialByCode(HttpServletRequest request){
        String code = request.getParameter("code");
        String supplierId = request.getParameter("supplierId");
        String remarks = request.getParameter("remarks");
        String materialProperties=request.getParameter("materialProperties");
        if(StringUtil.isBlank(code)&& StringUtil.isBlank(remarks)){
            return Result.fail("2003","参数为空");
        }

        return materialService.findMaterialByCode(code,remarks,materialProperties,supplierId);
    }

    /**
     * 查看零售价
     */
    @RequestMapping(value = "detailPrice")
    public String detailPrice(HttpServletRequest request,Model model){
        String qqCode = request.getParameter("code");
        List<Record> records = materialProjectPriceService.findPriceByQqMaterialCode(qqCode);
        List<PriceVo> list = new ArrayList<>();
        for (Record record : records) {
            String qqProjectCode = record.getStr("qq_project_code");
            BigDecimal price = record.getBigDecimal("price");
            Record project = projectDao.queryByCode(qqProjectCode);
            if (project == null) {
                continue;
            }
            PriceVo priceVo = new PriceVo();
            priceVo.setProjectCode(qqProjectCode);
            priceVo.setTaxPrice(price);
            priceVo.setProjectName(project.getStr("name"));
            list.add(priceVo);
        }
        model.addAttribute("list",list);
        return "modules/supply/material/detailPrice";
    }
}
