package com.cftech.brand.apply.web;

import com.alibaba.fastjson.JSONObject;
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.BrandApplyVo;
import com.cftech.brand.apply.service.BrandApplyService;
import com.cftech.brand.emp.model.BrandEmp;
import com.cftech.brand.emp.service.BrandEmpService;
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.Constants;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.SystemConfig;
import com.cftech.showroom.appform.util.DocToPdf;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 品牌申请审批
 * @author faye
 * @date 2020-02-10
 */
@Slf4j
@Controller
@RequestMapping("/mp/brandApply/comm")
public class BrandApplyCommController {

    @Autowired
    private BrandApplyService brandApplyService;

    @Autowired
    private BrandApplyDetailService detailService;

    @Autowired
    private BrandEmpService empService;

    @Autowired
    private BrandSupplierService supplierService;

    @Autowired
    private MpTokenUtil tokenUtil;


    @RequestMapping(value = "/empData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, BrandEmp brandEmp, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(brandEmp.getNumber())) {
            conds.like("number", brandEmp.getNumber());
        }
        if (!StringUtils.isEmpty(brandEmp.getName())) {
            conds.like("name", brandEmp.getName());
        }

        if (!StringUtils.isEmpty(brandEmp.getContactInformation())) {
            conds.like("contact_information", brandEmp.getContactInformation());
        }

        Sort sort = new Sort("create_time", OrderType.DESC);

        List<BrandEmp> list = empService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = empService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }
    @RequestMapping(value = "/supplierData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, BrandSupplier brandSupplier, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(brandSupplier.getNumber())) {
            conds.like("number", brandSupplier.getNumber());
        }
        if (!StringUtils.isEmpty(brandSupplier.getName())) {
            conds.like("name", brandSupplier.getName());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

        List<BrandSupplier> list = supplierService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = supplierService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //管理员接单审批页面
    @RequestMapping(value = "/managerAudit")
    public String list(Long id,String auditId,String status,HttpServletRequest request, 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);
                brandApply.setAuditId(auditId);
                model.addAttribute("data",brandApply);
            }
            model.addAttribute("status",status);
        }
        return "brandApply/audit";
    }

    /**
     * 管理员接单
     */
    @RequestMapping("/agree")
    @ResponseBody
    public JSONObject agree(String id,String empId,String distributionClass,Long contactEmpId,String manHour,String estimateExternalCosts,
                            String supplierId,String auditId,String intendedDeliveryDate,String estimatedWorkload) {
        JSONObject rtnJosn = new JSONObject();
        try {
            BrandApply brandApply=brandApplyService.fetchById(id);
            if(com.cftech.core.util.StringUtils.equals("0",brandApply.getStatus())){
                brandApply.setDistributionClass(distributionClass);
                brandApply.setContactEmpId(contactEmpId);
                brandApply.setIntendedDeliveryDate(DateUtils.parseDate(intendedDeliveryDate,"yyyy-MM-dd"));
                brandApply.setAuditId(auditId);
                brandApply.setEstimatedWorkload(estimatedWorkload);
                Double hourlyRateData=0d;
                if(com.cftech.core.util.StringUtils.equals("0",distributionClass)){
                    brandApply.setManHour(new BigDecimal(manHour).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                    //仅设计
                    brandApply.setEmpId(Long.valueOf(empId));
                    BrandEmp emp=empService.fetchById(empId);
                    BigDecimal hourlyRate=new BigDecimal(emp.getUnitPrice());
                    hourlyRateData=hourlyRate.doubleValue();
                    BigDecimal estimateInternalCosts=new BigDecimal(manHour).multiply(hourlyRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                    brandApply.setEstimateInternalCosts(estimateInternalCosts.doubleValue());
                    brandApply.setQuotedPrice(brandApply.getEstimateInternalCosts());
                }else  if(com.cftech.core.util.StringUtils.equals("1",distributionClass)){
                    //仅制作
                    brandApply.setSupplierId(Long.valueOf(supplierId));
                    brandApply.setEstimateExternalCosts(new BigDecimal(estimateExternalCosts).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                    brandApply.setQuotedPrice(brandApply.getEstimateExternalCosts());
                }else  if(com.cftech.core.util.StringUtils.equals("2",distributionClass)){
                    //设计和制作
                    brandApply.setManHour(new BigDecimal(manHour).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                    brandApply.setEmpId(Long.valueOf(empId));
                    BrandEmp emp=empService.fetchById(empId);
                    BigDecimal hourlyRate=new BigDecimal(emp.getUnitPrice());
                    hourlyRateData=hourlyRate.doubleValue();
                    BigDecimal estimateInternalCosts=new BigDecimal(manHour).multiply(hourlyRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                    brandApply.setEstimateInternalCosts(estimateInternalCosts.doubleValue());

                    brandApply.setSupplierId(Long.valueOf(supplierId));
                    brandApply.setEstimateExternalCosts(new BigDecimal(estimateExternalCosts).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                    brandApply.setQuotedPrice(estimateInternalCosts.add(new BigDecimal(estimateExternalCosts)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                brandApply.setHourlyRate(hourlyRateData);
                brandApply.setStatus("1");
                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.handleDataByBrandApplyAgreed(datas);
                String pdfPath = null;
                try {
                    pdfPath = DocToPdf.DocToPdf(params,"empToBeConfirm.xml","empToBeConfirm.docx");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String imgFilePath = SystemConfig.p.getProperty("docXmlTemplatePath")+"How to confirm on WeChat.jpg";
                List<File> files = new ArrayList<File>();
                File file = new File(pdfPath);
                files.add(file);
                File imgFile=new File(imgFilePath);
                files.add(imgFile);
                String [] mailResult=CommonSendUtils.sendMailByBrandApplyAgreed(brandApply.getName(),brandApply.getNumber(),brandApply.getEmail(),brandApply.getLineManagerEmail(),files);
                if(mailResult!=null && "0".equals(mailResult[0]) && file!=null && file.exists()){
                    file.delete();
                }
                //给申请人发送确认拟交付信息消息
                BrandEmp contactEmp=empService.fetchById(contactEmpId);
                BrandApplyTempMsgUtil.sendMsgByEmpToBeConfirm(brandApply.getId(),brandApply.getName(),brandApply.getNumber(),brandApply.getOpenId(),
                        new Date(),contactEmp.getName(),contactEmp.getContactInformation(),tokenUtil.getToken(brandApply.getAccountsId()));
                rtnJosn.put("errorNo", 0);

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("品牌申请接单失败："+e.getMessage());
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    /**
     * 管理员拒单
     * @param id
     * @param text
     * @return
     */
    @RequestMapping("/reject")
    @ResponseBody
    public JSONObject reject(Long id,String text) {
        JSONObject rtnJosn = new JSONObject();
        try {
            BrandApply brandApply=brandApplyService.fetchById(id);
            if(com.cftech.core.util.StringUtils.equals("0",brandApply.getStatus())){
                brandApply.setId(Long.valueOf(id));
                brandApply.setStatus("4");
                brandApply.setCloseReason(text);
                brandApplyService.update(brandApply);
                rtnJosn.put("errorNo", 0);
            }
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }


}
