package com.cftech.common.typeappform.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.common.grantitems.model.Grantitems;
import com.cftech.common.grantitems.service.GrantitemsService;
import com.cftech.common.send.util.CommonSendUtils;
import com.cftech.common.send.util.CommonWorkFlowConstants;
import com.cftech.common.typeappform.model.AppitemsGrantReport;
import com.cftech.common.typeappform.model.TypeAppForm;
import com.cftech.common.typeappform.service.AppformGrantService;
import com.cftech.common.typeappform.service.TypeAppFormService;
import com.cftech.common.typeappform.util.NewStatisticalExportUtil;
import com.cftech.common.typeappform.util.StatisticalDetailListUtil;
import com.cftech.common.typeform.model.Typeform;
import com.cftech.common.typeform.service.TypeformService;
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.Constants;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.UploadUtils;
import com.cftech.shop.qrcode.model.WxQrcode;
import com.cftech.shop.qrcode.service.WxQrcodeService;
import com.cftech.shop.qrcode.util.WxQrcodeUtil;
import com.cftech.showroom.svideo.model.Svideo;
import com.cftech.showroom.svideo.service.SvideoService;
import com.cftech.sys.security.SecurityRealm;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.mp.api.qrcode.QrcodeDownload;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 类型申请单Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String TYPEAPPFORM_VIEW = "qy:typeAppForm:view"
 * 查看:public static final String TYPEAPPFORM_EDIT = "qy:typeAppForm:edit"
 *
 * @author faye
 * @date: 2019-08-14 16:52
 */
@Slf4j
@Controller
@RequestMapping("/a/typeAppForm")
public class TypeAppFormController {

    public static final String TYPEAPPFORM_VIEW = "qy:typeAppForm:view";

    @Autowired
    private TypeAppFormService typeAppFormService;

    @Autowired
    private GrantitemsService grantitemsService;

    @Autowired
    private WxQrcodeService wxQrcodeService;
    @Autowired
    private WxQrcodeUtil wxQrcodeUtil;
    @Autowired
    private TypeformService typeformService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private Map<String, AppformGrantService> appformGrantServiceMap;

    @Autowired
    private StatisticalDetailListUtil statisticalDetailListUtil;




    //列表页面
    @RequiresPermissions(value = TYPEAPPFORM_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model,String typeform) {
        Long accountId = UserUtils.getmpaccounts(request);
        if(StringUtils.isEmpty(typeform)){
            typeform="1";
        }
        model.addAttribute("id", typeform);
        model.addAttribute("accountId", accountId);
        String isManager = isManager();
        model.addAttribute("isManager",isManager);
        return "typeAppForm/typeAppFormlist";
    }

    /**
     * 获取当前操作人是否是管理员
     * 0:供应商管理员
     * 1:非供应商管理员
     * @return
     */
    private String isManager (){
        Subject subject = SecurityUtils.getSubject();
        String isManager = "1";
        if(subject.hasRole(CommonWorkFlowConstants.DIS_PERMISSION_STR)){//供应商管理员
            isManager="0";
        }
        return isManager;
    }

    //编辑页面（新增、修改）
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            TypeAppForm typeAppForm = typeAppFormService.fetchById(id);
            model.addAttribute("data", typeAppForm);
        }
        return "typeAppForm/typeAppFormform";
    }

    //提交数据（新增、修改）
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(TypeAppForm typeAppForm, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (typeAppForm != null && typeAppForm.getId() != null) {
                typeAppForm.setUpdateBy(UserUtils.getUser().getId());
                typeAppFormService.update(typeAppForm);
                rtnJson.put("errorNo", 0);
            } else {
                typeAppForm.setAccountsId(accountsId);
                typeAppForm.setDelFlag(false);
                typeAppForm.setAccountsId(UserUtils.getmpaccounts(request));
                typeAppForm.setCreateBy(UserUtils.getUser().getId());
                typeAppForm.setUpdateBy(UserUtils.getUser().getId());
                typeAppFormService.save(typeAppForm);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    @RequestMapping(value = "/formId")
    public String listData(Long id,String type,Model model) {
        //type 管理员录入数量0 管理员发货1  供应商发货2  查看单据详情3
        JSONObject rtnjson = new JSONObject();
        rtnjson.put("errorNo",0);
        try{
            Conds conds = new Conds();
            conds.equal("ca.id",id);
            TypeAppForm typeAppForm = typeAppFormService.fetchSearchByConds(conds);
            if(typeAppForm!=null){
                typeAppForm.setItems(ESAPI.encoder().decodeForHTML(typeAppForm.getItems()));
            }
            Conds grantConds = new Conds();
            grantConds.equal("cg.appform",id);
            List<Grantitems> grantitems = grantitemsService.fetchGrantItems(grantConds);
            model.addAttribute("data",typeAppForm);
            model.addAttribute("items",grantitems);
            model.addAttribute("isManager",isManager());
            model.addAttribute("type",type);
        }catch (Exception e){
            rtnjson.put("errorNo",1);
            e.printStackTrace();
        }
        if("0".equals(type)){
            return "typeAppForm/typeAppFormform";
        }else if("1".equals(type)){
            return "typeAppForm/managerTypeAppFormform";
        }else if("2".equals(type)){
            return "typeAppForm/disTypeAppFormform";
        }else if("3".equals(type)){
            return "typeAppForm/detailTypeAppFormform";
        }
        return null;
    }


    @RequestMapping(value = "/cancelForm")
    public String cancelForm(Long id,Model model) {
        JSONObject rtnjson = new JSONObject();
        rtnjson.put("errorNo",0);
        try{
            Conds conds = new Conds();
            conds.equal("ca.id",id);
            TypeAppForm typeAppForm = typeAppFormService.fetchSearchByConds(conds);
            if(typeAppForm!=null){
                typeAppForm.setItems(ESAPI.encoder().decodeForHTML(typeAppForm.getItems()));
            }
            Conds grantConds = new Conds();
            grantConds.equal("cg.appform",id);
            List<Grantitems> grantitems = grantitemsService.fetchGrantItems(grantConds);
            model.addAttribute("data",typeAppForm);
            model.addAttribute("items",grantitems);
        }catch (RuntimeException e){
            e.printStackTrace();
        }catch (Exception e){
            rtnjson.put("errorNo",1);
            e.printStackTrace();
        }
        return "cancelitems/cancelitemsform";
    }

    @RequestMapping(value = "/cancelSubmit")
    @ResponseBody
    public JSONObject cancelSubmit(TypeAppForm typeform) {
        JSONObject rtnjson = new JSONObject();
        rtnjson.put("errorNo",0);
        try{
            typeAppFormService.updatecancelSubmit(typeform,typeform.getCancelitems());
        }catch (RuntimeException e){
            e.printStackTrace();
            rtnjson.put("errorNo",2);
        }catch (Exception e){
            rtnjson.put("errorNo",1);
            e.printStackTrace();
        }
        return rtnjson;
    }

    @RequestMapping(value = "/grantSubmit")
    @ResponseBody
    public JSONObject grantSubmit(TypeAppForm typeform,String source) {
        //source  1:管理员确认发货  2:供应商确认发货
        JSONObject rtnjson = new JSONObject();
        rtnjson.put("errorNo",0);
        try{
            AppformGrantService appformGrantService = null;
            if("1".equals(source)){
                appformGrantService=appformGrantServiceMap.get(CommonWorkFlowConstants.MANAGER_GRANT_SERVICE_NAME);
            }else{
                appformGrantService=appformGrantServiceMap.get(CommonWorkFlowConstants.DIS_GRANT_SERVICE_NAME);
            }
            appformGrantService.updateGrantService(typeform,threadPoolTaskExecutor);
          //typeAppFormService.updategrantSubmit(typeform,typeform.getGrantitems(),threadPoolTaskExecutor);
        }catch (RuntimeException e){
            e.printStackTrace();
            rtnjson.put("errorNo",2);
        }catch (Exception e){
            rtnjson.put("errorNo",1);
            e.printStackTrace();
        }
        return rtnjson;
    }

    @RequestMapping(value = "/submitGrantCount")
    @ResponseBody
    public JSONObject submitGrantCount(TypeAppForm typeform) {
        JSONObject rtnjson = new JSONObject();
        rtnjson.put("errorNo",0);
        try{
            typeAppFormService.updateSubmitGrantCount(typeform,typeform.getGrantitems());
        }catch (RuntimeException e){
            e.printStackTrace();
            rtnjson.put("errorNo",2);
        }catch (Exception e){
            rtnjson.put("errorNo",1);
            e.printStackTrace();
        }
        return rtnjson;
    }

    //获取列表数据
    @RequiresPermissions(value = TYPEAPPFORM_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, TypeAppForm typeAppForm, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        conds.equal("ca.del_flag", Constants.DEL_FLAG_0);
        conds.equal("ca.accounts_id", accountsId);
        if (!StringUtils.isEmpty(typeAppForm.getOrg())) {
            conds.like("ca.org", typeAppForm.getOrg());
        }
        if (!StringUtils.isEmpty(typeAppForm.getNumber())) {
            conds.like("ca.number", typeAppForm.getNumber());
        }
        if (!StringUtils.isEmpty(typeAppForm.getDepartment())) {
            conds.equal("ca.department", typeAppForm.getDepartment());
        }
        if(typeAppForm.getTypeform()!=null){
            conds.equal("ca.typeform", typeAppForm.getTypeform());
        }
        if(!StringUtils.isEmpty(typeAppForm.getDname())){
            conds.like("ca.dname",typeAppForm.getDname());
        }
        if (!StringUtils.isEmpty(typeAppForm.getCostCenter())) {
            conds.equal("ca.cost_center", typeAppForm.getCostCenter());
        }
        if (!StringUtils.isEmpty(typeAppForm.getAddress())) {
            conds.equal("ca.address", typeAppForm.getAddress());
        }
        if(!StringUtils.isEmpty(typeAppForm.getName())){
            conds.like("ca.name",typeAppForm.getName());
        }
        Sort sort = new Sort("ca.create_time", OrderType.DESC);
        try{
            //列表获取判断是否是供应商角色，查询数据权限

        List<TypeAppForm> list = typeAppFormService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength,isManager());
        Integer counts = typeAppFormService.countServer(conds,isManager());

        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        }catch (Exception e){
            e.printStackTrace();
        }

        return rtnJson;
    }

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = TYPEAPPFORM_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response,TypeAppForm typeAppForm) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("ca.create_time", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("ca.del_flag", 0);
        conds.equal("ca.accounts_id", accountId);
        if (!StringUtils.isEmpty(typeAppForm.getOrg())) {
            conds.like("ca.org", typeAppForm.getOrg());
        }
        if (!StringUtils.isEmpty(typeAppForm.getDepartment())) {
            conds.equal("ca.department", typeAppForm.getDepartment());
        }
        if (!StringUtils.isEmpty(typeAppForm.getCostCenter())) {
            conds.equal("ca.cost_center", typeAppForm.getCostCenter());
        }
        if(typeAppForm.getTypeform()!=null){
            conds.equal("ca.typeform", typeAppForm.getTypeform());
        }
        if(!StringUtils.isEmpty(typeAppForm.getDname())){
            conds.equal("ca.dname",typeAppForm.getDname());
        }
        if (!StringUtils.isEmpty(typeAppForm.getAddress())) {
            conds.equal("ca.address", typeAppForm.getAddress());
        }
        if (!StringUtils.isEmpty(typeAppForm.getNumber())) {
            conds.like("ca.number", typeAppForm.getNumber());
        }
        if(!StringUtils.isEmpty(typeAppForm.getName())){
            conds.like("ca.name",typeAppForm.getName());
        }
        List<TypeAppForm> list = typeAppFormService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(TypeAppForm.class, response).toExcel(list, "促销品申请单信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = TYPEAPPFORM_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(TypeAppForm.class, response).toExcel(null, "促销品申请单信息");
    }


    @RequestMapping("/exportAppitemsExcel")
    @RequiresPermissions(value = TYPEAPPFORM_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response,String typeform) {
        List<AppitemsGrantReport> list = typeAppFormService.getAppitemsGrantReport(typeform);
        ExcelKit.$Export(AppitemsGrantReport.class, response).toExcel(list, "促销品报表");
    }


    //下载展厅二维码
    @RequiresPermissions(value = "download:promotion:qrcode")
    @RequestMapping(value = "/downloadcode", method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadcode(Long id, WxQrcode qrcode, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long accountsId = UserUtils.getmpaccounts(request);
        if (id != null) {
            Typeform typeform = typeformService.fetchById(id);
            if (StringUtils.isEmpty(typeform.getQrcode())) {
                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 = qrcode.getTicket();
                    qrcode.setCreateBy(UserUtils.getUser().getId());
                    qrcode.setType("typeform");
                    qrcode.setUpdateBy(UserUtils.getUser().getId());
                    qrcode.setSceneId(String.valueOf(count));
                    qrcode.setBindId(typeform.getId());
                    qrcode.setDelFlag(false);
                    wxQrcodeService.save(qrcode);
                    typeform.setQrcode(qrcode.getTicket());
                    QrcodeDownload.downPicture(request, response, tempTicket, typeform.getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                QrcodeDownload.downPicture(request, response, typeform.getQrcode(), typeform.getName());
            }
        }

    }

    @Autowired
    private SvideoService svideoService;


    //编辑页面（新增、修改）
    @RequiresPermissions(value = "qy:common:agreement:view")
    @RequestMapping("/agreementform")
    public String agreementform(HttpServletRequest request, String id, Model model) {
        Conds conds = new Conds();
        conds.equal("status","1");
        Svideo svideo = svideoService.fetchSearchByConds(conds);
        if(svideo!=null){
            svideo.setPersonContent(ESAPI.encoder().decodeForHTML(svideo.getPersonContent()));
            model.addAttribute("data", svideo);
        }
        return "svideo/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());
                svideo.setStatus("1");
                svideoService.update(svideo);
                rtnJson.put("errorNo", 0);
            } else {
                svideo.setAccountsId(accountsId);
                svideo.setDelFlag(false);
                svideo.setStatus("1");
                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;
    }

    /**
     * 申请单明细报表
     */
    @RequiresPermissions(value = "qy:typeappform:exportDetail")
    @RequestMapping(value = "exportAppformDetail")
    public void appformDetail(String time,HttpServletResponse response){
        if (!StringUtils.isEmpty(time)) {
            String credateBegin = time.split(" - ")[0];
            String credateEnd = time.split(" - ")[1];
            String fileName ="促销品申请明细表"+"("+credateBegin+"~"+credateEnd+")_"+ DateUtils.getDate("yyyyMMDDHHMM");
            String sheetName = "促销品申请明细";
            try{
                statisticalDetailListUtil.exportExcel(fileName,sheetName,credateBegin,credateEnd,response);
            }catch (Exception e){
                log.error("导出报表出错"+e.getMessage());
                e.printStackTrace();
            }
        }
    }

    @Autowired
    private NewStatisticalExportUtil newStatisticalExportUtil;

    /**
     * 导出促销品总报表
     */
    @RequiresPermissions(value = "manager:statistical:report")
    @RequestMapping(value = "exportAppformStatistical")
    public void appformStaisticalExcel(String time,HttpServletResponse response){
        if (!StringUtils.isEmpty(time)) {
            String credateBegin = time.split(" - ")[0];
            String credateEnd = time.split(" - ")[1];
            String fileName = "促销品申请汇总报表"+"("+credateBegin+"~"+credateEnd+")_"+DateUtils.getDate("yyyyMMDDHHMM");
            try{
                newStatisticalExportUtil.exportStatistical(fileName,credateBegin,credateEnd,response);
            }catch (Exception e){
                log.error("导出报表出错"+e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     *管理员确认收货接口
     */
    @RequiresPermissions(value = "qy:typeappform:confirm")
    @RequestMapping(value = "confirm",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject confirm(Long id){
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo",0);
        try
        {
            TypeAppForm typeAppForm = new TypeAppForm();
            typeAppForm.setId(id);
            typeAppForm.setManagerConfirmTime(new Date());
            typeAppFormService.update(typeAppForm);
            //通知申请人进行评价
            TypeAppForm temp = typeAppFormService.fetchById(id);
            CommonSendUtils.confirmPromotionSendApply(temp.getOpenid(),mpTokenUtil.getToken(temp.getAccountsId()),
                    temp.getCreateTime(),id,temp.getName(),temp.getNumber()
            );
        }catch (Exception e){
          rtnJson.put("errorNo",1);
          rtnJson.put("errorMsg",e.getMessage());
          e.printStackTrace();
        }
        return rtnJson;
    }

    /**
     *管理员评分接口
     */
    @RequiresPermissions(value = "qy:typeappform:evaliuate")
    @RequestMapping(value = "evaluate",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject confirm(Long id,Integer managerAllEvaluate,
                              Integer managerQualityEvaluate,
                              Integer managerLogisticsEvaluate,
                              String managerEvaluateRemarks){
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo",0);
        try
        {

            TypeAppForm typeAppForm = new TypeAppForm();
            typeAppForm.setId(id);
            typeAppForm.setManagerAllEvaluate(managerAllEvaluate);
            typeAppForm.setManagerQualityEvaluate(managerQualityEvaluate);
            typeAppForm.setManagerLogisticsEvaluate(managerLogisticsEvaluate);
            typeAppForm.setManagerEvaluateRemarks(managerEvaluateRemarks);
            typeAppForm.setManagerQualityTime(new Date());
            typeAppFormService.update(typeAppForm);

        }catch (Exception e){
            rtnJson.put("errorNo",1);
            rtnJson.put("errorMsg",e.getMessage());
            e.printStackTrace();
        }
        return rtnJson;
    }

    @Autowired
    private MpTokenUtil mpTokenUtil;

}
