// Decompiled by Jad v1.5.7g. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi 
// Source File Name:   ProviderProductAction.java

package com.keyshop.shop.product.controller;

import com.keyshop.pub.bo.PubHibernate;
import com.keyshop.pub.controller.PubAction;
import com.keyshop.pub.controller.PubForm;
import com.keyshop.pub.model.PubBean;
import com.keyshop.pub.util.*;
import com.keyshop.pub.util.image.ImageUtil;
import com.keyshop.shop.product.bo.*;
import com.keyshop.shop.product.model.*;
import com.keyshop.shop.product.util.ProductHelper;
import com.keyshop.shop.system.model.Provider;
import com.keyshop.shop.system.util.SystemConst;
import java.io.File;
import java.util.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;

// Referenced classes of package com.keyshop.shop.product.controller:
//            ProviderProductForm, ProductCategoryForm, ProductForm

public class ProviderProductAction extends PubAction
{

    Provider provider;
    public static final String QIANTAILIST = "qiantailist";
    public boolean isRedirect;

    public ProviderProductAction()
    {
        provider = null;
        isRedirect = false;
    }

    public String getSelectSQL()
    {
        String sql = "select product from Product as product where 1=1 ";
        sql = sql + " and product.corpId='" + provider.getId() + "'";
        ProviderProductForm fpForm = (ProviderProductForm)thisform;
        Product productBean = (Product)fpForm.getBean();
        if(productBean.getName() != null && !productBean.getName().trim().equals(""))
        {
            sql = sql + " and (product.name like'%" + productBean.getName().trim() + "%'";
            sql = sql + " or product.description like'%" + productBean.getName().trim() + "%')";
        }
        if(productBean.getBrand() != null && !productBean.getBrand().trim().equals(""))
            sql = sql + " and product.brand like'%" + productBean.getBrand().trim() + "%'";
        if(fpForm.getStartUnitPrice() != null && !fpForm.getStartUnitPrice().trim().equals(""))
            sql = sql + " and product.unitPrice >= " + fpForm.getStartUnitPrice().trim();
        if(fpForm.getEndUnitPrice() != null && !fpForm.getEndUnitPrice().trim().equals(""))
            sql = sql + " and product.unitPrice <= " + fpForm.getStartUnitPrice().trim();
        sql = sql + " order by product.updateTime desc";
        return sql;
    }

    public void initClassName()
    {
        boClass = "com.keyshop.shop.product.bo.ProductBO";
        beanClass = "com.keyshop.shop.product.model.Product";
        formBeanClass = "com.keyshop.shop.product.controller.ProviderProductForm";
    }

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        provider = (Provider)request.getSession().getAttribute(SystemConst.PROVIDER);
        if(provider == null)
            try
            {
                response.sendRedirect("../login.jsp");
                return null;
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        return super.execute(mapping, form, request, response);
    }

    public ActionForward performEdit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        super.performEdit(mapping, form, request, response);
        ProviderProductForm pform = (ProviderProductForm)form;
        Product product = (Product)pform.getBean();
        if(product != null)
        {
            List checkCategoryIds = ProductHelper.getCategorysByProductId(product.getId());
            if(checkCategoryIds != null && checkCategoryIds.size() > 0)
            {
                String se[] = ToolUtil.ArrayToString((ArrayList)checkCategoryIds);
                pform.setSelected(se);
            }
        }
        return mapping.findForward("add");
    }

    public ActionForward performUpdateindex(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        String productId = request.getParameter("productId");
        int index = 0;
        try
        {
            ProductBO bo = new ProductBO();
            Product p = (Product)bo.get(productId);
            String strindex = request.getParameter(productId + "index");
            if(!StringUtil.isEmpty(strindex))
            {
                index = Integer.parseInt(strindex);
                p.setIndex(index);
                bo.updateBean(p);
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return super.performList(mapping, form, request, response);
    }

    public ActionForward performAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        ProductCategoryForm cform = (ProductCategoryForm)request.getSession().getAttribute("pmcCategoryForm");
        if(cform != null)
        {
            cform.setCheckCategorys(new ArrayList());
            cform.setOpenCategorys(new ArrayList());
        }
        try
        {
            if(isRedirect)
                return null;
            invokeBOClearMethod((PubForm)form);
            PubForm _tmp = (PubForm)form;
            ((PubForm)form).setPageType("add");
        }
        catch(Exception e)
        {
            generalError(request, e);
            e.printStackTrace();
            return mapping.findForward("fail");
        }
        return mapping.findForward("add");
    }

    private void vaildateImage()
    {
        ProductForm pForm = (ProductForm)thisform;
        if(pForm.getBigPicData() != null && pForm.getBigPicData().getFileSize() > 0 && !ImageUtil.validateImage(pForm.getBigPicData(), 1024, 768))
        {
            httpRequest.setAttribute("big_image_error", "true");
            pForm.setBigPicData(null);
        }
        if(pForm.getCenterPicData() != null && pForm.getCenterPicData().getFileSize() > 0 && !ImageUtil.validateImage(pForm.getCenterPicData(), 265, 245))
        {
            httpRequest.setAttribute("center_image_error", "true");
            pForm.setCenterPicData(null);
        }
        if(pForm.getSmallPicData() != null && pForm.getSmallPicData().getFileSize() > 0 && !ImageUtil.validateImage(pForm.getSmallPicData(), 115, 115))
        {
            httpRequest.setAttribute("small_image_error", "true");
            pForm.setSmallPicData(null);
        }
    }

    public ActionForward performSave(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            ProviderProductForm pForm = (ProviderProductForm)form;
            Product bean = (Product)pForm.getBean();
            if(pForm.getBigPicData() != null && pForm.getBigPicData().getFileSize() > 0)
            {
                FormFile bigPicFile = pForm.getBigPicData();
                String fileName = updateAdElement(bigPicFile, "", "big");
                bean.setBigPicture(fileName);
            }
            if(pForm.getSmallPicData() != null && pForm.getSmallPicData().getFileSize() > 0)
            {
                FormFile smallPicFile = pForm.getSmallPicData();
                String fileName = updateAdElement(smallPicFile, "", "small");
                bean.setSmallPicture(fileName);
            }
            if(pForm.getCenterPicData() != null && pForm.getCenterPicData().getFileSize() > 0)
            {
                FormFile centerPicFile = pForm.getCenterPicData();
                String fileName = updateAdElement(centerPicFile, "", "center");
                bean.setCenterPicture(fileName);
            }
            ProductBO bo = new ProductBO();
            bean.setCreateTime(DateUtil.getSysDateString());
            bean.setUpdateTime(DateUtil.getSysDateString());
            bean.setCorpId(provider.getId());
            bo.addBean(pForm.getBean());
            ProductCategoryRelationBO rbo = new ProductCategoryRelationBO();
            String selected[] = pForm.getSelected();
            if(selected != null && selected.length > 0)
            {
                for(int i = 0; i < selected.length; i++)
                {
                    ProductCategoryRelation prelation = new ProductCategoryRelation();
                    prelation.setCategoryId(selected[i]);
                    prelation.setProductId(pForm.getBean().getId());
                    rbo.addBean(prelation);
                }

            }
            if(bean.getTemplate() != null)
                updateTemplateFieldsData(request, form, bean);
            request.setAttribute("save_success", "true");
        }
        catch(Exception e)
        {
            generalError(request, e);
            return mapping.findForward("fail");
        }
        return mapping.findForward("add");
    }

    public ActionForward performUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            ProviderProductForm pForm = (ProviderProductForm)form;
            Product bean = (Product)pForm.getBean();
            String removeSmallPhoto = request.getParameter("removesmallphoto");
            if(removeSmallPhoto != null && removeSmallPhoto.equals("true"))
            {
                try
                {
                    FileUtil.deleteFile(request.getRealPath(bean.getSmallPicture()));
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
                bean.setSmallPicture(null);
            } else
            if(pForm.getSmallPicData() != null && pForm.getSmallPicData().getFileSize() > 0)
            {
                String fileName = updateAdElement(pForm.getSmallPicData(), bean.getSmallPicture(), "small");
                bean.setSmallPicture(fileName);
            }
            String removeCenterPhoto = request.getParameter("removecenterphoto");
            if(removeCenterPhoto != null && removeCenterPhoto.equals("true"))
            {
                try
                {
                    FileUtil.deleteFile(request.getRealPath(bean.getCenterPicture()));
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
                bean.setCenterPicture(null);
            } else
            if(pForm.getCenterPicData() != null && pForm.getCenterPicData().getFileSize() > 0)
            {
                String fileName = updateAdElement(pForm.getCenterPicData(), bean.getCenterPicture(), "center");
                bean.setCenterPicture(fileName);
            }
            String removeBigPhoto = request.getParameter("removebigphoto");
            if(removeBigPhoto != null && removeBigPhoto.equals("true"))
            {
                try
                {
                    FileUtil.deleteFile(request.getRealPath(bean.getBigPicture()));
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
                bean.setBigPicture(null);
            } else
            if(pForm.getBigPicData() != null && pForm.getBigPicData().getFileSize() > 0)
            {
                String fileName = updateAdElement(pForm.getBigPicData(), bean.getBigPicture(), "big");
                bean.setBigPicture(fileName);
            }
            ProductBO bo = new ProductBO();
            bean.setUpdateTime(DateUtil.getSysDateString());
            bean.setCorpId(provider.getId());
            bo.updateBean(pForm.getBean());
            String sql = " from ProductCategoryRelation as pcr where prc.productId='" + bean.getId() + "'";
            List categorys = provider.getProductCategorys();
            if(categorys != null && categorys.size() > 0)
            {
                sql = sql + " and pcr.categoryId in(";
                for(int i = 0; i < categorys.size(); i++)
                {
                    sql = sql + "'" + (String)categorys.get(i) + "'";
                    if(i != categorys.size() - 1)
                        sql = sql + ",";
                }

            }
            ProductCategoryRelationBO rbo = new ProductCategoryRelationBO();
            rbo.delete(sql);
            String selected[] = pForm.getSelected();
            if(selected != null && selected.length > 0)
            {
                for(int i = 0; i < selected.length; i++)
                {
                    ProductCategoryRelation prelation = new ProductCategoryRelation();
                    prelation.setCategoryId(selected[i]);
                    prelation.setProductId(pForm.getBean().getId());
                    rbo.addBean(prelation);
                }

            }
            if(bean.getTemplate() != null)
                updateTemplateFieldsData(request, form, bean);
            request.setAttribute("update_success", "true");
        }
        catch(Exception e)
        {
            generalError(request, e);
            return mapping.findForward("fail");
        }
        return mapping.findForward("edit");
    }

    public ActionForward performChangetemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        return mapping.findForward("add");
    }

    public ActionForward performRemove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            if(isRedirect)
                return null;
            ProviderProductForm pform = (ProviderProductForm)form;
            String selected[] = pform.getSelected();
            ProductBO bo = new ProductBO();
            if(selected != null && selected.length > 0)
            {
                for(int i = 0; i < selected.length; i++)
                {
                    String sel = selected[i];
                    try
                    {
                        bo.deleteById(sel);
                        bo.delete("from TemplateTextField field where field.productId='" + sel + "'");
                        bo.delete("from TemplateBlobField field where field.productId='" + sel + "'");
                        bo.delete("from ProductCategoryRelation relation where relation.productId='" + sel + "'");
                        bo.delete("from ProductRelation relation where relation.productId='" + sel + "' or relation.reproductId='" + sel + "'");
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }

            }
            return performList(mapping, form, request, response);
        }
        catch(Exception e)
        {
            generalError(request, e);
        }
        return mapping.findForward("fail");
    }

    protected boolean isObjectExisted(PubBean bean)
    {
        return false;
    }

    private void updateBlobField(Product bean, HttpServletRequest request, TemplateBlobFieldBO bo, TemplateBlobField field, Hashtable files)
    {
        try
        {
            field.setProductId(bean.getId());
            String removePhoto = request.getParameter("removephoto" + field.getFieldId());
            if(removePhoto != null && removePhoto.equals("true"))
            {
                try
                {
                    FileUtil.deleteFile(request.getRealPath(field.getFieldValue()));
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
                field.setFieldValue(null);
                if(!StringUtil.isEmpty(field.getId()))
                {
                    bo.updateBean(field);
                    return;
                }
            }
            FormFile formFile = (FormFile)files.get(field.getFieldId());
            if(formFile != null && formFile.getFileData() != null && formFile.getFileData().length > 0)
            {
                String fileName = updateAdElement(formFile, field.getFieldValue(), field.getId());
                field.setFieldValue(fileName);
                if(StringUtil.isEmpty(field.getId()))
                    bo.addBean(field);
                else
                    bo.updateBean(field);
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    private void updateTextField(Product bean, HttpServletRequest request, TemplateTextFieldBO bo, TemplateTextField field, Hashtable files)
    {
        try
        {
            String fieldValue = request.getParameter(field.getFieldId());
            field.setFieldValue(fieldValue);
            field.setProductId(bean.getId());
            if(StringUtil.isEmpty(field.getId()))
                bo.addBean(field);
            else
                bo.updateBean(field);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    private void updateTemplateFieldsData(HttpServletRequest request, ActionForm form, Product bean)
        throws Exception
    {
        if(bean.getTemplate() == null)
            return;
        TemplateTextFieldBO templateTextFieldBo = new TemplateTextFieldBO();
        TemplateBlobFieldBO templateBlobFieldBo = new TemplateBlobFieldBO();
        Hashtable files = null;
        if(form.getMultipartRequestHandler() != null)
            files = form.getMultipartRequestHandler().getFileElements();
        List templateCategorys = ProductHelper.getTemplateCategorys();
        if(templateCategorys != null && templateCategorys.size() > 0)
        {
            for(int i = 0; i < templateCategorys.size(); i++)
            {
                TemplateCategory category = (TemplateCategory)templateCategorys.get(i);
                List fieldDatas = bean.getFieldsData(category.getId(), category.getType());
                for(Iterator it = fieldDatas.iterator(); it.hasNext();)
                    if("img".equals(category.getType()) && files != null && files.size() > 0)
                    {
                        TemplateBlobField blobField = (TemplateBlobField)it.next();
                        updateBlobField(bean, request, templateBlobFieldBo, blobField, files);
                    } else
                    {
                        TemplateTextField textField = (TemplateTextField)it.next();
                        updateTextField(bean, request, templateTextFieldBo, textField, files);
                    }

            }

        }
    }

    private List getRelationProducts(String productId)
    {
        if(StringUtil.isEmpty(productId))
            return null;
        String sql = "select distinct p.id, p.name,p.unitPrice, p.status, p.key, p.createTime, p.updateTime";
        sql = sql + " from Product as p, ProductRelation r where 1=1 ";
        sql = sql + "  and p.id=r.reproductId";
        sql = sql + " and r.productId='" + productId + "'";
        try
        {
            PubHibernate bo = new PubHibernate();
            List list = bo.list(sql);
            list = convertProductList(list);
            if(list != null && list.size() > 0)
                httpRequest.setAttribute("existedlist", list);
            else
                httpRequest.setAttribute("existedlist", new ArrayList());
            return list;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

    private List convertProductList(List searchResult)
    {
        if(searchResult == null || searchResult.size() <= 0)
            return new ArrayList();
        List rlist = new ArrayList();
        for(int i = 0; i < searchResult.size(); i++)
        {
            Product p = new Product();
            Object o[] = (Object[])searchResult.get(i);
            String id = (String)o[0];
            String name = (String)o[1];
            Double unitPrice = (Double)o[2];
            Boolean status = (Boolean)o[3];
            String key = (String)o[4];
            String createTime = (String)o[5];
            String updateTime = (String)o[6];
            p.setId(id);
            p.setName(name);
            p.setUnitPrice(unitPrice.doubleValue());
            p.setStatus(status.booleanValue());
            p.setKey(key);
            p.setCreateTime(createTime);
            p.setUpdateTime(updateTime);
            rlist.add(p);
        }

        return rlist;
    }

    private String updateAdElement(FormFile file, String oldFileName, String type)
    {
        shopResource = ResourceBundle.getBundle("resources.shopapplication", new Locale("", ""));
        String fileRoot = shopResource.getString("product.file.root");
        try
        {
            if(file != null && file.getFileData() != null && file.getFileSize() > 0)
            {
                String currentPath = fileRoot + DateUtil.getNoSpSysDateString() + "/" + type + "/";
                String currentRoot = httpRequest.getRealPath(currentPath);
                String oldFilePath = "";
                if(!StringUtil.isEmpty(oldFileName))
                    oldFilePath = httpRequest.getRealPath(oldFileName);
                File currentFolder = new File(currentRoot);
                if(!currentFolder.exists())
                    currentFolder.mkdirs();
                if(file != null && file.getFileSize() > 0)
                {
                    String fileName = FileUtil.updateImageFileByRelPath(currentRoot + "/", oldFilePath, file);
                    return currentPath + fileName;
                }
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return "";
    }
}
