package com.cftech.brand.apply.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.brand.apply.detail.model.BrandApplyDetail;
import com.cftech.brand.apply.detail.model.BrandApplyDetailVo;
import com.cftech.brand.apply.detail.service.BrandApplyDetailService;
import com.cftech.brand.apply.model.BrandApply;
import com.cftech.brand.apply.model.BrandApplyProduct;
import com.cftech.brand.apply.model.BrandApplyVo;
import com.cftech.brand.apply.service.BrandApplyProductService;
import com.cftech.brand.apply.service.BrandApplyService;
import com.cftech.brand.department.model.BrandDepartment;
import com.cftech.brand.department.service.BrandDepartmentService;
import com.cftech.brand.emp.model.BrandEmp;
import com.cftech.brand.emp.service.BrandEmpService;
import com.cftech.brand.market.model.BrandMarketLeader;
import com.cftech.brand.market.service.BrandMarketLeaderService;
import com.cftech.brand.util.BrandApplyTempMsgUtil;
import com.cftech.brand.util.BrandExportUtil;
import com.cftech.common.send.util.CommonSendUtils;
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.*;
import com.cftech.shop.qrcode.service.WxQrcodeService;
import com.cftech.shop.qrcode.util.WxQrcodeUtil;
import com.cftech.showroom.appform.util.DocToPdf;
import com.cftech.showroom.svideo.model.Svideo;
import com.cftech.showroom.svideo.service.SvideoService;
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.mp.api.wxaccount.model.WxQrcode;
import org.mp.api.wxsendmsg.JwTemplateMessageAPI;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
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.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 品牌申请Controller
 *
 * 权限字符串说明:
 * 查看:public static final String BRANDAPPLY_VIEW = "qy:brandApply:view"
 * 查看:public static final String BRANDAPPLY_EDIT = "qy:brandApply:edit"
 *
 * @author faye
 * @date 2020/01/14
 */
@Slf4j
@Controller
@RequestMapping("/a/brandApply")
public class BrandApplyController {

    public static final String BRANDAPPLY_VIEW = "qy:brandApply:view";
    public static final String BRANDAPPLY_EDIT = "qy:brandApply:edit";

    @Autowired
    private BrandApplyService brandApplyService;
    @Autowired
    private CodingruleUtils codingruleUtils;

    @Autowired
    private MpTokenUtil tokenUtil;

    @Autowired
    private WxQrcodeService wxQrcodeService;

    @Autowired
    private WxQrcodeUtil wxQrcodeUtil;

    @Autowired
    private BrandApplyDetailService detailService;

    @Autowired
    private BrandMarketLeaderService marketLeaderService;

    @Autowired
    private BrandEmpService brandEmpService;

    @Autowired
    private BrandDepartmentService departmentService;

    @Autowired
    private BrandApplyProductService brandApplyProductService;


    /**
     * 列表页面
     *
     * @param request
     * @param model
     * @return
     */
    @RequiresPermissions(value = BRANDAPPLY_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "brandApply/brandApplylist";
    }

    /**
     * 编辑页面（新增、修改）
     *
     * @param request
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions(value = BRANDAPPLY_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, Long id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Conds conds=new Conds();
            conds.equal("t.del_flag","0");
            conds.equal("t.id",id);
            List<BrandApplyVo> datas=brandApplyService.fetchSearchByPageVo(conds,null,0,0);
            if(!CollectionUtils.isEmpty(datas)){
                BrandApplyVo brandApply = datas.get(0);
                List<BrandApplyDetailVo> details=detailService.getDatabyApplyId(id);
                model.addAttribute("details",details);
                model.addAttribute("data", brandApply);
                String actInnerCost="";
                if(com.cftech.core.util.StringUtils.equals("5",brandApply.getStatus())&&brandApply.getInnerCost()!=null){
                    actInnerCost=  new BigDecimal(brandApply.getInnerCost()).multiply(new BigDecimal(brandApply.getHourlyRate()).setScale(2,BigDecimal.ROUND_HALF_UP)).toString();
                }
                model.addAttribute("actInnerCost",actInnerCost);
                List<BrandApplyProduct> brandApplyProducts = brandApplyProductService.fetchByApplyId(brandApply.getId());
                model.addAttribute("brandApplyProducts", brandApplyProducts);
            }

        }
        return "brandApply/brandApplyform";
    }

    /**
     * 提交数据（新增、修改）
     *
     * @param brandApply
     * @param model
     * @param request
     * @return
     */
    @RequiresPermissions(value = BRANDAPPLY_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(BrandApply brandApply, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            brandApply.setUpdateBy(UserUtils.getUser().getId());
            if (brandApply != null && brandApply.getId() != null) {
                brandApplyService.update(brandApply);
                rtnJson.put("errorNo", 0);
            } else {
                brandApply.setNumber(codingruleUtils.getNumber(accountsId, BrandApply.class.getName()));
                brandApply.setAccountsId(accountsId);
                brandApply.setDelFlag(false);
                brandApply.setAccountsId(UserUtils.getmpaccounts(request));
                brandApply.setCreateBy(UserUtils.getUser().getId());
                brandApplyService.save(brandApply);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            log.error("保存品牌申请异常:"+e.getMessage());
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    /**
     * 获取列表数据
     *
     * @param iDisplayStart
     * @param iDisplayLength
     * @param brandApply
     * @param request
     * @return
     */

    @RequiresPermissions(value = BRANDAPPLY_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, BrandApplyVo brandApply, HttpServletRequest request, String createTimeStr) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if (!StringUtils.isEmpty(brandApply.getNumber())) {
            conds.like("t.number", brandApply.getNumber());
        }
        if (!StringUtils.isEmpty(brandApply.getDepartmentName())) {
            conds.equal("d.name", brandApply.getDepartmentName());
        }
        if (!StringUtils.isEmpty(brandApply.getCategoryName())) {
            conds.equal("c.name", brandApply.getCategoryName());
        }
        if (!StringUtils.isEmpty(brandApply.getStatus())) {
            conds.like("t.status", brandApply.getStatus());
        }
        if (!StringUtils.isEmpty(brandApply.getName())) {
            conds.like("t.name", brandApply.getName());
        }
        if (!StringUtils.isEmpty(createTimeStr)) {
            String credateBegin = createTimeStr.split(" - ")[0];
            String credateEnd = createTimeStr.split(" - ")[1];
            conds.greatEqual("t.create_time", credateBegin);
            conds.lessEqual("t.create_time", credateEnd);
        }
        if(!StringUtils.isEmpty(brandApply.getProductName())) {
            conds.like("t.product_name", brandApply.getProductName());
        }

        if(!StringUtils.isEmpty(brandApply.getProductFormat())) {
            conds.like("t.product_format", brandApply.getProductFormat());
        }

        if(!StringUtils.isEmpty(brandApply.getProductLabel())) {
            conds.like("t.product_label", brandApply.getProductLabel());
        }
        Sort sort = new Sort("t.create_time", OrderType.DESC);

        List<BrandApplyVo> list = brandApplyService.fetchSearchByPageVo(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = brandApplyService.countVo(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

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

    //下载申请单
    @RequiresPermissions(value = BRANDAPPLY_VIEW)
    @RequestMapping(value = "/downloadcode", method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadcode(com.cftech.shop.qrcode.model.WxQrcode qrcode, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("type", "brandApply");
        com.cftech.shop.qrcode.model.WxQrcode wxQrcode = wxQrcodeService.fetchSearchByConds(conds);
        WxQrcode wxqrcode = null;
        if (wxQrcode == null) {
            try {
                Conds countConds = new Conds();
                countConds.equal("t.del_flag", 0);
                int count = wxQrcodeService.count(countConds);
                JSONObject wxObj = wxQrcodeUtil.createLimitQrcode(accountsId, Long.valueOf(count));
                if (wxObj.containsKey("ticket")) {
                    qrcode.setTicket(wxObj.getString("ticket"));
                }
                qrcode.setId(null);
                String tempTicket = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + qrcode.getTicket();
                qrcode.setCreateBy(UserUtils.getUser().getId());
                qrcode.setType("brandApply");
                qrcode.setUpdateBy(UserUtils.getUser().getId());
                qrcode.setSceneId(String.valueOf(count));
                qrcode.setBindId(0L);
                qrcode.setDelFlag(false);
                wxQrcodeService.save(qrcode);
                downPicture(request, response, tempTicket, "品牌申请二维码");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            downPicture(request, response, "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + wxQrcode.getTicket(), "品牌申请二维码");
        }
    }

    public void downPicture(HttpServletRequest request, HttpServletResponse response, String urls, String title) throws IOException {

        String prefix = "jpg";
        //获取文件
        URL url = new URL(urls);
        URLConnection conn = url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //输出流
        InputStream fs = conn.getInputStream();

        int bytesRead = 0;
        byte[] image = new byte[8192];
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(title.getBytes("gb2312"), "ISO8859-1") + "." + prefix);
        try {
            while ((bytesRead = fs.read(image, 0, 8192)) != -1) {
                response.getOutputStream().write(image, 0, bytesRead);

            }
            fs.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
    /**
     * 导出
     *
     * @param request
     * @param response
     */
    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = BRANDAPPLY_VIEW)
    public void exportExcel(HttpServletRequest request, BrandApplyVo brandApply, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountId);
        if (!StringUtils.isEmpty(brandApply.getNumber())) {
            conds.like("t.number", brandApply.getNumber());
        }
        if (!StringUtils.isEmpty(brandApply.getDepartmentName())) {
            conds.equal("d.name", brandApply.getDepartmentName());
        }
        if (!StringUtils.isEmpty(brandApply.getCategoryName())) {
            conds.equal("c.name", brandApply.getCategoryName());
        }
        if (!StringUtils.isEmpty(brandApply.getStatus())) {
            conds.like("t.status", brandApply.getStatus());
        }
        if (!StringUtils.isEmpty(brandApply.getName())) {
            conds.like("t.name", brandApply.getName());
        }
        Sort sort = new Sort("t.create_time", OrderType.DESC);

        List<BrandApplyVo> list = brandApplyService.getApplyData(null,conds, sort, 0, 0);
        BrandExportUtil.ExportBrandApply(list,response);
    }

    /**
     * 模板下载
     *
     * @param request
     * @param response
     */
    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = BRANDAPPLY_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(BrandApply.class, response).toExcel(null, "品牌申请信息");
    }
    @Autowired
    private SvideoService svideoService;


    //编辑页面（新增、修改）
    @RequiresPermissions(value = "qy:brand:agreement:view")
    @RequestMapping("/agreementform")
    public String agreementform(HttpServletRequest request, String id, String status,Model model) {
        Conds conds = new Conds();
        conds.equal("status",status);
        Svideo svideo = svideoService.fetchSearchByConds(conds);
        if(svideo!=null){
            svideo.setPersonContent(ESAPI.encoder().decodeForHTML(svideo.getPersonContent()));
            model.addAttribute("data", svideo);
        }
        return "brandApply/agreementform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = "qy:common:agreement:edit")
    @RequestMapping("/agreementFormData")
    @ResponseBody
    public JSONObject formData(Svideo svideo, Model model, HttpServletRequest request, MultipartFile videoFileAddress, Long cosconfigId) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        Map<String,Object> jsonObject=null;
        try {
            if(videoFileAddress!=null){
                jsonObject= UploadUtils.uploadImageFilesByQcloudInputStearm(request, "newRecommend",videoFileAddress,"/gogi/newReCommend/");
                String url= jsonObject.get("fileUrl")==null?"":jsonObject.get("fileUrl").toString();
                svideo.setName(url);
            }

            //删除视频
            if(StringUtils.isEmpty(svideo.getName()) && videoFileAddress==null){
                svideo.setName("");
            }
            if (svideo != null && svideo.getId() != null) {
                svideo.setUpdateBy(UserUtils.getUser().getId());
                svideoService.update(svideo);
                rtnJson.put("errorNo", 0);
            } else {
                svideo.setAccountsId(accountsId);
                svideo.setDelFlag(false);
                svideo.setAccountsId(UserUtils.getmpaccounts(request));
                svideo.setCreateBy(UserUtils.getUser().getId());
                svideo.setUpdateBy(UserUtils.getUser().getId());
                svideoService.save(svideo);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }


        return rtnJson;
    }

    /**
     * 完工
     * @return
     */
    @RequiresPermissions(value = BRANDAPPLY_EDIT)
    @RequestMapping(value = "/complete",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject compelte(Long id,String actInnerCost,String actOuterCost,String isScore) {
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try{
            BrandApply  brandApply=brandApplyService.fetchById(id);
            if(!com.cftech.core.util.StringUtils.equals("3",brandApply.getStatus())){
                rtnJson.put("errorMsg","申请单状态不可操作");
                return rtnJson;
            }
            BigDecimal innerCost=new BigDecimal(0);
            BigDecimal outerCost=new BigDecimal(0);

            if(!StringUtils.isEmpty(actInnerCost)){
                innerCost=new BigDecimal(actInnerCost).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            if(!StringUtils.isEmpty(actOuterCost)){
                outerCost=new BigDecimal(actOuterCost).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            brandApply.setStatus("5");
            brandApply.setInnerCost(innerCost.doubleValue());
            brandApply.setOuterCost(outerCost.doubleValue());
            brandApply.setTotalCost(innerCost.multiply(new BigDecimal(brandApply.getHourlyRate())).add(outerCost).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            brandApply.setIsScore(isScore);
            brandApply.setActualDeliveryDate(new Date());
            brandApplyService.update(brandApply);
            //判断是否邀请申请人评分
            if(com.cftech.core.util.StringUtils.equals("1",isScore)){
                BrandEmp emp=brandEmpService.fetchById(brandApply.getContactEmpId());
                BrandApplyTempMsgUtil.sendTemplateMsgByComplte(id,tokenUtil.getToken(brandApply.getAccountsId()),
                        brandApply.getOpenId(),brandApply.getName(),brandApply.getNumber(),
                        emp.getName(),emp.getContactInformation()  );
            }
            rtnJson.put("errorNo","0");
        }catch (Exception e){
            rtnJson.put("errorMsg","操作失败:"+e.getMessage());
                log.error("品牌申请完工操作失败"+e.getMessage());
        }
        return rtnJson;
    }

    @RequiresPermissions(value = BRANDAPPLY_EDIT)
    @RequestMapping(value = "/submitRemarks", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject submitRemarks(Long id, String text) {
        JSONObject object = new JSONObject();
        try {
            BrandApply brandApply = brandApplyService.fetchById(id);
            brandApply.setId(id);
            brandApply.setManagerRemark(text);
            brandApplyService.update(brandApply);
            object.put("errorNo", 0);
        } catch (Exception e) {
            e.printStackTrace();
            object.put("errorNo", 1);
        }
        return object;
    }

    @RequiresPermissions(value = BRANDAPPLY_EDIT)
    @RequestMapping(value = "/closeReason", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject closeReason(Long id, String text) {
        JSONObject object = new JSONObject();
        try {
            BrandApply brandApply = brandApplyService.fetchById(id);
            brandApply.setId(id);
            brandApply.setCloseReason(text);
            brandApplyService.update(brandApply);
            object.put("errorNo", 0);
        } catch (Exception e) {
            e.printStackTrace();
            object.put("errorNo", 1);
        }
        return object;
    }

    /**
     * 评价
     * @return
     */
    @RequiresPermissions(value = BRANDAPPLY_EDIT)
    @RequestMapping(value = "/evaluate",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject evaluate(Long id,String designQuanlityScore,String makeQuanlityScore,String managerFeedback) {
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try{
            BrandApply  brandApply=brandApplyService.fetchById(id);
            brandApply.setDesignQuanlityScore(designQuanlityScore);
            brandApply.setMakeQuanlityScore(makeQuanlityScore);
            brandApply.setManagerFeedback(managerFeedback);
            brandApplyService.update(brandApply);
            Conds conds =new Conds();
            conds.equal("t.id",id);
            BrandApplyVo datas=brandApplyService.getApplyData(null,conds,null,0,1).get(0);
            Map<String,Object> params = CommonSendUtils.handleDataByBrandApplyCompleted(datas);
            String pdfPath = null;
            try {
                pdfPath = DocToPdf.DocToPdf(params,"brandApplyCompleted.xml","brandApplyCompleted.docx");
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<File> files = new ArrayList<File>();
            File file = new File(pdfPath);
            files.add(file);
            Conds marketConds=new Conds();
            marketConds.equal("del_flag","0");
            BrandMarketLeader marketLeader=marketLeaderService.fetchSearchByConds(marketConds);
            if(marketConds!=null){
                //给部门领导发送邮件
                String [] mailResult = CommonSendUtils.sendMailByBrandApplyCompleted(marketLeader.getName(),marketLeader.getEmail(),brandApply.getNumber(),files);
                if(mailResult!=null && "0".equals(mailResult[0]) && file!=null && file.exists()){
                    file.delete();
                }
            }
            rtnJson.put("errorNo","0");
        }catch (Exception e){
            rtnJson.put("errorMsg","操作失败:"+e.getMessage());
            log.error("品牌申请评价操作失败"+e.getMessage());
        }
        return rtnJson;
    }

    /**
     * 导出促销品总报表
     */
    @RequiresPermissions(value = BRANDAPPLY_EDIT)
    @RequestMapping(value = "exportStatistical")
    public void staisticalExcel(String time,HttpServletResponse response){
        if (!StringUtils.isEmpty(time)) {
            String beginTime = time.split(" - ")[0];
            String endTime = time.split(" - ")[1];
            String fileName = "品牌申请汇总报表"+"("+beginTime+"~"+endTime+")_"+DateUtils.getDate("yyyyMMDDHHMM");
            try{
                Conds conds=new Conds();
                conds.equal("t.del_flag","0");
                conds.greatEqual("t.create_time",beginTime);
                conds.lessEqual("t.create_time",endTime);
                List<BrandApplyVo> datas=brandApplyService.fetchSearchByPageVo(conds,null,0,0);
                BrandExportUtil.exportStatistical(fileName,datas,beginTime,endTime,response);
            }catch (Exception e){
                log.error("导出报表出错"+e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
