<template>
    <el-dialog v-model="visible" :title="`${form.projectName}-验收清单`" width="860" :close-on-click-modal="false" @closed="$emit('closed')">
        <el-form ref="formRef" :model="form" label-width="120">
            <el-form-item required>
                <template #label>
                    <el-tooltip placement="top">
                        <i class="vxe-icon-question-circle-fill"></i>
                        <template #content>
                            &nbsp;&nbsp;&nbsp;&nbsp;A级智慧化工地：18项基础项<br />
                            &nbsp;&nbsp;AA级智慧化工地：18项基础项、不少于10项推广项（包含必选项），2项非必选推广项可替代1项必选推广项<br />
                            AAA级智慧化工地：18项基础项、不少于20项推广项（包含必选项）、2项提升项（包含必选项），2项非必选提升项可替代1项必选提升项
                        </template>
                    </el-tooltip>申报等级
                </template>
                <el-radio-group v-model="form.starLevel" @change="changeLevel">
                    <el-radio label="A"></el-radio>
                    <el-radio label="AA"></el-radio>
                    <el-radio label="AAA"></el-radio>
                </el-radio-group>
            </el-form-item>

            <div class="items-statistic">{{ XEUtils.template(statisticTemp, statisticData) }}</div>
            <el-form-item label-width="0">
                <el-radio-group v-model="itemsLevel" @change="refreshTable">
                    <el-radio-button label="基础项" />
                    <el-radio-button v-if="form.starLevel == 'AA' || form.starLevel == 'AAA'" label="推广项" />
                    <el-radio-button v-if="form.starLevel == 'AAA'" label="提升项" />
                </el-radio-group>
            </el-form-item>

            <scTable ref="xGridTable" :maxHeight="1048" :columns="columns" :options="options">
                <template #checked_content="{ row }">
                    <el-checkbox v-model="row.checked"></el-checkbox>
                </template>

                <template #checked_replace="{ row }">
                    <el-checkbox v-if="row.acceptItemType.includes('必选项')" v-model="row.replaceIds" true-value="1" :false-value="0"></el-checkbox>&nbsp;&nbsp;
                    <!-- <div v-if="row.acceptItemType.includes('必选项')" class="replace-content">
                        <el-select v-model="row.replaceIds" multiple collapse-tags collapse-tags-tooltip placeholder="选择替换推广项">
                            <el-option v-for="item in XEUtils.filter(acceptItems, acc => acc.acceptItemType == '推广项')" :key="item.id" :label="item.acceptItem" :value="item.id"></el-option>
                        </el-select>
                    </div> -->
                </template>

                <template #date_picker_begin="{ row }">
                    <el-date-picker v-model="row.beginTime" :disabled-date="date => disabledDate(date, row, 'beginTime')" value-format="YYYY-MM-DD 00:00:00" placeholder="选择开始时间"></el-date-picker>
                </template>

                <template #date_picker_end="{ row }">
                    <el-date-picker v-model="row.endTime" :disabled-date="date => disabledDate(date, row, 'endTime')" value-format="YYYY-MM-DD 23:59:59" placeholder="选择结束时间"></el-date-picker>
                </template>
            </scTable>
        </el-form>

        <template #footer>
            <el-button :loading="isSaving" type="primary" auto-insert-space @click="submit">保存</el-button>
            <el-button auto-insert-space @click="visible = false">取消</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import moment from "moment";
import XEUtils from "xe-utils";
import API from "@/api";
import { categoryDic, statisticTemp } from "@/views/basic/acceptItems/main";

const $emit = defineEmits(["success", "closed"]);
const visible = ref(false);
const isSaving = ref(false);

const form = ref({
    projectId: null,
    projectName: null,
    starLevel: "A"
});

const itemsLevel = ref("基础项");
const acceptItems = ref([]);
const filterItem = value => XEUtils.filter(acceptItems.value, item => item.acceptItemType.includes(value))
const statisticData = reactive({
    b_length: computed(() => filterItem("基础项").length),
    p_length: computed(() => filterItem("推广项").length),
    i_length: computed(() => filterItem("提升项").length),
    b_select: computed(() => XEUtils.filter(filterItem("基础项"), item => item.checked).length),
    p_select: computed(() => XEUtils.filter(filterItem("推广项"), item => item.checked).length),
    i_select: computed(() => XEUtils.filter(filterItem("提升项"), item => item.checked).length),
    p_required: computed(() => XEUtils.filter(filterItem("推广项"), item => item.acceptItemType.includes("必选项") && item.checked).length),
    i_required: computed(() => XEUtils.filter(filterItem("提升项"), item => item.acceptItemType.includes("必选项") && item.checked).length)
})

const options = reactive({
    align: "center",
    formConfig: { enabled: false },
    pagerConfig: { enabled: false }
})
const columns = reactive([
    { type: "seq", width: 60 },
    { field: "itemCategoryName", title: "验收项类别", minWidth: 120, formatter: ({ cellValue, row }) => cellValue || XEUtils.get(categoryDic, row.itemCategory) },
    { field: "acceptItem", title: "验收项名称", minWidth: 160 },
    { field: "acceptItemType", title: "验收项级别", minWidth: 160 },
    { field: "checked", title: "选择", width: 80, slots: { default: "checked_content" } },
    { visible: computed(() => itemsLevel.value == "推广项" || itemsLevel.value == "提升项"), field: "replaceIds", title: "验收项替换", minWidth: 100, slots: { default: "checked_replace" } },
    { field: "beginTime", title: "数据开始时间", width: 160, slots: { default: "date_picker_begin" } },
    { field: "endTime", title: "数据结束时间", width: 160, slots: { default: "date_picker_end" } },
])

const disabledDate = (date, row, field) => {
    if (field == "beginTime" && XEUtils.get(row, "endTime")) return moment(date).diff(XEUtils.get(row, "endTime")) > 0
    if (field == "endTime" && XEUtils.get(row, "beginTime")) return moment(date).diff(XEUtils.get(row, "beginTime")) < 0
    return false
}

const open = () => visible.value = true;
const setData = ({ fpiId, projectName }) => {
    open();
    form.value.projectId = fpiId;
    form.value.projectName = projectName;
    getAcceptItems(fpiId);
}

const xGridTable = ref();
const refreshTable = () => {
    xGridTable.value.reloadColumn(columns);
    xGridTable.value.reloadData(filterItem(itemsLevel.value));
    xGridTable.value.toggleTableLoading(false);
}

const getAcceptItems = (projectId) => {
    nextTick(() => xGridTable.value?.toggleTableLoading(true));
    Promise.all([
        API.system.acceptItems.all({ orderBy: "itemCategory_asc,createTime_asc" }),
        API.system.project.bindItem.get({ projectId })
    ]).then(([itemsRes, infoRes]) => {
        let count = 0;
        XEUtils.arrayEach(itemsRes, item => {
            if (!XEUtils.get(infoRes, "data", []).length) {
                if (item.acceptItemType == "基础项" && count < 18) {
                    item.checked = true;
                    count++;
                }
            } else {
                form.value.starLevel = infoRes.starLevel;
                const selectInfo = XEUtils.find(XEUtils.get(infoRes, "data", []), info => info.itemId == item.id);
                selectInfo && XEUtils.merge(item, { checked: true, ...XEUtils.omit(XEUtils.pick(selectInfo, "beginTime", "endTime", "replaceIds"), val => XEUtils.isEmpty(val)) })
            }
        });
        
        acceptItems.value = itemsRes;
        refreshTable();
    }).catch(() => {
        nextTick(() => xGridTable.value?.toggleTableLoading(false));
        acceptItems.value = [];
    });
}
const changeLevel = e => {
    if (e == "A" || e == "AA" && itemsLevel.value == "提升项") {
        itemsLevel.value = "基础项";
        refreshTable();
    }
};

const formRef = ref();
const submit = () => {
    if (statisticData.b_select < 18) return ElMessage.warning("基础项不足18项");
    if (form.value.starLevel == "AA" && statisticData.p_select < 10) return ElMessage.warning("推广项不足10项");
    if (form.value.starLevel == "AAA" && statisticData.p_select < 20) return ElMessage.warning("推广项不足20项");
    if (form.value.starLevel == "AAA" && statisticData.i_select < 2) return ElMessage.warning("提升项不足20项");

    const query = XEUtils.omit(form.value, "projectName");
    XEUtils.set(query, "data", XEUtils.map(acceptItems.value, item => ({ itemId: item.id, ...XEUtils.pick(item, "beginTime", "endTime", "replaceIds") })));
    
    isSaving.value = true;
    API.system.project.bindItem.add(query).then(res => {
        isSaving.value = false;
        ElMessage.success("操作成功");
        visible.value = false;
    }).catch(() => isSaving.value = false);
}

defineExpose({
    open,
    setData
})
</script>

<style lang="scss" scoped>
.el-form {padding-right: var(--el-message-close-size, 16px);}
.el-form .el-main {padding: 0;}
.el-form-item :deep(.el-form-item__label) {align-items: center;}
.vxe-icon-question-circle-fill {cursor: help;margin-right: .25em;font-size: var(--vxe-ui-font-size-mini, 12px);}

.items-statistic {margin-bottom: 18px;padding-left: 8px;font-size: 15px;color: var(--el-color-primary);}
</style>