package thyyxxk.webserver.service.settings.SchedulingClass;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.envionment.JcptMobile;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.settings.SchedulingClassDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.dictionary.SimpleCodeName;
import thyyxxk.webserver.entity.schedulingClass.data.SchedulingClass;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.R;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class SchedulingClassService {
    private final SchedulingClassDao dao;
    private final UserCache userCache;
    private final JcptMobile jcptMobile;

    public void create() {
        DateTime now = DateTime.now();
        // 获取下一个月的日期
        String nextMonth = DateUtil.format(DateUtil.offsetMonth(now, 1), "yyyy-MM-dd");
        // 生成下一个月的数据
        createByMonth(nextMonth);
    }

    public void sendMessageData() {
        String now = DateUtil.format(DateTime.now(), "yyyy-MM-dd");
        SchedulingClass schedulingClass = dao.selectOne(SchedulingClass.lambdaQueryWrapper().eq(SchedulingClass::getSchedulingDate, now));
        String code = StrUtil.isNotBlank(schedulingClass.getChangeClass()) ? schedulingClass.getChangeClass() : schedulingClass.getCode();
        String phoneNo = dao.getCellPhoneNumber(code);
        if (StrUtil.isBlank(phoneNo)) {
            return;
        }
        JSONObject js = new JSONObject() {{
            putOnce("key", "zyb5beed2597b243608841cb719b5d4135");
            putOnce("id", "zb465551e87fdf4146aa745492c99a28d1");
            putOnce("data", new JSONArray() {{
                add(new JSONObject() {{
                    putOnce("phone", phoneNo);
                }});
            }});
        }};

        HttpRequest.post("http://172.16.32.167:9205/thyy/api/public/sms/sendMessageOne").body(js.toJSONString(0)).execute().body();
    }


    public List<CodeName> getCodes() {
        return dao.getXinXiKeCode();
    }

    public ResultVo<String> createByMonth(String month) {
        CreateMonth createMonth = new CreateMonth(month, getSortAndName());
        List<SchedulingClass> computed = createMonth.computed();
        if (dao.selectCount(SchedulingClass.lambdaQueryWrapper()
                .ge(SchedulingClass::getSchedulingDate, createMonth.getFirstDayOfMonth())
                .le(SchedulingClass::getSchedulingDate, createMonth.getLastDayOfMonth())) > 0) {
            return R.fail(ExceptionEnum.LOGICAL_ERROR, "已经存在数据了无法生成。");
        }
        dao.insert(computed);
        return R.ok(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }


    public List<CodeName> getSortAndName() {
        String codes = dao.getSort();
        return JSONUtil.toList(codes, CodeName.class);
    }

    public ResultVo<String> saveSort(JSONObject value) {
        dao.updateDictData(value.getStr("data"));
        return R.ok(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }

    public List<SchedulingClass.SchedulingClassVo> getByMonth(String month) {
        Result result = getResult(month);
        List<SchedulingClass.SchedulingClassVo> rst = dao.selectByDateVo(SchedulingClass.lambdaQueryWrapper()
                .ge(SchedulingClass::getSchedulingDate, result.firstDayOfMonth)
                .le(SchedulingClass::getSchedulingDate, result.lastDayOfMonth)
                .orderByAsc(SchedulingClass::getSchedulingDate)
        );
        for (SchedulingClass.SchedulingClassVo item : rst) {
            if (StrUtil.isNotBlank(item.getFalseCode())) {
                item.setFalseCodeList(new ArrayList<>());
                List<String> split = StrUtil.split(item.getFalseCode(), ",");
                split.forEach(i -> {
                    String employeeName = userCache.getEmployeeName(i);
                    item.getFalseCodeList().add(new SimpleCodeName(i, employeeName));
                });
            }
        }
        return rst;
    }

    private @NotNull Result getResult(String month) {
        DateTime parse = DateUtil.parse(month, "yyyy-MM");
        // 获取第一个月
        DateTime firstDayOfMonth = thyyxxk.webserver.utils.DateUtil.beginOfMonth(parse);
        // 获取最后一个月
        DateTime lastDayOfMonth = thyyxxk.webserver.utils.DateUtil.endOfMonth(parse);
        return new Result(firstDayOfMonth, lastDayOfMonth);
    }

    private static class Result {
        public final DateTime firstDayOfMonth;
        public final DateTime lastDayOfMonth;

        public Result(DateTime firstDayOfMonth, DateTime lastDayOfMonth) {
            this.firstDayOfMonth = firstDayOfMonth;
            this.lastDayOfMonth = lastDayOfMonth;
        }
    }

    public ResultVo<String> updateById(SchedulingClass data) {
        DateTime now = DateUtil.parse(DateUtil.format(DateTime.now(), "yyyy-MM-dd") + " 17:20:20");
        SchedulingClass schedulingClass = dao.selectById(data.getId());
        if (schedulingClass == null) {
            return R.fail(ExceptionEnum.LOGICAL_ERROR, "没有找到数据");
        }
        DateTime dateTime = DateTime.of(schedulingClass.getSchedulingDate());
        if (DateUtil.isSameDay(now, dateTime) && DateTime.now().compareTo(now) > 0) {
            return R.fail(ExceptionEnum.LOGICAL_ERROR, "数据固话无法修改。");
        }
        dao.updateById(data);
        return R.ok(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }

}
