package com.jwipc.order.controller.pc;

import cn.hutool.core.collection.CollectionUtil;
import com.jwipc.exception.DaoException;
import com.jwipc.order.dto.AppointmentPurchaseListDTO;
import com.jwipc.order.logic.AppointmentPurchaseLogic;
import com.jwipc.order.model.query.AppointmentPurchaseQuery;
import com.jwipc.security.LoginUtil;
import com.jwipc.sys.client.SysConfigClient;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;

import java.util.Collections;
import java.util.List;

import static com.jwipc.order.constant.ModuleConst.MODULE_ROOT;

/**
 * <p>
 * 低值供应商采购类预约 前端控制器
 * </p>
 *
 * @author WT
 * @since 2024-03-06
 */
@Controller
@RequiredArgsConstructor
@RequestMapping(MODULE_ROOT + "/appointmentPurchase")
public class AppointmentPurchasePageController {

    private final AppointmentPurchaseLogic appointmentPurchaseLogic;
    private final SysConfigClient sysConfigClient;

    /**
     * 低值供应商采购类型预约&变更&查看
     *
     * @param model
     * @param ids   主键ids
     * @param type  1新增 2变更
     * @return
     */
    @GetMapping("/detail")
    public String detail(Model model, String ids, String type) {
        if (StringUtils.equals("2", type) && StringUtils.isEmpty(ids)) {
            throw new DaoException("变更数据有误");
        }
        //编辑时  如果只有一个ID 则自动带出 表头信息
        if (StringUtils.equals("2", type)) {
            String[] split = ids.split(",");
            if (split.length == 1) {
                AppointmentPurchaseQuery query = new AppointmentPurchaseQuery();
                query.setIds(Collections.singletonList(split[0]));
                List<AppointmentPurchaseListDTO> purchaseList = appointmentPurchaseLogic
                        .selectDataByQuery(query);
                if (CollectionUtil.isNotEmpty(purchaseList)) {
                    model.addAttribute("data", purchaseList.get(0));
                }
            }
        }

        String appointmentDate = sysConfigClient.getTextConfig("appointment_date");
        if (StringUtils.isBlank(appointmentDate)) {
            appointmentDate = "5";
        }
        model.addAttribute("limitDate", appointmentDate);
        model.addAttribute("ids", ids);
        model.addAttribute("viewType", type);
        model.addAttribute("supplierCode", LoginUtil.getAccount());
        return MODULE_ROOT + "/delivery/appointmentPurchase/detail";
    }

    /**
     * 预约记录的查看页面内
     *
     * @param model
     * @param id   预约记录的id
     * @return 查看页面
     */
    @GetMapping("/lookUp")
    public String lookUp(Model model, String id) {
        model.addAttribute("id", id);
        return MODULE_ROOT + "/delivery/appointmentRecord/look_up";
    }

}
