<template>
    <el-dialog v-model="visible" :title="titleMap[mode]" fullscreen :close-on-click-modal="false" @closed="$emit('closed', isDel)">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120">
            <el-collapse v-model="activeNames">
                <el-collapse-item title="基本信息" name="basic">
                    <el-row>
                        <el-col v-if="$store.state.tenant.tenantId === '0'" :md="8" :xs="24">
                            <el-form-item label="所属租户" prop="tenantId">
                                <el-select v-if="!form.id" v-model="form.tenantId" filterable placeholder="请选择所属租户">
                                    <el-option v-for="item in $store.state.tenant.tenants" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                </el-select>
                                <el-input v-else v-model="tenantName" readonly></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :md="8" :xs="24">
                            <el-form-item label="工艺路线名称" prop="name">
                                <el-input v-model="form.name" placeholder="请输入工艺路线名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :md="8" :xs="24">
                            <el-form-item label="工艺路线编号" prop="code">
                                <el-input v-model="form.code" :readonly="mode == 'edit'" maxlength="50" show-word-limit clearable placeholder="不填将自动生成"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :md="8" :xs="24">
                            <el-form-item label="时间单位">
                                <el-radio-group v-model="form.timeUnit">
                                    <el-radio v-for="(label, key) in processDic.timeUnit" :key="key" :label="label" :value="key"></el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :md="8" :xs="24">
                            <el-form-item label="版本号" prop="version">
                                <el-input v-model="form.version" :readonly="mode == 'edit'" placeholder="v1.0.0"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-collapse-item>

                <el-collapse-item title="加工路线" name="line">
                    <sc-form-table ref="formTableRef" v-model="form.detailList" v-bind="tableOptions"></sc-form-table>
                </el-collapse-item>

                <!-- <el-collapse-item title="质检方案" name="plan">
                    inspectProgramId
                </el-collapse-item> -->

                <el-collapse-item title="其他说明" name="other">
                    <el-row>
                        <el-col :xs="24">
                            <el-form-item label="概要" label-width="100">
                                <el-input v-model="form.remark" type="textarea" maxlength="200" :rows="4" placeholder="请输入内容"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24">
                            <el-form-item label="附件" label-width="100">
                                <sc-upload-file v-model="form.fileList" isNested @removeSuccess="removeSuccess">
                                    <el-row>
                                        <el-col :xs="24">
                                            <vxe-button status="primary" size="mini" content="上传附件"></vxe-button>
                                        </el-col>
                                        <el-col :xs="24">
                                            <sc-upload-file v-model="oldData.fileList" disabled hideAdd></sc-upload-file>
                                        </el-col>
                                    </el-row>
                                </sc-upload-file>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-collapse-item>
            </el-collapse>
        </el-form>

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

<script setup>
import XEUtils from "xe-utils";

import API from "@/api";
import store from "@/store";
import { processDic } from "@/utils/basicDic";
import { tableOptions } from "./main";
import scUploadFile from "@/components/scUpload/file";

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

const activeNames = ref(["basic", "line", "other"]);
const mode = ref("add");
const titleMap = reactive({
    add: "新增工艺路线",
    edit: "修改工艺路线",
    upgrade: "发布新版本"
});

provide("tenantId", computed(() => form.value.tenantId));
const tenantName = computed(() => XEUtils.get(XEUtils.find(store.state.tenant.tenants, item => item.id == form.value.tenantId), "name"));
const oldData = reactive({
    code: null,
    version: null,
    fileList: []
});
const form = ref({
    id: null,
    parentId: null,
    tenantId: store.state.tenant.tenantId,
    name: null,
    code: null,
    timeUnit: "minute",
    version: "v1.0.0",
    detailList: [],
    remark: null,
    fileList: []
});
const rules = reactive({
    tenantId: [{ required: true, message: "请选择所属租户" }],
    code: [{ required: true, validator: (rule, value, callback) => {
        if (mode.value === "upgrade" && value === oldData.code) return callback(new Error("请清空或更新工艺路线编号"));
        callback();
    }}],
    name: [{ required: true, message: "请输入工艺路线名称" }],
    version: [
        { required: true, message: "请输入版本号" },
        { validator: (rule, value, callback) => {
            if (mode.value === "upgrade" && value === oldData.version) return callback(new Error("请更新版本号"));
            callback();
        }}
    ]
});

const open = () => visible.value = true;
const setData = (data, modeKey = "edit") => {
    open();
    mode.value = modeKey;
    XEUtils.objectEach(form.value, (_, key) => {
        if (XEUtils.has(oldData, key)) {
            let keyValue = XEUtils.get(data, key);
            if (key == "fileList") keyValue = XEUtils.map(XEUtils.get(data, key), item => ({ ...item, name: item.fileName }));
            
            if (modeKey === "upgrade") {
                XEUtils.set(oldData, key, keyValue);
                XEUtils.set(form.value, key, key == "fileList" ? [] : null);
            } else XEUtils.set(form.value, key, keyValue);
        } else if (key == "detailList") XEUtils.set(form.value, key, XEUtils.map(XEUtils.get(data, key), item => ({ ...item.stage, ...XEUtils.omit(item, "id", "stage") })));
        else XEUtils.set(form.value, key, XEUtils.get(data, key));
    });
}

const formRef = ref();
const formTableRef = ref();
const submit = () => {
    formRef.value.validate(async valid => {
        if (valid) {
            if (!form.value.detailList.length) return ElMessage.warning("请添加加工路线信息后再保存");
            
            if (await formTableRef.value.validateFormTable()) {
                const data = XEUtils.omit(form.value, "detailList", "fileList");
                const detailList = XEUtils.map(form.value.detailList, item => XEUtils.omit(item, "id", "name", "code", "processType"));
                XEUtils.set(data, "detailList", detailList);
                
                let fileList = XEUtils.map(XEUtils.filter(form.value.fileList, item => !item.id), item => ({ ...XEUtils.omit(item, "id", "name"), fileName: item.name, fileType: "processLineAttach" }));
                if (mode.value == "upgrade") fileList = fileList.concat(XEUtils.map(oldData.fileList, item => ({ ...XEUtils.omit(item, "id", "name"), fileName: item.name, fileType: "processLineAttach" })));
                fileList.length > 0 && XEUtils.set(data, "fileList", fileList);

                isSaving.value = true;
                API.process.line[mode.value](data).then(res => {
                    ElMessage.success("操作成功");
                    isSaving.value = false;
                    isDel.value = false;
                    visible.value = false;
                    $emit("success", mode.value);
                }).catch(() => isSaving.value = false);
            }
        } else {
            return false;
        }
    });
}

const removeSuccess = () => {
    if (form.value.id) isDel.value = true;
}

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

<style scoped>
.el-form {padding-left: 16px;padding-right: 22px;}

.el-collapse {border: none;}
.el-collapse-item {margin-top: 15px;padding: 0 24px;background-color: var(--el-fill-color-blank);border: 1px solid var(--el-border-color-light);border-radius: 4px;color: var(--el-text-color-primary);box-shadow: var(--el-box-shadow-light);transition: var(--el-transition-duration);}
.el-collapse-item :deep(.el-collapse-item__header) {border-bottom-color: transparent;line-height: 55px;font-size: 16px;font-weight: bold;}
.el-collapse-item :deep(.el-collapse-item__header.is-active) {border-bottom: 1px solid var(--el-border-color-lighter);}
.el-collapse-item :deep(.el-collapse-item__wrap) {border: none;}
.el-collapse-item :deep(.el-collapse-item__content) {padding: 20px 28px 20px 0;}
.el-collapse-item:nth-child(2) :deep(.el-collapse-item__content) {padding-right: 0;}
</style>