package com.bonus.material.fieldMaintenance.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.enums.FieldTaskStatusEnum;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.fieldMaintenance.domain.FieldApplyDetails;
import com.bonus.material.fieldMaintenance.domain.FieldApplyInfo;
import com.bonus.material.fieldMaintenance.mapper.FieldMaintenanceMapper;
import com.bonus.material.fieldMaintenance.service.FieldMaintenanceService;
import com.bonus.material.task.domain.TmTask;
import com.bonus.material.task.domain.TmTaskAgreement;
import com.bonus.material.task.mapper.TmTaskAgreementMapper;
import com.bonus.material.task.mapper.TmTaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FieldMaintenanceImpl implements FieldMaintenanceService {

    @Resource
    private FieldMaintenanceMapper fieldMaintenanceMapper;

    @Resource
    private TmTaskMapper taskMapper;

    @Resource
    private TmTaskAgreementMapper taskAgreementMapper;

    /**
     * 查询现场维修任务列表
     *
     * @param fieldApplyInfo 现场维修任务
     * @return 现场维修任务集合
     */
    @Override
    public List<FieldApplyInfo> selectFieldApplyInfoList(FieldApplyInfo fieldApplyInfo) {
        try {
            List<FieldApplyInfo> list = fieldMaintenanceMapper.selectFieldApplyInfoList(fieldApplyInfo);
            // 如果列表为空，直接返回空列表
            if (CollectionUtils.isEmpty(list)) {
                return Collections.emptyList();
            }
            return list;
        } catch (Exception e) {
            log.error(e.getMessage());
            return Collections.emptyList();
        }
    }

    /**
     * @param fieldApplyDetails
     * @return
     */
    @Override
    public List<FieldApplyDetails> selectFieldApplyDetailsList(FieldApplyDetails fieldApplyDetails) {
        try {
            List<FieldApplyDetails> list = fieldMaintenanceMapper.selectFieldApplyDetailsList(fieldApplyDetails);
            // 如果列表为空，直接返回空列表
            if (CollectionUtils.isEmpty(list)) {
                return Collections.emptyList();
            }
            return list;
        } catch (Exception e) {
            log.error(e.getMessage());
            return Collections.emptyList();
        }
    }

    /**
     * 通过id获取
     *
     * @param id id
     * @return 信息
     */
    @Override
    public AjaxResult selectFieldApplyInfoById(Integer id) {
        try {
            return AjaxResult.success(fieldMaintenanceMapper.selectFieldApplyInfoById(id));
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 新增维修任务
     *
     * @param fieldApplyInfo 信息
     * @return 是否成功
     */
    @Override
    public AjaxResult insert(FieldApplyInfo fieldApplyInfo) {
        try {
            int thisMonthMaxOrder = taskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_FIELD.getTaskTypeId());
            String code = genderTaskCode(thisMonthMaxOrder);
            TmTask tmTask = new TmTask(null, TmTaskTypeEnum.TM_TASK_FIELD.getTaskTypeId(),
                    FieldTaskStatusEnum.FIELD_TASK_NO_FINISHED.getStatus(),
                    null, thisMonthMaxOrder + 1, code);
            tmTask.setCreateTime(DateUtils.getNowDate());
            tmTask.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            fieldApplyInfo.setCode(code);
            fieldApplyInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            fieldApplyInfo.setCreateTime(DateUtils.getNowDate());
            int i = taskMapper.insertTmTask(tmTask);
            if (i > 0) {
                TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask.getTaskId(), fieldApplyInfo.getAgreementId());
                tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
                tmTaskAgreement.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                taskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);
                fieldApplyInfo.setTaskId(tmTask.getTaskId());
                fieldApplyInfo.setAgreementId(tmTaskAgreement.getAgreementId());
                int insert = fieldMaintenanceMapper.insert(fieldApplyInfo);
                return insert > 0 ? AjaxResult.success() : AjaxResult.error("保存失败，请重试!");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error("保存失败，请重试!");
        }
        return AjaxResult.error("保存失败，请重试!");
    }

    /**
     * 删除任务
     *
     * @param id id
     * @return 条数
     */
    @Override
    public AjaxResult deleteFieldApplyInfoById(Integer id, Long taskId) {
        try {
            taskMapper.deleteTmTaskByTaskId(taskId);
            int i = fieldMaintenanceMapper.deleteFieldApplyInfoById(id);
            return i > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 提交任务
     *
     * @param taskId 任务id
     * @return 条数
     */
    @Override
    public AjaxResult submitTask(Long taskId) {
        try {
            int i = taskMapper.updateTaskStatus(taskId.toString(), FieldTaskStatusEnum.FIELD_TASK_IN_FINISHED.getStatus());
            return i > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * @param id
     * @param typeId
     * @return
     */
    @Override
    public AjaxResult deleteFieldApplyDetailsById(Long id, Long typeId) {
        try {
            int i = fieldMaintenanceMapper.deleteFieldApplyDetailsById(id, typeId);
            return i > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * @param fieldApplyDetails
     * @return
     */
    @Override
    public AjaxResult insertDetails(FieldApplyDetails fieldApplyDetails) {
        try {
            int i = fieldMaintenanceMapper.insertDetails(fieldApplyDetails);
            return i > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }


    /**
     * 生成现场维修任务单号
     *
     * @param thisMonthMaxOrder
     * @return
     */
    private String genderTaskCode(int thisMonthMaxOrder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        return MaterialConstants.FIELD_TASK_TYPE_LABEL + result + String.format("-%03d", thisMonthMaxOrder + 1);
    }
}
