package com.sifang.modules.sunshine.SystemSetting.service;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.dao.RectificationSetDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmRectificationSet;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class RectificationSettingService extends BaseService {

    @Autowired
    private RectificationSetDao dao;

    /**
     * 获取设置列表
     */
    public List<Record> getList(Map<String, String> params) {
        return dao.findList(params);
    }

    /**
     * 查询变更类型设置详情
     */
    public Record getOneById(String id) {
        return dao.findOneById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result add(String name, String status,  Result result) {
        // 校验名称
        long total = dao.queryCountByName(name, null);
        if (total > 0) {
            result.setCode("206");
            result.setMsg("已存在相同类型名称，请重新设置");
            return result;
        }
        if (StringUtil.equalsAny(status, "5","6")) {
            result.setCode("206");
            result.setMsg("节点：待上传发票、待签署合同 不可用，请重新设置");
            return result;
        }
        User user = UserUtils.getUser();
        CrmRectificationSet set = new CrmRectificationSet();
        set.setName(name);
        set.setStatus(status);
        set.setCreateBy(user.getId());
        set.setCreateTime(new Date());
        dao.save(set);
        result.setCode("200");
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result edit(String id, String name, String status,  Result result) {
        // 校验名称
        long total = dao.queryCountByName(name, id);
        if (total > 0) {
            result.setCode("206");
            result.setMsg("已存在相同类型名称，请重新设置");
            return result;
        }
        if (StringUtil.equalsAny(status, "5","6")) {
            result.setCode("206");
            result.setMsg("节点：待上传发票、待签署合同 不可用，请重新设置");
            return result;
        }
        CrmRectificationSet set = dao.get(id);
        set.setName(name);
        set.setStatus(status);
        set.setUpdateTime(new Date());
        dao.save(set);
        result.setCode("200");
        return result;
    }

    public void deleteById(String id) {
        dao.deleteById(id);
    }
}
