package com.cftech.brand.apply.web;

import com.alibaba.fastjson.JSONArray;
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.service.BrandApplyDetailService;
import com.cftech.brand.apply.model.BrandApply;
import com.cftech.brand.apply.model.BrandApplyVo;
import com.cftech.brand.apply.service.BrandApplyService;
import com.cftech.brand.category.model.BrandCategory;
import com.cftech.brand.category.service.BrandCategoryService;
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.manager.model.BrandManager;
import com.cftech.brand.manager.service.BrandManagerService;
import com.cftech.brand.market.model.BrandMarketLeader;
import com.cftech.brand.market.service.BrandMarketLeaderService;
import com.cftech.brand.material.model.BrandMaterial;
import com.cftech.brand.material.service.BrandMaterialService;
import com.cftech.brand.supplier.model.BrandSupplier;
import com.cftech.brand.supplier.service.BrandSupplierService;
import com.cftech.brand.util.BrandApplyTempMsgUtil;
import com.cftech.common.send.util.CommonSendUtils;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.showroom.appform.util.DocToPdf;
import lombok.extern.slf4j.Slf4j;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 品牌申请移动端接口
 * @author faye
 * @date 2020-02-18
 */
@RestController
@RequestMapping(value = "/mobile/brandApply")
@Slf4j
public class MobileBrandApplyController {

    @Autowired
    private BrandApplyService brandApplyService;

    @Autowired
    private MpTokenUtil tokenUtil;

    @Autowired
    private BrandEmpService empService;

    @Autowired
    private BrandManagerService managerService;


    @Autowired
    private BrandSupplierService brandSupplierService;

    @Autowired
    private BrandApplyDetailService detailService;

    @Autowired
    private CodingruleUtils codingruleUtils;

    @Autowired
    private BrandMarketLeaderService marketLeaderService;

    @Autowired
    private BrandDepartmentService departmentService;

    @Autowired
    private BrandCategoryService categoryService;

    @Autowired
    private BrandMaterialService materialService;

    @RequestMapping(value = "departmentData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String departmentData(){
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try {
            Conds conds=new Conds();
            conds.equal("del_flag","0");
            Sort sort=new Sort("number", OrderType.ASC);
            List<BrandDepartment> data=departmentService.fetchSearchByPage(conds,sort,0,0);
            for(BrandDepartment department:data){
                department.setName(ESAPI.encoder().decodeForHTML(department.getName()));
            }
            rtnJson.put("errorNo","0");
            rtnJson.put("data",data);
        }catch (Exception e){
            log.error("品牌申请获取部门信息异常:"+e.getMessage());
            rtnJson.put("errorMsg",e.getMessage());
        }
        return rtnJson.toString();
    }

    @RequestMapping(value = "categoryData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String categoryData(@RequestParam(required = false) String departmentId){
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try {
            Conds conds=new Conds();
            conds.equal("del_flag","0");
            Sort sort=new Sort("name", OrderType.ASC);
            List<BrandCategory> data=categoryService.fetchSearchByPage(departmentId,conds,sort,0,0);
            for(BrandCategory obj:data){
                obj.setName(ESAPI.encoder().decodeForHTML(obj.getName()));
            }
            rtnJson.put("errorNo","0");
            rtnJson.put("data",data);
        }catch (Exception e){
            log.error("品牌申请获取类别信息异常:"+e.getMessage());
            rtnJson.put("errorMsg",e.getMessage());
        }
        return rtnJson.toString();
    }

    @RequestMapping(value = "materialData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String materialData(@RequestParam(required = false) String categoryId){
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try {
            Conds conds=new Conds();
            conds.equal("del_flag","0");
            if(StringUtils.isNotBlank(categoryId)){
                conds.equal("category_id",categoryId);
            }
            Sort sort=new Sort("name", OrderType.ASC);
            List<BrandMaterial> data=materialService.fetchSearchByPage(conds,sort,0,0);
            for(BrandMaterial obj:data){
                obj.setName(ESAPI.encoder().decodeForHTML(obj.getName()));
            }
            rtnJson.put("errorNo","0");
            rtnJson.put("data",data);
        }catch (Exception e){
            log.error("品牌申请获取物料信息异常:"+e.getMessage());
            rtnJson.put("errorMsg",e.getMessage());
        }
        return rtnJson.toString();
    }

    @RequestMapping(value = "getLatestData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getLatestData(@RequestParam String openId){
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try{
            Conds conds=new Conds();
            conds.equal("t.open_id",openId);
            conds.equal("t.del_flag","0");
            List<BrandApplyVo> datas=brandApplyService.getApplyData(openId,conds,null,0,1);
            if(!CollectionUtils.isEmpty(datas)){
                rtnJson.put("data",datas.get(0));
            }
            rtnJson.put("errorNo","0");
        }catch (Exception e){
            log.error("获取上次提交品牌申请单异常:"+e.getMessage());
            rtnJson.put("errorMsg",e.getMessage());
        }
        return rtnJson;
    }

    @RequestMapping(value = "getDetail", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getDetail(@RequestParam(required = false)String openId,@RequestParam String id){
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try{
            Conds conds=new Conds();
            conds.equal("t.id",id);
            List<BrandApplyVo> datas=brandApplyService.getApplyData(null,conds,null,0,1);
            if(CollectionUtils.isEmpty(datas)){
                rtnJson.put("errorMsg","无法访问");
                return rtnJson;
            }
            rtnJson.put("data",datas.get(0));
            rtnJson.put("errorNo","0");
        }catch (Exception e){
            log.error("获取品牌申请单异常:"+e.getMessage());
            rtnJson.put("errorMsg",e.getMessage());
        }
        return rtnJson;
    }
    /**
     * 申请人确认信息
     * @param id
     * @param status 0 取消，1确认
     * @return
     */
    @RequestMapping(value = "confirmData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String confirmData(@RequestParam String id,@RequestParam String status,@RequestParam String openId,@RequestParam(required = false) String closeReason){
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try {
            BrandApply apply=brandApplyService.fetchById(id);
            if(apply!=null&&StringUtils.equals(apply.getOpenId(),openId)){
                if (StringUtils.equals("0",status)){
                    apply.setStatus("6");
//                    apply.setCloseReason(closeReason);
                    apply.setDescription(closeReason);
                    brandApplyService.update(apply);
                    BrandApplyTempMsgUtil.sendMsgToApplicantByCanceled(apply.getId(),apply.getName(),apply.getNumber(),apply.getOpenId(),apply.getCreateTime(),tokenUtil.getToken(apply.getAccountsId()));
                    Conds conds =new Conds();
                    conds.equal("del_flag","0");
                    conds.equal("id",apply.getAuditId());
                    BrandManager manager=managerService.fetchSearchByConds(conds);
                    BrandApplyTempMsgUtil.sendMsgToManagerByCanceled(apply.getId(),apply.getName(),apply.getNumber(),manager.getOpenId(),apply.getCreateTime(),tokenUtil.getToken(apply.getAccountsId()));
                    rtnJson.put("errorNo","0");
                }else{
                    apply.setStatus("2");
                    //申请人确认通知管理员
                    Conds mConds =new Conds();
                    mConds.equal("del_flag","0");
                    mConds.equal("id",apply.getAuditId());
                    BrandManager manager=managerService.fetchSearchByConds(mConds);
                    BrandApplyTempMsgUtil.sendMsgByEmpToBeConfirmForManager(apply.getId(),apply.getName(),apply.getNumber(),manager.getOpenId(),new Date(),
                          null,null,  tokenUtil.getToken(apply.getAccountsId()));
                    //申请人确认发送至市场部领导
                    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.handleDataByBrandApplyAgreed(datas);
                    String pdfPath = null;
                    try {
                        pdfPath = DocToPdf.DocToPdf(params,"empToBeConfirm.xml","empToBeConfirm.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(marketLeader==null){
                        rtnJson.put("errorNo","-1");
                        return rtnJson.toString();
                    }
                    String [] mailResult= CommonSendUtils.sendMailByEmpToBeConfirmed(marketLeader.getEmail(),apply.getId(),files,apply.getNumber());
                    if(mailResult!=null && "0".equals(mailResult[0]) && file!=null && file.exists()){
                        file.delete();
                    }
                    brandApplyService.update(apply);
                    rtnJson.put("errorNo","0");
                }
            }
        }catch (Exception e){
            log.error("品牌申请申请人确认异常:"+e.getMessage());
            rtnJson.put("errorMsg",e.getMessage());
        }
        return rtnJson.toString();
    }


    /**
     * 申请人修改接口
     * @param id
     * @param openId
     * @param accountsId
     * @param name
     * @param email
     * @param lineManager
     * @param lineManagerEmail
     * @param costCenter
     * @param departmentId
     * @param categoryId
     * @param isMaterialObject
     * @param details
     * @param requireSpecify
     * @param deliveryDate
     * @param remarks
     * @return
     */
    @RequestMapping(value = "updateData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String submitData(@RequestParam String id,@RequestParam String openId,@RequestParam Long accountsId,
                             @RequestParam String name,@RequestParam String email,
                             @RequestParam String lineManager,@RequestParam String lineManagerEmail,
                             @RequestParam String costCenter,@RequestParam Long departmentId,
                             @RequestParam Long categoryId,@RequestParam String isMaterialObject,
                             @RequestParam String details,@RequestParam String requireSpecify,
                             @RequestParam String deliveryDate,@RequestParam(required = false) String remarks){
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try {
            BrandApply oldData=brandApplyService.fetchById(id);
            if(!StringUtils.equals("1",oldData.getStatus())||!StringUtils.equals(openId,oldData.getOpenId())){
                rtnJson.put("errorMsg","无法修改");
                return rtnJson.toString();
            }
            oldData.setStatus("4");
            oldData.setCloseReason("申请人修改");
            oldData.setDelFlag(true);
            brandApplyService.update(oldData);

            BrandApply data=new BrandApply();
//            data.setCreateTime(oldData.getCreateTime());
            data.setNumber(oldData.getNumber());
            data.setAuditId(oldData.getAuditId());

            data.setOpenId(openId);
            data.setName(name);
            data.setEmail(email);
            data.setLineManager(lineManager);
            data.setLineManagerEmail(lineManagerEmail);
            data.setCostCenter(costCenter);
            String legalEntity = costCenter.split("-")[0];
            data.setLegalEntity(legalEntity);
            data.setDepartmentId(departmentId);
            data.setCategoryId(categoryId);
            data.setIsMaterialObject(isMaterialObject);
            data.setAccountsId(accountsId);
            data.setRequireSpecify(requireSpecify);
            data.setDeliveryDate(DateUtils.parseDate(deliveryDate,"yyyy-MM-dd"));
            data.setDescription(remarks);

            Conds managerConds=new Conds();
            managerConds.equal("del_flag","0");
            BrandManager manager=managerService.fetchSearchByConds(managerConds);
            if(manager==null){
                rtnJson.put("errorMsg","未找到流程管理员");
                return rtnJson.toString();
            }
            Conds marketConds = new Conds();
            marketConds.equal("del_flag","0");
            BrandMarketLeader marketLeader=marketLeaderService.fetchSearchByConds(marketConds);
            if(marketLeader==null){
                rtnJson.put("errorMsg","未找到市场部流程管理员");
                return rtnJson.toString();
            }
            brandApplyService.saveData(data, JSONArray.parseArray(details));
            Date now=new Date();
            //发送提交成功的提醒给申请人
            BrandApplyTempMsgUtil.sendMsgToApplicantByUpdate(data.getId(),data.getName(),data.getNumber(),data.getOpenId(),now,
                    manager.getName(),manager.getMobile(),tokenUtil.getToken(accountsId));
            //发送提醒给管理员
            BrandApplyTempMsgUtil.sendMsgToManagerByUpdate(data.getId(),data.getName(),data.getNumber(),manager.getOpenId(),now,
                    tokenUtil.getToken(accountsId));
            // 发送邮件给管理员
            Conds conds =new Conds();
            conds.equal("t.id",data.getId());
            BrandApplyVo datas=brandApplyService.getApplyData(null,conds,null,0,1).get(0);
            datas.setAuditName(manager.getName());
            Map<String,Object> params = CommonSendUtils.handleDataByBrandApplySubmit(datas);
            String pdfPath = null;
            try {
                pdfPath = DocToPdf.DocToPdf(params,"brandApplySubmit.xml","brandApplySubmit.docx");
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<File> files = new ArrayList<File>();
            File file = new File(pdfPath);
            files.add(file);

            String [] mailResult= CommonSendUtils.sendMailByBrandApplySubmit(data.getId(),manager.getName(),data.getNumber(),manager.getEmail(),manager.getId(),marketLeader.getEmail(),files);
            if(mailResult!=null && "0".equals(mailResult[0]) && file!=null && file.exists()){
                file.delete();
            }
            rtnJson.put("errorNo","0");
        }catch (Exception e){
            log.error("提交品牌申请异常:"+e.getMessage());
            rtnJson.put("errorMsg","请稍后重试:"+e.getMessage());
        }
        return rtnJson.toString();
    }
    /**
     * 申请人提交接口
     * @param openId
     * @param accountsId
     * @param name
     * @param email
     * @param lineManager
     * @param lineManagerEmail
     * @param costCenter
     * @param departmentId
     * @param categoryId
     * @param isMaterialObject
     * @param details
     * @param requireSpecify
     * @param deliveryDate
     * @param remarks
     * @return
     */
    @RequestMapping(value = "submitData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String submitData(@RequestParam String openId,@RequestParam Long accountsId,
                             @RequestParam String name,@RequestParam String email,
                             @RequestParam String lineManager,@RequestParam String lineManagerEmail,
                             @RequestParam String costCenter,@RequestParam Long departmentId,
                             @RequestParam Long categoryId,@RequestParam String isMaterialObject,
                             @RequestParam String details,@RequestParam String requireSpecify,
                             @RequestParam String deliveryDate,@RequestParam(required = false) String remarks){
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        try {
            BrandApply data=new BrandApply();
            data.setNumber(codingruleUtils.getNumber(accountsId,BrandApply.class.getName()));
            data.setOpenId(openId);
            data.setName(name);
            data.setEmail(email);
            data.setLineManager(lineManager);
            data.setLineManagerEmail(lineManagerEmail);
            data.setCostCenter(costCenter);
            String legalEntity = costCenter.split("-")[0];
            data.setLegalEntity(legalEntity);
            data.setDepartmentId(departmentId);
            data.setCategoryId(categoryId);
            data.setIsMaterialObject(isMaterialObject);
            data.setAccountsId(accountsId);
            data.setRequireSpecify(requireSpecify);
            data.setDeliveryDate(DateUtils.parseDate(deliveryDate,"yyyy-MM-dd"));
            data.setDescription(remarks);
            Conds managerConds=new Conds();
            managerConds.equal("del_flag","0");
            BrandManager manager=managerService.fetchSearchByConds(managerConds);
            if(manager==null){
                rtnJson.put("errorMsg","未找到流程管理员");
                return rtnJson.toString();
            }
            Conds marketConds = new Conds();
            marketConds.equal("del_flag","0");
            BrandMarketLeader marketLeader=marketLeaderService.fetchSearchByConds(marketConds);
            if(marketLeader==null){
                rtnJson.put("errorMsg","未找到市场部流程管理员");
                return rtnJson.toString();
            }
            brandApplyService.saveData(data, JSONArray.parseArray(details));
            Date now=new Date();
            //发送提交成功的提醒给申请人
            BrandApplyTempMsgUtil.sendMsgToApplicantBySubmit(data.getId(),data.getName(),data.getNumber(),data.getOpenId(),now,
                    manager.getName(),manager.getMobile(),tokenUtil.getToken(accountsId));
            //发送提醒给管理员
            BrandApplyTempMsgUtil.sendMsgToManagerBySubmit(data.getId(),data.getNumber(),manager.getOpenId(),now,
                    tokenUtil.getToken(accountsId));
            // 发送邮件给管理员
            Conds conds =new Conds();
            conds.equal("t.id",data.getId());
            BrandApplyVo datas=brandApplyService.getApplyData(null,conds,null,0,1).get(0);
            datas.setAuditName(manager.getName());
            Map<String,Object> params = CommonSendUtils.handleDataByBrandApplySubmit(datas);
            String pdfPath = null;
            try {
                pdfPath = DocToPdf.DocToPdf(params,"brandApplySubmit.xml","brandApplySubmit.docx");
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<File> files = new ArrayList<File>();
            File file = new File(pdfPath);
            files.add(file);

            String [] mailResult= CommonSendUtils.sendMailByBrandApplySubmit(data.getId(),manager.getName(),data.getNumber(),manager.getEmail(),manager.getId(),marketLeader.getEmail(),files);
            if(mailResult!=null && "0".equals(mailResult[0]) && file!=null && file.exists()){
                file.delete();
            }
            rtnJson.put("errorNo","0");
        }catch (Exception e){
            e.printStackTrace();
            log.error("提交品牌申请异常:"+e.getMessage());
            rtnJson.put("errorMsg","请稍后重试:"+e.getMessage());
        }
        return rtnJson.toString();
    }

    /**
     * 跳转接口弹窗
     *
     */
    @RequestMapping(value = "auditConfirm", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void auditConfirm(Long id,HttpServletResponse response,String type){
        response.setContentType("text/html;charset=utf-8");
        try {
            BrandApply brandApply=brandApplyService.fetchById(id);
            //必须是待审核状态
            if (brandApply != null) {
                if (StringUtils.equals(brandApply.getStatus(), "2")) {
                    String auditStr = "确定要审核通过吗?";
                    if(!"0".equals(type)){
                        auditStr=auditStr.replace("通过","拒绝");
                    }
                    String yuming = SystemConfig.p.getProperty("QY_DOMAIN_NAME");
                    String url = yuming +"/mobile/brandApply/marketAudit?id="+id+"&type="+type;
                    response.getWriter().write("<script>var a = ''; if(confirm(\""+auditStr+"\")){a='123';location.href=\""+url+"&password=\"+a}else{window.close();}</script>");
                }else if(StringUtils.equals(brandApply.getStatus(),"3")){
                    try {
                        response.setContentType("text/html;charset=utf-8");
                        response.getWriter().write("<script>alert('您已审核-通过');</script>");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else if(StringUtils.equals(brandApply.getStatus(),"4")){
                    try {
                        response.setContentType("text/html;charset=utf-8");
                        response.getWriter().write("<script>alert('您已审核-拒绝');</script>");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else{
                    try {
                        response.setContentType("text/html;charset=utf-8");
                        response.getWriter().write("<script>alert('申请单状态不可操作');</script>");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 市场部领导审核接口
     *
     * @param id
     */
    @RequestMapping(value = "marketAudit", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void managerAudit(Long id, HttpServletResponse response, String type, String password) {
        if(!StringUtils.equals(password,"123")){
            return;
        }
        BrandApply brandApply=brandApplyService.fetchById(id);


        //提示语
        String remind = "审核成功,已通过审核";
        //必须是待审核状态
        if (brandApply != null) {
            if (StringUtils.equals(brandApply.getStatus(), "2")) {
                //审核通过
                if (StringUtils.equals(type, "0")) {
                    brandApply.setStatus("3");
                    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.handleDataByBrandApplyDivision(datas);
                    String pdfPath = null;
                    try {
                        pdfPath = DocToPdf.DocToPdf(params,"brandApplyDivision.xml","brandApplyDivision.docx");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    List<File> files = new ArrayList<File>();
                    File file = new File(pdfPath);
                    files.add(file);
                    BrandManager brandManager=managerService.fetchById(brandApply.getAuditId());
                    Set<String> ccMails = new HashSet<>();
                    if(StringUtils.equals("0",brandApply.getDistributionClass())){
                        BrandEmp designer=empService.fetchById(brandApply.getEmpId());
                        ccMails.add(designer.getEmail());
                    }else if(StringUtils.equals("1",brandApply.getDistributionClass())){
//                        BrandSupplier supplier=brandSupplierService.fetchById(brandApply.getSupplierId());
//                        ccMails.add(supplier.getEmail());
                    }else if(StringUtils.equals("2",brandApply.getDistributionClass())){
                        BrandEmp designer=empService.fetchById(brandApply.getEmpId());
                        ccMails.add(designer.getEmail());
//                        BrandSupplier supplier=brandSupplierService.fetchById(brandApply.getSupplierId());
//                        ccMails.add(supplier.getEmail());
                    }
                    log.info("品牌申请:市场部领导审核同意:toMail:"+brandManager.getEmail());
                    CommonSendUtils.sendMailByBrandApplyMarketAgreed(brandManager.getName(),brandApply.getNumber(),brandManager.getEmail(),ccMails,files);
                    //发送消息给管理员
                    BrandApplyTempMsgUtil.sendToManagerByMarketConfirm(brandApply.getId(),tokenUtil.getToken(brandApply.getAccountsId()),brandManager.getOpenId(),brandApply.getNumber(),brandApply.getCreateTime());
                    //发送消息给申请人
                    BrandEmp emp=empService.fetchById(brandApply.getContactEmpId());
                    BrandApplyTempMsgUtil.sendToApplicantByMarketConfirm(id,tokenUtil.getToken(brandApply.getAccountsId()),
                            brandApply.getOpenId(),brandApply.getName(),brandApply.getNumber(),
                            emp.getName(),emp.getContactInformation() ,brandApply.getCreateTime() );
                } else if (StringUtils.equals(type, "1")) {
                    brandApply.setStatus("4");
                    brandApplyService.update(brandApply);
                    remind = "审核成功,已拒绝";
                }
            }else if(StringUtils.equals(brandApply.getStatus(),"3")){
                remind="您已审核-通过";
            }else if(StringUtils.equals(brandApply.getStatus(),"4")){
                remind="您已审核-拒绝";
            }
        }else{
            remind="未找到对应单据";
        }
        response.setContentType("text/html;charset=utf-8");
        try {
            response.getWriter().write("<script>alert('" + remind + "');</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "submitEvaluate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject submitEvaluate(@RequestParam String openId,@RequestParam String id,
                                     @RequestParam String serviceScore,@RequestParam String feedback){
        JSONObject rtnJson=new JSONObject();
        rtnJson.put("errorNo","1");
        rtnJson.put("errorMsg","不可评分!");
        try{
            BrandApply brandApply=brandApplyService.fetchById(id);
            if(!StringUtils.equals(openId,brandApply.getOpenId())){
                return rtnJson;
            }
            if(StringUtils.equals("5",brandApply.getStatus())&&StringUtils.equals("1",brandApply.getIsScore())){
                brandApply.setServiceScore(serviceScore);
                brandApply.setFeedback(feedback);
                brandApplyService.update(brandApply);
                rtnJson.put("errorNo","0");
            }

        }catch (Exception e){
            log.error("品牌申请评分异常:"+e.getMessage());
            rtnJson.put("errorMsg",e.getMessage());
        }
        return rtnJson;
    }
}
