package com.fs.his.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.fs.common.core.domain.AjaxResult;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.config.cloud.CloudHostProper;
import com.fs.his.mapper.FsStoreOrderMapper;
import com.fs.his.mapper.FsStorePaymentMapper;
import com.fs.his.param.FsStoreOrderParam;
import com.fs.his.param.FsStorePaymentParam;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.fs.his.mapper.FsExportTaskMapper;
import com.fs.his.domain.FsExportTask;
import com.fs.his.service.IFsExportTaskService;

/**
 * 导出任务Service业务层处理
 *
 * @author fs
 * @date 2024-11-19
 */
@Service
public class FsExportTaskServiceImpl implements IFsExportTaskService
{
    private static final Logger log = LoggerFactory.getLogger(FsExportTaskServiceImpl.class);
    @Autowired
    private FsExportTaskMapper fsExportTaskMapper;
    @Autowired
    FsStoreOrderMapper fsStoreOrderMapper;
    @Autowired
    FsStorePaymentMapper fsStorePaymentMapper;

    @Autowired
    private CloudHostProper cloudHostProper;
    /**
     * 查询导出任务
     *
     * @param taskId 导出任务主键
     * @return 导出任务
     */
    @Override
    public FsExportTask selectFsExportTaskByTaskId(Long taskId)
    {
        return fsExportTaskMapper.selectFsExportTaskByTaskId(taskId);
    }

    /**
     * 查询导出任务列表
     *
     * @param fsExportTask 导出任务
     * @return 导出任务
     */
    @Override
    public List<FsExportTask> selectFsExportTaskList(FsExportTask fsExportTask)
    {
        return fsExportTaskMapper.selectFsExportTaskList(fsExportTask);
    }

    /**
     * 新增导出任务
     *
     * @param fsExportTask 导出任务
     * @return 结果
     */
    @Override
    public int insertFsExportTask(FsExportTask fsExportTask)
    {
        return fsExportTaskMapper.insertFsExportTask(fsExportTask);
    }

    /**
     * 修改导出任务
     *
     * @param fsExportTask 导出任务
     * @return 结果
     */
    @Override
    public int updateFsExportTask(FsExportTask fsExportTask)
    {
        return fsExportTaskMapper.updateFsExportTask(fsExportTask);
    }

    /**
     * 批量删除导出任务
     *
     * @param taskIds 需要删除的导出任务主键
     * @return 结果
     */
    @Override
    public int deleteFsExportTaskByTaskIds(Long[] taskIds)
    {
        return fsExportTaskMapper.deleteFsExportTaskByTaskIds(taskIds);
    }

    /**
     * 删除导出任务信息
     *
     * @param taskId 导出任务主键
     * @return 结果
     */
    @Override
    public int deleteFsExportTaskByTaskId(Long taskId)
    {
        return fsExportTaskMapper.deleteFsExportTaskByTaskId(taskId);
    }

    @Override
    public Integer isExportType1(Long userId) {

        return fsExportTaskMapper.isExportType1(userId);
    }

    @Async
    @Override
    public void exportStore1Data(FsStoreOrderParam fsStoreOrder, boolean isCheckPhone, boolean isCheckAddress,ArrayList<String> filter) {
        if ("金牛明医".equals(cloudHostProper.getCompanyName())){
            exportErpData(fsStoreOrder, isCheckPhone,isCheckAddress,filter);
        } else {
            List<FsStoreOrderExportVO> list = fsStoreOrderMapper.selectFsStoreOrderListVOByExport(fsStoreOrder);

            //对手机号脱敏
            if (list != null) {
                for (FsStoreOrderExportVO vo : list) {
                    vo.setFollowFrequency(6);
                    if (vo.getCycle()!=null){
                        vo.setFollowCount(vo.getCycle()/ vo.getFollowFrequency());
                    }
                    if (vo.getUserPhone() != null &&  !isCheckPhone) {
                        vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    }
                    if (vo.getUserPhone() != null && isCheckPhone && vo.getUserPhone().length()>11) {
                        vo.setUserPhone(PhoneUtil.decryptPhone(vo.getUserPhone()));
                    }
                    if (vo.getUserAddress() != null && !isCheckAddress) {
                        vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
                    }
                }
            }
            // 动态导出：根据选中的字段生成Excel
            ExcelUtil<FsStoreOrderExportVO> util = new ExcelUtil<FsStoreOrderExportVO>(FsStoreOrderExportVO.class);
            AjaxResult result;
            // 如果有选中的字段，只导出这些字段
            if (filter != null && !filter.isEmpty()) {
                result = util.exportExcelSelectedColumns(list, "订单数据", filter);
            } else {
                // 导出所有字段
                result = util.exportExcel(list, "订单数据");
            }
            FsExportTask task=fsExportTaskMapper.selectFsExportTaskByTaskId(fsStoreOrder.getTaskId());
            task.setFinishTime(new Date());
            task.setStatus(1);
            task.setFileUrl(result.get("msg").toString());
            fsExportTaskMapper.updateFsExportTask(task);
        }

    }

    /**
     * 检查对象是否至少有一个指定字段有有效值
     * @param vo 要检查的对象
     * @param fields 字段列表
     * @return 是否符合条件
     */
    private boolean hasAtLeastOneFieldValue(FsStoreOrderErpExportVO vo, List<String> fields) {
        if (vo == null || fields == null || fields.isEmpty()) {
            return false;
        }

        try {
            // 通过反射检查每个字段
            for (String fieldName : fields) {
                // 根据字段名获取对应的getter方法
                String getterMethod = "get" +
                        fieldName.substring(0, 1).toUpperCase() +
                        fieldName.substring(1);

                Method method = vo.getClass().getMethod(getterMethod);
                Object value = method.invoke(vo);

                // 检查值是否有效（非空且非空字符串）
                if (value != null) {
                    if (value instanceof String) {
                        if (!((String) value).trim().isEmpty()) {
                            return true;
                        }
                    } else {
                        // 非字符串类型只要不为null就算有效
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            // 处理反射异常，如字段不存在等情况
            log.error("检查字段值时发生错误", e);
        }

        // 所有字段都无效
        return false;
    }

    private void exportErpData(FsStoreOrderParam fsStoreOrder,  boolean isCheckPhone, boolean isCheckAddress,ArrayList<String> filter) {
        List<FsStoreOrderErpExportVO> erpList = fsStoreOrderMapper.selectFsStoreOrderListErpVOByExport(fsStoreOrder);
        //对手机号脱敏
        if (erpList != null) {
            for (FsStoreOrderErpExportVO vo : erpList) {
                vo.setFollowFrequency(6);
                if (vo.getCycle()!=null){
                    vo.setFollowCount(vo.getCycle()/ vo.getFollowFrequency());
                }
                if (vo.getUserPhone() != null &&  !isCheckPhone) {
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (vo.getUserPhone() != null && isCheckPhone && vo.getUserPhone().length()>11) {
                    vo.setUserPhone(PhoneUtil.decryptPhone(vo.getUserPhone()));
                }
                if (vo.getUserAddress() != null && !isCheckAddress) {
                    vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
                }
            }
        }

        // 动态导出：根据选中的字段生成Excel
        ExcelUtil<FsStoreOrderErpExportVO> util = new ExcelUtil<FsStoreOrderErpExportVO>(FsStoreOrderErpExportVO.class);
        AjaxResult result;
        // 如果有选中的字段，只导出这些字段
        if (filter != null && !filter.isEmpty()) {
            result = util.exportExcelSelectedColumns(erpList, "订单数据", filter);
        } else {
            // 导出所有字段
            result = util.exportExcel(erpList, "订单数据");
        }
        FsExportTask task=fsExportTaskMapper.selectFsExportTaskByTaskId(fsStoreOrder.getTaskId());
        task.setFinishTime(new Date());
        task.setStatus(1);
        task.setFileUrl(result.get("msg").toString());
        fsExportTaskMapper.updateFsExportTask(task);
    }

    @Async
    @Override
    public void exportStoreData(FsStoreOrderParam fsStoreOrder) {
        List<FsStoreOrderExcelVO> list = fsStoreOrderMapper.selectFsStoreOrderExcelListVO(fsStoreOrder);
        ExcelUtil<FsStoreOrderExcelVO> util = new ExcelUtil<FsStoreOrderExcelVO>(FsStoreOrderExcelVO.class);
        AjaxResult result= util.exportExcel(list, "药品订单财务导出");
        FsExportTask task=fsExportTaskMapper.selectFsExportTaskByTaskId(fsStoreOrder.getTaskId());
        task.setFinishTime(new Date());
        task.setStatus(1);
        task.setFileUrl(result.get("msg").toString());
        fsExportTaskMapper.updateFsExportTask(task);
    }
    @Async
    @Override
    public void exportStorePaymentData(FsStorePaymentParam fsStorePayment) {

            List<FsStorePaymentExcelVO> list = fsStorePaymentMapper.selectFsStorePaymentExcelVO(fsStorePayment);
            ExcelUtil<FsStorePaymentExcelVO> util = new ExcelUtil<FsStorePaymentExcelVO>(FsStorePaymentExcelVO.class);
            AjaxResult result =  util.exportExcel(list, "支付明细数据");
            FsExportTask task=fsExportTaskMapper.selectFsExportTaskByTaskId(fsStorePayment.getTaskId());
            task.setFinishTime(new Date());
            task.setStatus(1);
            task.setFileUrl(result.get("msg").toString());
            fsExportTaskMapper.updateFsExportTask(task);
    }

    @Override
    public Integer isExportType2(Long userId) {
         return fsExportTaskMapper.isExportType2(userId);
    }
}
