package com.cftech.common.typeappform.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.common.appitems.model.Appitems;
import com.cftech.common.appitems.service.AppitemsService;
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.dao.MarketingMapper;
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.use.model.Use;
import com.cftech.common.use.service.UseService;
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.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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/mobile/auth/appform")
public class MobileTypeAppFormController {


    @Autowired
    private CommonDepartmentService commonDepartmentService;

    @Autowired
    private AppitemsService appitemsService;

    @Autowired
    private TypeAppFormService typeAppFormService;

    @Autowired
    private ApproverService approverService;

    @Autowired
    GrantitemsService grantitemsService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private UseService useService;

    @Autowired
    private ManagerService managerService;

    @Autowired
    private MpTokenUtil tokenUtil;

    @Autowired
    private MarketingService marketingService;

    /**
     * 通用申请单获取部门
     *
     * @return
     */
    @RequestMapping(value = "getdept", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getdept() {
        JSONObject rtnJson = new JSONObject();
        try {
            rtnJson.put("errorNo", 0);
            Conds conds = new Conds();
            conds.equal("cd.del_flag", 0);
            Sort sort = new Sort("cd.sort", OrderType.ASC);
            List<CommonDepartment> commonDepartmentList = commonDepartmentService.fetchSearchByPage(conds, null, 0, 0);
            rtnJson.put("datas", commonDepartmentList);
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    /**
     * 获取商品
     */
    @RequestMapping(value = "getitem", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getItems(Long id, int page, int pageSize) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        conds.equal("au.use_id", id);
        conds.equal("ca.del_flag", 0);
        conds.equal("ca.is_online", 1);
        conds.greatThan("ca.invented_stock",0);
        Sort sort = new Sort("ca.sort", OrderType.ASC);
        List<Appitems> appitems = appitemsService.fetchSearchByPage(conds, sort, page * pageSize, pageSize);
        rtnJson.put("datas", appitems);
        try {
            rtnJson.put("errorNo", 0);
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    /**
     * 获取使用用途
     */
    @RequestMapping(value = "getuse", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getItems() {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        conds.equal("cd.del_flag", 0);
        Sort sort = new Sort("cd.sort", OrderType.ASC);
        List<Use> typeforms = useService.fetchSearchByPage(conds, sort, 0, 0);
        rtnJson.put("datas", typeforms);
        try {
            rtnJson.put("errorNo", 0);
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }


    /**
     * 获取审批人
     */
    @RequestMapping(value = "getApprover", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getApprover(Long departmentId) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        conds.equal("cd.id", departmentId);
        conds.equal("t.del_flag", 0);
        conds.equal("t.status",1);
        Sort sort = new Sort("t.sort", OrderType.ASC);
        List<Approver> approvers = approverService.fetchSearchByPage(conds, sort, 0, 0);
        rtnJson.put("datas", approvers);
        try {
            rtnJson.put("errorNo", 0);
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }


    /**
     * 提交申请单
     */
    @RequestMapping(value = "submitTypeAppform", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getItems(TypeAppForm typeAppForm) {
        JSONObject rtnJson = new JSONObject();
        try {

            Conds conds = new Conds();
            conds.equal("ca.del_flag", 0);
            conds.equal("YEAR(ca.create_time)", 1900 + new Date().getYear());
            Sort sort = new Sort("ca.create_time", OrderType.DESC);
            List<TypeAppForm> typeAppForms = typeAppFormService.fetchSearchByPage(conds, sort, 0, 1);
            Integer num = 1;
            if (typeAppForms != null && typeAppForms.size() > 0) {
                TypeAppForm typeAppFormTemp = typeAppForms.get(0);
                String number = typeAppFormTemp.getNumber();
                num = Integer.valueOf(number.substring(8, number.length()));
                num = num + 1;
                typeAppForm.setSerialNumber(Long.valueOf(num));
                typeAppForm.setNumber(DateUtils.formatDate(new Date(), "yyyyMMdd") + (num));
            } else {
                typeAppForm.setSerialNumber(Long.valueOf(num));
                typeAppForm.setNumber(DateUtils.formatDate(new Date(), "yyyyMMdd") + num);
            }
            typeAppForm.setStatus("0");//职能部门领导审批中
            typeAppForm.setIssuingState("-1");//发放状态，待管理员录入
            typeAppForm.setIsCancel("0");//默认没有退库
            if (StringUtils.isNotBlank(typeAppForm.getCostCenter()) && typeAppForm.getCostCenter().contains("-")) {
                String legalEntity = typeAppForm.getCostCenter().split("-")[0];
                typeAppForm.setLegalEntity(legalEntity);
            } else {
                //参数错误
                rtnJson.put("errorNo", 2);
                return rtnJson;
            }
            //审批人
            Approver approver = approverService.fetchById(typeAppForm.getApprover());
            if (StringUtils.isNotBlank(typeAppForm.getItems())) {
                typeAppFormService.save(typeAppForm, typeAppForm.getItems());
                String token = tokenUtil.getToken(typeAppForm.getAccountsId());
                Long id = typeAppForm.getId();
                String openId = typeAppForm.getOpenid();
                Date nowDate = new Date();
                List<String> managerOpenIds = new ArrayList<>();
                List<ManagerDto> managerDtos = managerService.fetchOpenidNickName(typeAppForm.getTypeform());
                if (managerDtos != null && managerDtos.size() > 0) {
                    for (ManagerDto managerDto : managerDtos) {
                        managerOpenIds.add(managerDto.getOpenid());
                    }
                }
                //给申请人发送提交成功模板消息
                CommonSendUtils.sendApplicationSubmitTemplate(token, openId, id, typeAppForm.getName(), nowDate,typeAppForm.getNumber());
                /**
                 * 发送邮件，通知部门领导审核
                 */
                //异步处理邮件
                threadPoolTaskExecutor.execute(new Runnable() {
                    @Override
                    public void run() {


                        // 此审批人是否是市场部领导，通过邮箱判断
                        Conds marketConds = new Conds();
                        marketConds.equal("del_flag", 0);
                        marketConds.equal("typeform",typeAppForm.getTypeform());
                        Marketing marketing = marketingService.fetchSearchByConds(marketConds);

                        boolean istrue  = marketing!=null && approver!=null;
                        String type = "0"; //统计范围，职能部门领导/市场部领导
                        //查询总发放金额，与此人发放的金额，放入职能部门领导邮件中(总金额排除内置成本中心)
                        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.greatEqual("status",1);
                        if(istrue && StringUtils.equals(marketing.getEmail(),approver.getEmail())){
                            type = "1";//此人是市场部领导
                        }else{
                            totalConds.equal("approver", approver.getId());
                        }
                        String totalSum = typeAppFormService.getSumGrantPrice(totalConds, type);
                        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 [] mailResult = CommonSendUtils.sendDepartmentMail(approver.getEmail(), typeAppForm.getId(), approver.getName(), totalSum,files,typeAppForm.getNumber());
                        if(mailResult!=null && "0".equals(mailResult[0]) && file!=null && file.exists()){
                            file.delete();
                        }
                        typeAppForm.setPdfpath(pdfPath);
                        //给管理员发送提交成功模板消息
                        CommonSendUtils.sendManagerTemplate(token, managerOpenIds, id, nowDate,typeAppForm.getNumber());
                    }
                });

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



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

        try {
            TypeAppForm typeAppForm = null;
            if(id!=null){
                Conds conds = new Conds();
                conds.equal("ca.id", id);
                 typeAppForm = typeAppFormService.fetchSearchByConds(conds);
            }else{
                Conds conds = new Conds();
                conds.equal("ca.openid",openId);
                Sort sort = new Sort("ca.create_time",OrderType.DESC);
                List<TypeAppForm> typeAppForms = typeAppFormService.fetchSearchByPage(conds,sort,0,1);
                if(typeAppForms!=null && typeAppForms.size()>0){
                    typeAppForm=typeAppForms.get(0);
                }
            }
            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;
    }

    /**
     *促销品评价接口
     */
    @RequestMapping(value = "submitEvaluate",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject submitEvaliuate(Long id,
                                      Integer applyAllEvaluate,
                                      String applyEvaluateRemarks,
                                      Integer logisticsEvaluate,
                                      Integer qualityEvaluate){
        JSONObject rtnJson = new JSONObject();
            try {
                TypeAppForm typeAppFormExits= typeAppFormService.fetchById(id);
                if(typeAppFormExits!=null && typeAppFormExits.getApplyQualityTime()!=null){
                    rtnJson.put("errorNo","2");
                    return rtnJson;
                }

                rtnJson.put("errorNo", 0);
                TypeAppForm typeAppForm = new TypeAppForm();
                typeAppForm.setApplyQualityTime(new Date())
                .setApplyAllEvaluate(applyAllEvaluate)
                .setApplyEvaluateRemarks(applyEvaluateRemarks)
                .setApplyLogisticsEvaluate(logisticsEvaluate)
                .setApplyQualityEvaluate(qualityEvaluate)
                        .setId(id);
                typeAppFormService.update(typeAppForm);

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