<template>
	<el-container class="is-vertical">
        <sc-page-header v-if="!selectable" @add="table_add()"></sc-page-header>
        
        <scTable ref="xGridTable" :apiObj="$API.production.bom" :formConfig="formConfig" :paramsColums="paramsColums" :columns="columns" :treeConfig="treeConfig" v-bind="options" v-on="tableEvents">
            <template #code_link="{ row }">
                <vxe-text v-if="row.parentId === '0'" status="primary" @click="table_detail(row)">{{ row.bomCode }}</vxe-text>
            </template>

            <template #action="{ row }">
                <el-button v-if="!row.isHaveChildren" type="primary" link @click="table_add(row)">
                    <template #icon><sc-iconify icon="ant-design:cloud-upload-outlined"></sc-iconify></template>新增
                </el-button>
                <el-button v-else type="primary" link @click="table_edit(row)">
                    <template #icon><sc-iconify icon="ant-design:edit-outlined"></sc-iconify></template>修改
                </el-button>

                <template v-if="row.parentId == 0">
                    <el-button v-if="row.status == 'enable'" type="primary" link @click="table_change(row)">
                        <template #icon><sc-iconify icon="material-symbols:lock-outline"></sc-iconify></template>停用
                    </el-button>
                    <el-button v-else type="primary" link @click="table_change(row)">
                        <template #icon><sc-iconify icon="material-symbols:lock-open-outline"></sc-iconify></template>启用
                    </el-button>
                </template>

                <el-button v-if="!row.isHaveChildren" type="primary" link @click="table_del(row)">
                    <template #icon><sc-iconify icon="ant-design:delete-outlined"></sc-iconify></template>删除
                </el-button>
            </template>
        </scTable>
	</el-container>

    <bom-detail v-if="dialog.detail" ref="bomRef" @success="refreshTable" @closed="dialog.detail = false"></bom-detail>
    <bom-desc v-if="dialog.desc" ref="bomDescRef" @closed="dialog.desc = false"></bom-desc>
</template>

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

import API from "@/api";
import TOOL from "@/utils/tool";
import { statusDic } from "@/utils/basicDic";
import { mapFormItemInput, mapFormItemSelect, mapFormItemDatePicker, mapFormItemTenant } from "@/components/scTable/helper";
import bomDetail from "./detail";
import bomDesc from "./desc";

import store from "@/store";
watch(() => store.state.tenant.tenantId, () => refreshTable());

const props = defineProps({
    selectable: { type: Boolean, default: false },
    multiple: { type: Boolean, default: false },
    paramsColums: { type: Array, default: () => [] },
    options: { type: Object, default: () => ({}) }
});

const formQueryData = reactive({});

const treeConfig = reactive({
    lazy: true,
    hasChildField: "isHaveChildren",
    loadMethod: ({ row }) => API.production.bom.getChild({ parentId: row.id, ...XEUtils.pick(formQueryData, (_, key) => XEUtils.includes(["materialCodeLike", "materialNameLike", "routeId"], key)) })
});

const routeConfig = reactive({
    api: { key: "process.line", query: { orderBy: "createTime_desc", parentId: "0", status: "enable" } },
    optionProps: { label: "name", value: "id" },
    events: {
        change: data => XEUtils.merge(formConfig.data, data)
    }
});

const selectConfig = reactive({
    options: statusDic,
    events: {
        change: data => XEUtils.merge(formConfig.data, data)
    }
});

const daterangeConfig = reactive({
    resetValue: () => [],
    props: {
        type: "daterange",
        startPlaceholder: "开始日期",
        endPlaceholder: "结束日期",
        format: "YYYY-MM-DD"
    }
});

const formConfig = reactive({
    data: {},
    items: computed(() => props.selectable ? [
        mapFormItemInput("materialCodeLike", "产品编码"),
        mapFormItemInput("materialNameLike", "产品名称")
    ]: [
        mapFormItemTenant({ events: { change: data => XEUtils.merge(formConfig.data, { ...data, routeId: undefined }) } }),
        mapFormItemInput("materialCodeLike", "产品编码"),
        mapFormItemInput("materialNameLike", "产品名称"),
        mapFormItemInput("bomCodeLike", "BOM单编号"),
        mapFormItemSelect("status", "BOM单状态", selectConfig),
        mapFormItemSelect("routeId", "工艺路线", routeConfig),
        mapFormItemDatePicker("createTime", "创建日期", daterangeConfig)
    ])
});

const paramsColums = reactive([
    { column: "orderBy", defaultValue: "createTime_desc" },
    { column: "parentId", defaultValue: "0" },
    { column: "tenantId" },
    { column: "materialCodeLike" },
    { column: "materialNameLike" },
    { column: "bomCodeLike" },
    { column: "status" },
    { column: "routeId" },
    { column: "createTimeBegin", field: "createTime[0]" },
    { column: "createTimeEnd", field: "createTime[1]" },
    ...props.paramsColums
]);

const columns = computed(() => props.selectable ? [
    { type: props.multiple && "checkbox" || "radio", fixed: "left", width: 40 },
    // { visible: computed(() => !XEUtils.isNull(XEUtils.get(props.options, "treeConfig"))), type: "html", field: "materialCode", title: "产品编码", fixed: "left", minWidth: 200, treeNode: true, headerAlign: "center", align: "left", sortable: true },
    // { visible: computed(() => XEUtils.isNull(XEUtils.get(props.options, "treeConfig"))), type: "html", field: "materialCode", title: "产品编码", fixed: "left", minWidth: 200, sortable: true },
    { type: "html", field: "materialCode", title: "产品编码", fixed: "left", minWidth: 200, sortable: true },
    { type: "html", field: "materialName", title: "产品名称", fixed: "left", minWidth: 150, sortable: true },
    { type: "html", field: "material.specification", title: "规格型号", minWidth: 120, sortable: true },
    { type: "html", field: "quantity", title: "标准用量", minWidth: 100, sortable: true },
    { type: "html", field: "material.unit", title: "单位", minWidth: 100, sortable: true }
] : [
    { type: "seq", fixed: "left", width: 80 },
    { visible: computed(() => store.state.tenant.tenantId === "0"), type: "html", field: "tenantName", title: "所属租户", fixed: "left", minWidth: 200, sortable: true, formatter: ({ cellValue, row }) => row.parentId === "0" ? cellValue || XEUtils.get(XEUtils.find(store.state.tenant.tenants, item => item.id == row.tenantId), "name") : "" },
    { type: "html", field: "materialCode", title: "产品编码", fixed: "left", minWidth: 200, treeNode: true, headerAlign: "center", align: "left", sortable: true },
    { type: "html", field: "materialName", title: "产品名称", fixed: "left", minWidth: 150, sortable: true },
    { field: "bomCode", title: "BOM单编号", minWidth: 150, sortable: true, className: "vxe-table-link-cell", slots: { default: "code_link" } },
    { field: "status", title: "BOM单状态", minWidth: 120, editRender: { name: "$cell-tag", options: statusDic } },
    { visible: true, type: "html", field: "routeName", title: "工艺路线", minWidth: 150, sortable: true },
    { type: "html", field: "createTime", title: "创建日期", minWidth: 120, sortable: true, formatter: ({ cellValue }) => TOOL.dateFormat(cellValue, "YYYY-MM-DD") || cellValue },
    { visible: false, type: "html", field: "remark", title: "概要", minWidth: 300, sortable: true },
    { title: "操作", fixed: "right", width: 220, slots: { default: "action" } }
]);

// 显示隐藏 筛选表单
const xGridTable = ref();
const refreshTable = (mode = "add") => (xGridTable.value.searchData(mode), xGridTable.value.reloadColumn(columns.value));

const bomRef = ref();
const bomDescRef = ref();
const dialog = reactive({
    detail: false,
    desc: false
});

const table_add = (row = {}) => {
    dialog.detail = true;
    nextTick(() => bomRef.value?.setData(row));
}

const table_edit = row => {
    dialog.detail = true;
    nextTick(() => bomRef.value?.setData(row, "edit"));
}

const table_detail = row => {
    dialog.desc = true;
    nextTick(() => bomDescRef.value?.setData(row));
}

const table_del = ({ id }) => {
    ElMessageBox.confirm("是否确认删除该BOM清单?", "删除警告", {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
    }).then(() => {
        API.production.bom.del({ id }).then(() => {
            ElMessage.success("操作成功");
            refreshTable();
        });
    }).catch(() => {});
}

const table_change = row => {
    const status = row.status == "enable" && "disable" || "enable";
    const msg = row.status == "enable" && "停用" || "启用";

    ElMessageBox.confirm(`是否确认${msg}该BOM清单?`, `${msg}警告`, {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
    }).then(() => {
        API.production.bom.edit({ id: row.id, status }).then(() => {
            ElMessage.success("操作成功");
            refreshTable();
        });
    }).catch(() => {});
}

const tableEvents = {
    tableSearch: data => (XEUtils.clear(formQueryData), XEUtils.merge(formQueryData, data)),
    tableReset: data => (XEUtils.clear(formQueryData), XEUtils.merge(formQueryData, data))
}

defineExpose({
    getSelectRows: () => xGridTable.value.getSelectRows()
});
</script>