
<template>
    <ele-modal width="1260px" :visible="visible" v-if="visible" :append-to-body="true" :close-on-click-modal="false"
        custom-class="ele-dialog-form" title="选择物料" @update:visible="updateVisible">
        <header-title title="基本信息"></header-title>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
                <el-col :span="8">


                    <el-form-item label="产品名称:" prop="name">
                        <el-input disabled v-model="form.name" readonly />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="产品编码:" prop="code">
                        <el-input disabled v-model="form.code" placeholder="自动带入" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="型号:" prop="modelType">
                        <el-input disabled v-model="form.modelType" placeholder="自动带入" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="牌号:" prop="brandNum">
                        <el-input disabled v-model="form.brandNum" placeholder="自动带入" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="规格:" prop="specification">
                        <el-input disabled v-model="form.specification" placeholder="自动带入" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="计量单位:" prop="measuringUnit">
                        <el-input disabled v-model="form.measuringUnit" placeholder="自动带入" />
                    </el-form-item>
                </el-col>
            </el-row>


            <el-button type="primary" size="small" style="margin-bottom: 10px;" @click="handleAddTab">添加工序</el-button>

            <el-tabs v-model="tabsValue" type="card" closable @tab-click="handleTab" @tab-remove="removeTab">
                <el-tab-pane v-for="(item, index) in tabsList" :key="item.id + index" :label="item.name" :name="item.id">



                    <header-title title="物料BOM" style="margin-top: 10px">
                        <div>
                            <el-button size="small" icon="el-icon-plus" class="ele-btn-icon" type="primary"
                                @click="handleAdd(item.id)">新增</el-button>
                        </div>
                    </header-title>

                    <el-card v-for="(bomItem, index) in form.bomList" :key="index">
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="BOM编码:">
                                    {{ bomItem.code }}
                                </el-form-item>
                            </el-col>

                            <el-col :span="8">
                                <el-form-item label="BOM名称:" prop="name">
                                    {{ bomItem.name }}
                                </el-form-item>
                            </el-col>

                            <el-col :span="8">
                                <el-form-item label="版本号:" prop="version">
                                    {{ bomItem.version }}
                                </el-form-item>
                            </el-col>

                            <el-col :span="8">
                                <el-form-item label="状态:" prop="status">
                                    <el-select v-model="bomItem.status" placeholder="" filterable disabled>
                                        <el-option v-for="item in statusList" :key="item.value" :label="item.label"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>



                            <el-col :span="8">
                                <el-form-item label="所属工厂:" prop="factoryId">
                                    <factorySelect v-model="bomItem.factoryId" disabled />
                                </el-form-item>
                            </el-col>

                            <el-col :span="8">
                                <el-form-item label="基本数量:" prop="baseCount">
                                    <el-row>
                                        <el-col :span="12">
                                            {{ bomItem.baseCount }}
                                        </el-col>
                                        <el-col :span="2">&nbsp;</el-col>
                                        <el-col :span="10">
                                            <DictSelection disabled dictName="计量单位:" v-model="bomItem.baseCountUnit" />
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <div class="ele-body">
                                <ele-pro-table ref="table" :columns="columns" :need-page="false" row-key="id"
                                    :datasource="bomItem.subDetailList" min-height="200px">

                                    <template v-slot:isReworkBom="{ row }">
                                        {{ row.isReworkBom ? '是' : '否' }}
                                    </template>

                                    <template v-slot:bomArtFiles="{ row }">

                                        <div v-if="row.bomArtFiles && row.bomArtFiles?.length">
                                            <el-link v-for="link in row.bomArtFiles" :key="link.id" type="primary"
                                                :underline="false" @click="downloadFile(link)">
                                                {{ link.name }}</el-link>
                                        </div>

                                    </template>

                                    <template v-slot:toolbar>
                                        <el-button type="primary" size="small" @click="openEdit(index)">编辑</el-button>

                                        <el-popconfirm class="ele-action" title="确定要删除此物料BOM？" @confirm="remove(bomItem)">
                                            <template v-slot:reference>
                                                <el-button type="danger" size="small" icon="el-icon-delete">
                                                    删除
                                                </el-button>
                                            </template>
                                        </el-popconfirm>
                                    </template>
                                </ele-pro-table>
                            </div>
                        </el-row>
                    </el-card>


                </el-tab-pane>



            </el-tabs>






        </el-form>

        <!-- 物料Bom -->
        <MaterialAdd :visible.sync="materialShow" :taskId="taskId" :data="current" :categoryId="categoryId" @done="done"
            ref="materialAddRef">
        </MaterialAdd>

        <!-- 添加工序 -->

        <ele-modal width="1720px" :visible="addDialog" :append-to-body="true" :close-on-click-modal="false"
            @update:visible="closeAdd">
            <Production :tableData="tableData" ref="ProductionCom" />
            <template v-slot:footer>
                <el-button @click="closeAdd">取消</el-button>
                <el-button type="primary" @click="addParamrter">
                    添加
                </el-button>
            </template>
        </ele-modal>

    </ele-modal>
</template>
  
<script>

import MaterialAdd from './MaterialAdd.vue';
import { pageList } from '@/api/technology/version/version.js';
import { getCategoryBom } from '@/api/material/product';
import { bomDelete, saveBatch, bomTaskList, bomTaskDelete, getByTaskId } from '@/api/material/BOM';
import factorySelect from '@/components/CommomSelect/factory-select.vue';
import Production from '@/views/technology/route/components/production/index.vue'
import { getFile } from "@/api/system/file";

export default {
    components: {
        MaterialAdd,
        factorySelect,
        Production
    },
    props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object
    },
    data() {
        const defaultForm = {
            id: null,

            code: '',
            name: '',
            modelType: '',
            brandNum: '',
            specification: '',
            measuringUnit: '',

            bomList: []
        };
        return {
            defaultForm,
            // 表单数据
            form: {
                ...defaultForm
            },

            versionList: [],

            // 表单验证规则
            rules: {
                categoryName: [
                    { required: true, message: '请输入产品名称', trigger: 'blur' }
                ]
            },

            columns: [
                {
                    type: 'index',
                    width: 55,
                    align: 'center'
                },
                {
                    label: '子项编号',
                    prop: 'subCode',
                    action: 'subCode'
                },
                {
                    label: '物料名称',
                    prop: 'categoryName',
                    action: 'categoryName'
                },

                {
                    label: '是否回收料',
                    prop: 'isReworkBom',
                    action: 'isReworkBom',
                    slot: 'isReworkBom',
                    width: 95,
                },

                {
                    label: '物料编码',
                    prop: 'categoryCode'
                },
                {
                    label: '牌号',
                    prop: 'brandNum'
                },
                {
                    label: '型号',
                    prop: 'modelType'
                },
                {
                    label: '数量',
                    prop: 'count'
                },
                {
                    label: '计量单位',
                    prop: 'unit'
                },


                {
                    label: '附件',
                    slot: 'bomArtFiles',
                    action: 'bomArtFiles',
                    minWidth: 100,
                },



                {
                    label: '单位',
                    prop: 'weightUnit'
                },

                {
                    label: '备注',
                    prop: 'remark',
                },

            ],

            statusList: [
                { label: '草稿', value: -1 },
                { label: '失效', value: 0 },
                { label: '生效', value: 1 }
            ],

            // 提交状态
            loading: false,

            categoryId: null,

            current: null,

            materialShow: false,

            tabsList: [],
            tableData: [],


            taskId: null,

            addDialog: false,
            tabsValue: null
        };
    },
    computed: {
        // 是否开启响应式布局
        styleResponsive() {
            return this.$store.state.theme.styleResponsive;
        }
    },
    methods: {

        downloadFile(file) {
            getFile({ objectName: file.storePath }, file.name);
        },

        openEdit(index) {
            this.current = this.form.bomList[index];
            this.materialShow = true;
        },

        /* 表格数据源 */
        datasource({ page, limit, where }) {
            return [];
        },

        async getVersionList() {
            const res = await pageList({
                pageNum: 1,
                size: 100
            });

            this.versionList = res.list;
        },

        handleAdd(id) {
            this.taskId = id
            this.current = null;
            this.materialShow = true;
        },

        /* 更新visible */
        updateVisible(value) {
            this.$emit('update:visible', value);
        },

        async getCategoryBomFn(taskId) {
            const res = await getByTaskId(this.categoryId, taskId);
            this.form.bomList = res;
        },

        remove(row) {
            bomDelete([row.id])
                .then((message) => {
                    this.$message.success(message);
                    this.getCategoryBomFn();
                })
                .catch((e) => {
                    this.$message.error(e.message);
                });
        },

        done(taskId) {
            this.materialShow = false
            this.getCategoryBomFn(taskId);
        },

        handleAddTab() {
            this.tableData = this.tabsList
            this.addDialog = true;
        },

        handleTab(e) {
            this.getCategoryBomFn(e.name);
        },

        removeTab(targetName) {

            this.$confirm('是否删除当前工序?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {

                    this.tabsList.forEach(e => {
                        if (e.id == targetName) {
                            bomTaskDelete([e.oldId]).then(res => {
                                this.taskListHead()
                            })
                        }
                    })
                })
                .catch(() => { });




        },

        /*关闭选择参数*/
        closeAdd() {
            this.$refs.ProductionCom.$refs.table.setSelectedRows([]);
            this.addDialog = false;
        },

        addParamrter() {
            let arr = [];
            arr = this.$refs.ProductionCom.selection.map(m => {
                return {
                    sourceTaskId: m.id,
                    ...m
                }
            })
            if (arr.length == 0) {
                this.addDialog = false;
                return false
            }
            this.tabsList = arr
            this.addDialog = false;
            this.$refs.ProductionCom.$refs.table.setSelectedRows([]);
            if (this.tabsList.length > 0) {
                this.tabsValue = this.tabsList[0].id
                this.saveBatchFn()
            }



        },

        // 保存
        saveBatchFn() {
            let arr = [];
            arr = this.tabsList.map(m => {
                return {
                    taskId: m.id,
                    sort: m.sort,
                    categoryId: this.categoryId
                }
            })

            saveBatch(arr).then(res => {
                this.taskListHead()
            })
        },

        taskListHead(isFirst) {
            console.log(isFirst)
            bomTaskList(this.categoryId).then(res => {
                let arr = []
                arr = res.map(m => {
                    return {
                        oldId: m.id,
                        sourceTaskId: m.id,
                        id: m.taskId,
                        name: m.taskName
                    }
                })
                this.tabsList = arr

                if (isFirst && this.tabsList.length > 0) {
                    this.tabsValue = this.tabsList[0].id
                    this.getCategoryBomFn(this.tabsList[0].id);
                }
            })


        },

    },

    watch: {
        async visible(visible) {
            if (visible) {
                this.getVersionList();

                if (this.data) {
                    this.categoryId = this.data.id;

                    this.$util.assignObject(this.form, {
                        ...this.data
                    });
                } else {
                }

                this.taskListHead(true)
            } else {
                this.$refs.form.clearValidate();
                this.form = { ...this.defaultForm };
            }
        }
    }
};
</script>



<style lang="scss" scoped></style>
  