package com.pj.project.tb_business_item;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.api.wx.bo.MsgDataBO;
import com.pj.api.wx.service.WxService;
import com.pj.current.config.MyConfig;
import com.pj.current.config.WxConfig;
import com.pj.current.task.TaskService;
import com.pj.project.tb_business.TbBusiness;
import com.pj.project.tb_business.TbBusinessService;
import com.pj.project.tb_fee_details.TbFeeDetails;
import com.pj.project.tb_fee_details.TbFeeDetailsService;
import com.pj.project4sp.admin.SpAdmin;
import com.pj.project4sp.admin.SpAdminService;
import com.pj.project4sp.uploadfile.UploadUtil;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.pj.utils.sg.*;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Service: tb_business_item -- 业务作业项
 *
 * @author qzy
 */
@Service
@Transactional
public class TbBusinessItemService extends ServiceImpl<TbBusinessItemMapper, TbBusinessItem> implements IService<TbBusinessItem> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbBusinessItemMapper tbBusinessItemMapper;
    @Resource
    @Lazy
    private TbBusinessService tbBusinessService;
    @Resource
    @Lazy
    private SpAdminService spAdminService;
    @Resource
    private WxConfig wxConfig;
    @Resource
    private MyConfig myConfig;
    @Resource
    @Lazy
    private WxService wxService;
    @Resource
    TaskService taskService;

    @Resource
    TbFeeDetailsService tbFeeDetailsService;

    /**
     * 增
     */
    int add(TbBusinessItem t) {
        return tbBusinessItemMapper.add(t);
    }


    /**
     * 改
     */
    int update(TbBusinessItem t) {
        return tbBusinessItemMapper.update(t);
    }

    /**
     * 查
     */
    TbBusinessItem getById(String id) {
        return tbBusinessItemMapper.getById(id);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    public List<TbBusinessItem> getList(SoMap so) {
        return tbBusinessItemMapper.getList(so);
    }


    public void removeByBusinessId(String businessId) {
        QueryWrapper<TbBusinessItem> ew = new QueryWrapper<>();
        ew.eq("business_id", businessId);
        this.remove(ew);
    }

    public List<TbBusinessItem> findByBusinessId(String businessId) {
        QueryWrapper<TbBusinessItem> ew = new QueryWrapper<>();
        ew.eq("business_id", businessId);
        ew.orderByDesc("pick");
        ew.orderByAsc("confirm");
        return list(ew);
    }



    public void confirmBusinessItem(long id) {
        TbBusinessItem tbBusinessItem = this.getById(id);
        tbBusinessItem.setConfirm(1).setConfirmTime(new Date());
        this.updateById(tbBusinessItem);

        TbFeeDetails feeDetails = tbFeeDetailsService.getByBusinessItemId(id + "");
        if (feeDetails != null) {
            feeDetails.setPickCustomerName(tbBusinessItem.getPickCustomerName());
            tbFeeDetailsService.updateById(feeDetails);
        }

        //todo 通知作业方
        List<SpAdmin> spAdminList = spAdminService.findByCustomerId(tbBusinessItem.getPickCustomerId());
        TbBusiness tbBusiness = tbBusinessService.getById(tbBusinessItem.getBusinessId());
        taskService.addTask(new PayTask(tbBusiness.getId(), 10, tbBusiness.getCustomerId()));
        MsgDataBO msgDataBO = new MsgDataBO("订单号：" + tbBusinessItem.getNo(), "系统管理人员", DateUtil.now(), tbBusiness.getGoodsName() + "(" + tbBusinessItem.getItemTypeName() + tbBusinessItem.getItemName() + ")");
        spAdminList.stream().filter(admin -> StrUtil.isNotEmpty(admin.getOpenid())).forEach(admin -> {
            String detailUrl = myConfig.getWebDomain() + "/pages/business-item/item-detail?itemId=" + id + "&openid=" + admin.getOpenid();
            wxService.sendTemplateMsg(wxConfig.getBusinessConfirmTemplate(), admin.getOpenid(), msgDataBO, detailUrl);
        });
    }

    public String exportItems(SoMap so) {
        String beginTime = so.getString("beginTime");
        String endTime = so.getString("endTime");
        List<TbBusinessItem> itemList = this.getList(so);
        List<ExportItemsDTO> itemDTOList = new ArrayList<>();
        for (TbBusinessItem item : itemList) {
            ExportItemsDTO itemsDTO = new ExportItemsDTO();
            BeanUtil.copyProperties(item, itemsDTO, "createTime", "pickTime", "confirmTime");
            itemsDTO.setUnit(item.getItemPrice() + item.getUnit())
                    .setCreateTime(DateUtil.format(item.getCreateTime(), "yyyy/MM/dd HH:mm:ss"))
                    .setPickTime(DateUtil.format(item.getPickTime(), "yyyy/MM/dd HH:mm:ss"))
                    .setConfirmTime(DateUtil.format(item.getConfirmTime(), "yyyy/MM/dd HH:mm:ss"));
            itemDTOList.add(itemsDTO);
        }
        String separator = File.separator;
        String today = DateUtil.today();
        String rootPath = UploadUtil.uploadConfig.rootFolder + separator + UploadUtil.uploadConfig.httpPrefix;
        String prefix = myConfig.getDomain() + UploadUtil.uploadConfig.httpPrefix;
        String extPath = "businessItem" + separator + today + separator;
        String fileName = "items_" + beginTime + "--" + endTime + ".xlsx";
        String savePath = rootPath + separator + extPath;
        File saveFIle = new File(savePath);
        if (!saveFIle.exists()) {
            saveFIle.mkdirs();
        }
        EasyExcel.write(savePath + fileName, ExportItemsDTO.class).sheet("作业订单").doWrite(itemDTOList);
        return prefix + "/businessItem/" + today + "/items_" + beginTime + "--" + endTime + ".xlsx";
    }

    public List<TbBusinessItem> findByBusinessIdList(List<String> businessIdList) {
        if (businessIdList.isEmpty()){
            return Collections.emptyList();
        }
        QueryWrapper<TbBusinessItem> ew = new QueryWrapper<>();
        ew.in("business_id", businessIdList);
        return list(ew);
    }
}
