package com.cftech.common.typeappform.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.model.Codingrule;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.common.appitems.model.Appitems;
import com.cftech.common.approver.model.Approver;
import com.cftech.common.approver.service.ApproverService;
import com.cftech.common.commondept.model.CommonDepartment;
import com.cftech.common.commondept.service.CommonDepartmentService;
import com.cftech.common.grantitems.model.Grantitems;
import com.cftech.common.grantitems.service.GrantitemsService;
import com.cftech.common.manager.model.ManagerDto;
import com.cftech.common.manager.service.ManagerService;
import com.cftech.common.marketing.model.Marketing;
import com.cftech.common.marketing.service.MarketingService;
import com.cftech.common.send.util.CommonSendUtils;
import com.cftech.common.typeappform.model.TypeAppForm;
import com.cftech.common.typeappform.service.TypeAppFormService;
import com.cftech.common.typeform.model.Typeform;
import com.cftech.common.typeform.service.TypeformService;
import com.cftech.common.use.model.Use;
import com.cftech.common.use.service.UseService;
import com.cftech.core.sql.Conds;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/mobile/wxjs")
public class MobileMailAuditController {

    @Autowired
    private TypeAppFormService typeAppFormService;

    @Autowired
    private MpTokenUtil tokenUtil;

    @Autowired
    private ManagerService managerService;

    @Autowired
    private TypeformService typeformService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private MarketingService marketingService;

    @Autowired
    private GrantitemsService grantitemsService;

    @Autowired
    private ApproverService approverService;

    @Autowired
    private UseService useService;

    @Autowired
    private CommonDepartmentService commonDepartmentService;

    @Autowired
    private CodingruleUtils codingruleUtils;

    /**
     * 获取编码接口测试
     */
    @RequestMapping(value = "getCode")
    public String getCode(){
        return codingruleUtils.getNumber(348L, Appitems.class.getName());
    }

    /**
     * 查看信息
     */
    /**
     * 查询申请单详情
     */
    @RequestMapping(value = "getTypeAppform", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getTypeAppform(Long id) {
        JSONObject rtnJson = new JSONObject();

        try {
            Conds conds = new Conds();
            conds.equal("ca.id", id);
            TypeAppForm typeAppForm = typeAppFormService.fetchSearchByConds(conds);
            Conds grantConds = new Conds();
            grantConds.equal("cg.appform", id);
            List<Grantitems> grantitems = grantitemsService.fetchSearchByPage(grantConds, null, 0, 0);
            rtnJson.put("grantItmes", grantitems);
            rtnJson.put("data", typeAppForm);
            rtnJson.put("errorNo", 0);
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }


    /**
     * 职能部门领导审核接口
     *
     * @param id
     */
    @RequestMapping(value = "deparmentAudit", method = RequestMethod.GET)
    public void audit(Long id, HttpServletResponse response, String type,String password) {
        if(!StringUtils.equals(password,"123")){
            return;
        }
        Conds typeAppConds = new Conds();
        typeAppConds.equal("ca.id", id);
        TypeAppForm typeAppForm = typeAppFormService.fetchSearchByConds(typeAppConds);
        Use use = useService.fetchById(typeAppForm.getUseId());
        CommonDepartment commonDepartment = commonDepartmentService.fetchById(typeAppForm.getDepartment());
        //提示语
        String remind = "审核成功,已通过审核";
        //必须是待部门领导审核状态
        if (typeAppForm != null) {
            if (typeAppForm != null && StringUtils.equals(typeAppForm.getStatus(), "0")) {
                //审核通过
                if (StringUtils.equals(type, "0")) {

                    Long typeformId = typeAppForm.getTypeform();
                    Typeform typeform = typeformService.fetchById(typeformId);
                    String max = typeform.getPrice();
                    if (StringUtils.isBlank(max)) {
                        max = SystemConfig.p.getProperty("WORKFLOW.MAXPRICE");
                    }
                    BigDecimal maxBigDecimal = new BigDecimal(max);
                    BigDecimal appBigDecimal = new BigDecimal(typeAppForm.getAppPrice());
                    /**
                     *1.申请金额大于上限金额，需市场部领导审核
                     *2.成本中心符合某几个成本中心，金额不大于上线金额，也需要市场部领导审核
                     *3.申请用途序号为1，则也需市场部领导审核
                     *4.部门过滤，则也需市场部领导审核
                     */
                    //成本中心判别
                    String[] costCenterArr = SystemConfig.p.getProperty("COSTCENTERS").split(",");
                    boolean istrue = false;
                    for (String str : costCenterArr) {
                        if (StringUtils.equals(str, typeAppForm.getCostCenter())) {
                            istrue = true;
                            break;
                        }
                    }

                    if("1".equals(use.getSort())){//申请用途判断
                       istrue=true;
                    }

                    if("6".equals(commonDepartment.getSort())){//申请部门判断
                        istrue=true;
                    }
                    String token = tokenUtil.getToken(typeAppForm.getAccountsId());
                    typeAppForm.setDescription("0");//无需市场部领导审核
                    if (appBigDecimal.compareTo(maxBigDecimal) == 1 || istrue) {
                        typeAppForm.setStatus("3");
                        typeAppForm.setDescription("1");
                        typeAppFormService.update(typeAppForm);
                        //异步处理邮件
                        threadPoolTaskExecutor.execute(new Runnable() {
                            @Override
                            public void run() {
                                Calendar cal = Calendar.getInstance();
                                int year = cal.get(Calendar.YEAR);
                                Conds conds = new Conds();
                                conds.equal("del_flag", 0);
                                conds.equal("typeform",typeAppForm.getTypeform());
                                Marketing marketing = marketingService.fetchSearchByConds(conds);
                                //查询总发放金额，与此人发放的金额，放入邮件中
                                Conds totalConds = new Conds();
                                totalConds.equal("del_flag", 0);
                                totalConds.greatThan("status",3);
                                totalConds.equal("YEAR(create_time)", year);
                                String totalSum = typeAppFormService.getSumGrantPrice(totalConds, "1");
//                                Conds personConds = new Conds();
//                                personConds.equal("del_flag", 0);
//                                personConds.equal("openid", typeAppForm.getOpenid());
//                                personConds.in("cost_center", costCenter);
//                                personConds.equal("YEAR(create_time)", year);
//                                String personSum = typeAppFormService.getSumGrantPrice(personConds, "1");
                                Map<String, Object> params = CommonSendUtils.data(typeAppForm,totalSum);
                                String pdfPath = null;
                                try {
                                    pdfPath = DocToPdf.DocToPdf(params, "cuxiaopindocument.xml", "cuxiaopin.docx");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                List<File> files = new ArrayList<File>();
                                File file = new File(pdfPath);
                                files.add(file);
                                //向市场部领导发送审核邮件
                                String[] results = CommonSendUtils.sendMarketMail(marketing.getEmail(), typeAppForm.getId(), marketing.getName(), totalSum, files,typeAppForm.getNumber());
                                if (results != null && "0".equals(results[0]) && file != null && file.exists()) {
                                    file.delete();
                                }
                                //通知后台管理员
                                CommonSendUtils.sendMarketAndDepartmentTemplate(token, getManagersOpenIds(typeAppForm.getTypeform()), id, new Date(), typeAppForm.getNumber());
                            }
                        });
                    } else {
                        typeAppForm.setStatus("1");
                        typeAppFormService.update(typeAppForm);
                        //不需要市场部领导审核，直接通知申请人为审核通过，等待发货
                        Date createTime = typeAppForm.getCreateTime();
                        CommonSendUtils.sendApplicationPassTemplate(token, typeAppForm.getOpenid(), createTime, id, typeAppForm.getName());
                        CommonSendUtils.sendManagerDeptAuditSuccessTemplate(token, getManagersOpenIds(typeAppForm.getTypeform()), id, createTime, typeAppForm.getNumber());
                    }
                    //审核拒绝
                } else if (StringUtils.equals(type, "1")) {
                    typeAppForm.setStatus("2");
                    typeAppFormService.update(typeAppForm);
                    /**
                     *发送模板消息通知申请人
                     */

                    Approver approver = approverService.fetchById(typeAppForm.getApprover());
                    String token = tokenUtil.getToken(typeAppForm.getAccountsId());
                    CommonSendUtils.sendApplicationRejectedTemplate(token, typeAppForm.getOpenid(), typeAppForm.getId(), typeAppForm.getName(),approver.getName());
                    remind = "审核成功,已拒绝";
                }
            } else if (StringUtils.equals(typeAppForm.getStatus(), "2")) {
                remind = "您已审核-拒绝";
            } else {
                remind = "您已审核-通过";
            }
        }else{
            remind="未找到对应单据";
        }
        response.setContentType("text/html;charset=utf-8");
        try {
            response.getWriter().write("<script>alert('" + remind + "');</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public List<String> getManagersOpenIds(Long typeform) {
        List<String> managerOpenIds = new ArrayList<>();
        List<ManagerDto> managerDtos = managerService.fetchOpenidNickName(typeform);
        if (managerDtos != null && managerDtos.size() > 0) {
            for (ManagerDto managerDto : managerDtos) {
                managerOpenIds.add(managerDto.getOpenid());
            }
        }
        return managerOpenIds;
    }


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

        //提示语
        String remind = "审核成功,已通过审核";
        //必须是待部门领导审核状态
        if (typeAppForm != null) {
            if (typeAppForm != null && StringUtils.equals(typeAppForm.getStatus(), "3")) {
                //审核通过
                String token = tokenUtil.getToken(typeAppForm.getAccountsId());
                Date createTime = typeAppForm.getCreateTime();
                if (StringUtils.equals(type, "0")) {
                    typeAppForm.setStatus("4");
                    typeAppFormService.update(typeAppForm);
                    //通知申请者，市场部领导已审批通过
                    CommonSendUtils.sendApplicationPassTemplate(token, typeAppForm.getOpenid(), createTime, id, typeAppForm.getName());
                    //通知管理员，市场部领导已审批通过
                    CommonSendUtils.sendManagerAuditSuccessTemplate(token, getManagersOpenIds(typeAppForm.getTypeform()), id, createTime, typeAppForm.getNumber());
                } else if (StringUtils.equals(type, "1")) {
                    //通知管理员，审核不通过
                    CommonSendUtils.sendManagerAndMarketrejected(token, getManagersOpenIds(typeAppForm.getTypeform()), id, createTime, typeAppForm.getNumber());
                    typeAppFormService.updateMarketRefuse(typeAppForm);
                    remind = "审核成功,已拒绝";
                }
            }else if(StringUtils.equals(typeAppForm.getStatus(),"4")){
                remind="您已审核-通过";
            }else if(StringUtils.equals(typeAppForm.getStatus(),"5")){
                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 = "auditConfirm", method = RequestMethod.GET)
    public void auditConfirm(Long id,HttpServletResponse response,String type,String mold){
        response.setContentType("text/html;charset=utf-8");
        try {
            String auditStr = "确定要审核通过吗?";
            if(!"0".equals(type)){
                auditStr=auditStr.replace("通过","拒绝");
            }
            String yuming = SystemConfig.p.getProperty("QY_DOMAIN_NAME");
            String url = "";
            if("0".equals(mold)){//部门领导
                url = yuming +"/mobile/wxjs/deparmentAudit?id="+id+"&type="+type;
            }else{//市场部
                url = yuming +"/mobile/wxjs/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>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 查询市场部领导审批的金额
     */
    @RequestMapping("getMarketSum")
    public String totalSUm(){
        try{
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            Conds totalConds = new Conds();
            totalConds.equal("del_flag",0);
            totalConds.equal("YEAR(create_time)",year);
            String totalSum = typeAppFormService.getSumGrantPrice(totalConds, "1");
            return totalSum;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";

    }

    /**
     * 查询市场部领导审批的金额
     */
    @RequestMapping("getDepartMentSum")
    public String getDepartMentSum(Long id){
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        Conds totalConds = new Conds();
        totalConds.equal("del_flag",0);
        totalConds.equal("YEAR(create_time)",year);
        totalConds.equal("approver",id);
        String totalSum = typeAppFormService.getSumGrantPrice(totalConds, "0");
        return totalSum;
    }
}
