<template>
    <div class="module-container">
        <el-row type="flex" :gutter="10" class="module-flex">
            <el-col :span="10">
                <el-card shadow="hover">
                    <template #header>
                        <div class="card-header">
                            <span class="card-title">工艺路线</span>
                            <span>
                                <el-button size="mini" type="primary" @click="routeAdd" v-if="checkMenuLimit('room/craft/Add')">新增</el-button>
                            </span>
                        </div>
                    </template>
                    <div class="card-container">
                        <el-form :inline="true" :model="formData.filterForm" size="small">
                            <el-form-item prop="craftName">
                                <el-input v-model="formData.filterForm.craftName" placeholder="路线名称" clearable style="width: 160px"></el-input>
                            </el-form-item>
                            <el-form-item prop="projectCatagoryCode">
                                <el-select v-model="formData.filterForm.projectCatagoryCode" placeholder="选择业态" clearable style="width: 160px">
                                    <el-option v-for="item in dictionaryData.formatList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="getTreeTableList()">查询</el-button>
                            </el-form-item>
                        </el-form>
                        <el-table :data="tableData.treeTableList" v-loading="tableData.treeTableLoading" :height="props.resizeHeight - 252" stripe border fit @row-click="nodeClick">
                            <el-table-column prop="craftName" label="路线名称" minWidth="140" align="center"></el-table-column>
                            <el-table-column prop="lpCategoryName" label="类别" width="80" align="center"></el-table-column>
                            <el-table-column prop="projectCatagory" label="业态" minWidth="80" align="center"></el-table-column>
                            <el-table-column label="操作" width="80" align="center" fixed="right" class-name="table-flex-column-right">
                                <template #default="scope">
                                    <i class="tree-icon el-icon-edit-outline" @click="routeEdit(scope.row)" v-if="checkMenuLimit('room/craft/Edit')"></i>
                                    <i class="tree-icon el-icon-delete" @click="routeDel(scope.row)" v-if="checkMenuLimit('room/craft/Delete')"></i>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="14">
                <el-card shadow="hover">
                    <template #header>
                        <div class="card-header">
                            <span class="card-title">设备类型/标准内容</span>
                            <span style="display: flex;">
                                <el-button size="mini" type="primary" @click="relationType" :disabled="!tableData.selectNode" v-if="checkMenuLimit('room/craft/level/Join')">关联类型</el-button>
                                <el-upload
                                        action="device/deviceCraft/downloadTemplate"
                                        :headers="{Authorization: 'Bearer '+ token}"
                                        accept=".xlsx"
                                        :show-file-list="false"
                                        :on-success="uploadSuccess"
                                        v-if="checkMenuLimit('room/craft/Import')">
                                    <el-button size="mini" type="primary" style="margin-left: 8px">批量导入</el-button>
                                </el-upload>
                            </span>
                        </div>
                    </template>
                    <div class="card-container">
                        <el-table :data="tableData.tableList" v-loading="tableData.tableLoading" :height="props.resizeHeight - 242" row-key="id"
                                  stripe border fit lazy :load="loadTableList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                            <el-table-column label="内容" minWidth="180" header-align="center" align="left">
                                <template #default="scope">{{scope.row.name || scope.row.colName}}</template>
                            </el-table-column>
                            <el-table-column prop="colType" label="任务类型" width="140" align="center"></el-table-column>
                            <el-table-column prop="isReq" label="是否必填" width="100" align="center"></el-table-column>
                            <el-table-column label="操作" width="110" align="center" fixed="right" class-name="table-flex-column-right">
                                <template #default="scope">
                                    <el-button size="mini" type="primary" @click="handleAdd(scope.row)" v-if="scope.row.level == 1 && checkMenuLimit('room/craft/standard/Add')">添加步骤</el-button>
                                    <el-button size="mini" type="danger" @click="handleDel(scope.row)" v-if="scope.row.level == 2 && checkMenuLimit('room/craft/standard/Delete')">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination background layout="prev, pager, next" :total="tableData.tableTotal" @current-change="handlePageChange"></el-pagination>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog
                :title="formData.routeFormType == 'add' ? '新增工艺路线' : '编辑工艺路线'"
                v-model="formData.routeFormShow"
                custom-class="table-dialog"
                width="500px">
            <el-form ref="routeFormRef" :model="formData.routeForm" :rules="formData.routeFormRules" label-width="100px" class="table-form">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="路线名称" prop="craftName">
                            <el-input v-model="formData.routeForm.craftName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="关联业态" prop="projectCatagoryCode">
                            <el-select v-model="formData.routeForm.projectCatagoryCode" placeholder="请选择">
                                <el-option v-for="item in dictionaryData.formatList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button size="medium" @click="formData.routeFormShow = false">取 消</el-button>
                <el-button type="primary" size="medium" @click="submitRouteForm">确 定</el-button>
            </span>
            </template>
        </el-dialog>
        <el-dialog title="关联类型" v-model="formData.typeFormShow" custom-class="table-dialog" width="500px">
            <el-form ref="destroyFormRef" :model="formData.destroyForm" :rules="formData.destroyFormRules" label-width="120px" class="table-form">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="级别" prop="deviceLevelIds">
                            <el-cascader v-model="formData.typeForm.deviceLevelIds" :options="dictionaryData.relationList"
                                         :props="{ multiple: true }" clearable filterable></el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button size="medium" @click="formData.typeFormShow = false">取消</el-button>
                    <el-button type="primary" size="medium" @click="submitTypeForm">提交</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog
                title="选择步骤"
                v-model="formData.stepFormShow"
                width="850px">
            <el-table ref="stepTableRef" row-key="fieldId" :data="tableData.stepTableList" v-loading="tableData.stepTableLoading" :height="300" stripe border fit
                      @selection-change="stepSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="gtfieldName" label="参数描述" minWidth="180" align="center"></el-table-column>
                <el-table-column prop="gtfieldTypeName" label="字段类型" minWidth="120" align="center"></el-table-column>
                <el-table-column label="必填" width="100" align="center">
                    <template #default="scope">{{scope.row.requiredState == 1 ? '是' : '否'}}</template>
                </el-table-column>
                <el-table-column label="强制拍照" width="100" align="center">
                    <template #default="scope">{{scope.row.photograph == 1 ? '是' : '否'}}</template>
                </el-table-column>
                <el-table-column label="强制扫码" width="100" align="center">
                    <template #default="scope">{{scope.row.scan == 1 ? '是' : '否'}}</template>
                </el-table-column>
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button size="medium" @click="formData.stepFormShow = false">取 消</el-button>
                    <el-button type="primary" size="medium" @click="submitStepForm">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import {reactive, ref, nextTick} from "vue";
    import {checkMenuLimit} from 'utils/util'
    import {setStore, getStore, getToken} from 'utils/store'
    import {
        getCurrencyDictionary,
        getRouteTypeDictionary,
    } from 'api/dictionary'
    import {
        getProcessTableListOfRoute,
        submitProcessFormOfRoute,
        submitDeleteProcessFormOfRoute,
        getStandardTableListOfRoute,
        getStandardStepTableListOfRoute,
        getStandardExistTypeListOfRoute,
        submitTypeFormOfRoute,
        getAvailableStepTableListOfRoute,
        submitStepFormOfRoute,
        submitDeleteStepFormOfRoute,
    } from 'api/device'
    import {
        ElNotification,
        ElMessage, ElMessageBox,
    } from "element-plus";

    export default {
        name: 'processRoute',
        props: {
            resizeHeight: {
                default: 500,
            },
        },
        setup(props, context){
            //  凭证
            let token = ref('')
            token = getToken()
            //  字典参数
            let dictionaryData = reactive({
                formatList: [],
                relationList: [],
            })
            getCurrencyDictionary({
                dictCode: 'projectCatagory',
            }).then(res => {
                if (res.status == 200) {
                    dictionaryData.formatList = res.data
                } else {
                    ElNotification({
                        title: '获取业态失败',
                        message: res.message,
                        type: 'error'
                    });
                }
            })
            //  表单参数
            let routeFormRef = ref(null)
            let formData = reactive({
                //  工艺路线
                filterForm: {
                    craftName: '',
                    projectCatagoryCode: '',
                },
                routeFormShow: false,
                routeFormType: '',
                routeForm: {
                    craftId: '',
                    craftName: '',
                    projectCatagoryCode: '',
                },
                routeFormRules: {
                    craftName: [
                        {required: true, message: '请输入路线名称', trigger: 'blur'}
                    ],
                    projectCatagoryCode: [
                        {required: true, message: '请选择关联业态', trigger: 'change'}
                    ],
                },
                //  关联类型
                typeFormShow: false,
                typeForm:{
                    deviceLevelIds: []
                },
                //  关联步骤
                stepForm: {
                    gtFormId: '',
                    fieldIds: [],
                },
                stepFormShow: false,
            })
            //  表格参数
            let stepTableRef = ref(null)
            let tableData = reactive({
                //  工艺路线
                selectNode: null,
                treeTableList: [],
                treeTableLoading: false,
                //  标准内容
                tableList: [],
                pageIndex: 1,
                pageSize: 10,
                tableTotal: 0,
                tableLoading: false,
                //  关联步骤
                stepTableList: [],
                stepTableLoading: false,
            })
            //  获取工艺路线表格数据
            function getTreeTableList () {
                tableData.treeTableLoading = true
                getProcessTableListOfRoute({
                    craftName: formData.filterForm.craftName,
                    projectCatagoryCode: formData.filterForm.projectCatagoryCode,
                    userId: getStore({name: 'userIdJH'}),
                    companyId: getStore({name: 'companyIdJH'}),
                }).then(res => {
                    tableData.treeTableLoading = false
                    if (res.status == 200) {
                        tableData.treeTableList = res.data
                    } else {
                        ElNotification({
                            title: '获取工艺路线列表失败',
                            message: res.message,
                            type: 'error'
                        });
                    }
                })
            }
            //  树形结构点击节点
            function nodeClick (row, column,) {
                tableData.selectNode = row
                getTableList()
            }
            //  工艺路线新增
            function routeAdd () {
                formData.routeFormShow = true
                formData.routeFormType = 'add'
                if (routeFormRef.value){
                    routeFormRef.value.resetFields()
                }
            }
            //  工艺路线编辑
            function routeEdit (data) {
                formData.routeFormShow = true
                formData.routeFormType = 'edit'
                if (routeFormRef.value){
                    routeFormRef.value.clearValidate()
                }
                formData.routeForm = {
                    craftId: data.id,
                    craftName: data.craftName,
                    projectCatagoryCode: data.projectCatagoryCode,
                }
            }
            //  工艺路线删除
            function routeDel (data) {
                ElMessageBox.confirm('是否删除，删除后无法找回！', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    submitDeleteProcessFormOfRoute({
                        craftId: data.id,
                        companyId: getStore({name: 'companyIdJH'}),
                    }).then(res => {
                        if (res.status == 200) {
                            ElNotification({
                                title: '删除成功',
                                type: 'success'
                            });
                            getTreeTableList()
                        } else {
                            ElNotification({
                                title: '删除失败',
                                message: res.message,
                                type: 'error'
                            });
                        }
                    })
                })
            }
            //  切换表格页数
            function handlePageChange (val) {
                tableData.pageIndex = val
                getTableList()
            }
            //  获取表格数据
            function getTableList () {
                tableData.tableLoading = true
                tableData.tableList = []
                getStandardTableListOfRoute({
                    craftId: tableData.selectNode.id,
                    pageIndex: tableData.pageIndex,
                    pageSize: tableData.pageSize,
                }).then(res => {
                    tableData.tableLoading = false
                    if (res.status == 200) {
                        tableData.tableList = res.data.records.map(site => {
                            return {
                                ...site,
                                level: 1,
                                hasChildren: true,
                            }
                        })
                        tableData.tableTotal = res.data.total
                    } else {
                        ElNotification({
                            title: '获取设备类型/标准内容列表失败',
                            message: res.message,
                            type: 'error'
                        });
                    }
                })
            }
            //  懒加载标准表格数据
            function loadTableList (tree, treeNode, resolve) {
                getStandardStepTableListOfRoute({
                    gtformId: tree.id
                }).then(res => {
                    if (res.status == 200) {
                        resolve(res.data.map(site => {
                            return {
                                ...site,
                                level: 2,
                                hasChildren: false,
                            }
                        }))
                    } else {
                        ElNotification({
                            title: '获取设备类型/标准内容列表失败',
                            message: res.message,
                            type: 'error'
                        });
                    }
                })
            }
            //  关联类型
            function relationType () {
                getRouteTypeDictionary({
                    format: tableData.selectNode.projectCatagoryCode,
                }).then(res => {
                    if (res.status == 200) {
                        dictionaryData.relationList = res.data.map(item => {
                            return {
                                value: item.id,
                                label: item.sysName,
                                children: item.levelList && item.levelList.length ? item.levelList.map(site =>{
                                    return{
                                        value: site.id,
                                        label: site.title,
                                    }
                                }) : [],
                            }
                        })
                    } else {
                        ElNotification({
                            title: '请求出错',
                            message: res.message,
                            type: 'error'
                        });
                    }
                })
                getStandardExistTypeListOfRoute({
                    craftId: tableData.selectNode.id,
                    projectCatagoryCode: tableData.selectNode.projectCatagoryCode,
                }).then(res => {
                    if (res.status == 200) {
                        formData.typeFormShow = true
                        formData.typeForm.deviceLevelIds = res.data.records.map(site => {
                            return [site.sysId, site.levelId]
                        })
                    } else {
                        ElNotification({
                            title: '请求出错',
                            message: res.message,
                            type: 'error'
                        });
                    }
                })
            }
            //  表格添加步骤操作
            function handleAdd (data) {
                tableData.stepTableLoading = true
                getAvailableStepTableListOfRoute({
                    gtformId: data.id,
                }).then(res => {
                    if (res.status == 200) {
                        tableData.stepTableList = res.data.all
                        tableData.stepTableLoading = false
                        formData.stepFormShow = true
                        formData.stepForm.gtFormId = data.id
                        nextTick(function() {
                            let selectList = res.data.checked.map(site => {
                                return site.fieldId
                            })
                            let selectNodeList = tableData.stepTableList.filter(site => selectList.indexOf(site.fieldId) != -1)
                            selectNodeList.forEach(site => {
                                stepTableRef.value.toggleRowSelection(site);
                            })
                        })
                    } else {
                        ElNotification({
                            title: '请求出错',
                            message: res.message,
                            type: 'error'
                        });
                    }
                })
            }
            //  表格删除操作
            function handleDel (data) {
                ElMessageBox.confirm('是否删除，删除后无法找回！', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    submitDeleteStepFormOfRoute({
                        gtFormId: data.gtformId,
                        gtFormFieldId: data.id,
                    }).then(res => {
                        if (res.status == 200) {
                            ElNotification({
                                title: '删除成功',
                                type: 'success'
                            });
                            getTableList()
                        } else {
                            ElNotification({
                                title: '删除失败',
                                message: res.message,
                                type: 'error'
                            });
                        }
                    })
                })

            }
            //  提交工艺路线表单
            function submitRouteForm () {
                routeFormRef.value.validate((valid) => {
                    if (valid) {
                        submitProcessFormOfRoute(formData.routeForm).then(res => {
                            if (res.status == 200) {
                                formData.routeFormShow = false
                                getTreeTableList()
                                ElNotification({
                                    title: formData.routeFormType == 'add' ? '新增成功' : '编辑成功',
                                    message: res.message,
                                    type: 'success'
                                });
                            } else {
                                ElNotification({
                                    title: '请求出错',
                                    message: res.message,
                                    type: 'error'
                                });
                            }
                        })
                    }
                });
            }
            //  提交关联类型表单
            function submitTypeForm () {
                submitTypeFormOfRoute({
                    deviceCraftId: tableData.selectNode.id,
                    deviceLevelIds: formData.typeForm.deviceLevelIds.map(site => {
                        return site[1]
                    }),
                }).then(res => {
                    if (res.status == 200) {
                        formData.typeFormShow = false
                        tableData.pageIndex = 1
                        getTableList()
                        ElNotification({
                            title: '关联成功',
                            message: res.message,
                            type: 'success'
                        });
                    } else {
                        ElNotification({
                            title: '请求出错',
                            message: res.message,
                            type: 'error'
                        });
                    }
                })
            }
            //  勾选步骤
            function stepSelectionChange(data) {
                formData.stepForm.fieldIds = data.map(site => {
                    return site.fieldId
                })
            }
            //  提交步骤表单
            function submitStepForm () {
                submitStepFormOfRoute({
                    gtFormId: formData.stepForm.gtFormId,
                    fieldIds: formData.stepForm.fieldIds.join(','),
                }).then(res => {
                    if (res.status == 200) {
                        formData.stepFormShow = false
                        tableData.pageIndex = 1
                        getTableList()
                        ElNotification({
                            title: '新增成功',
                            message: res.message,
                            type: 'success'
                        });
                    } else {
                        ElNotification({
                            title: '请求出错',
                            message: res.message,
                            type: 'error'
                        });
                    }
                })
            }
            //  上传附件成功
            function uploadSuccess (res, file, fileList) {
                if (res.status == 200) {
                    ElNotification({
                        title:  '上传成功',
                        message: res.message,
                        type: 'success'
                    });
                } else {
                    ElNotification({
                        title: '上传失败',
                        message: res.message,
                        type: 'error'
                    });
                }
            }
            getTreeTableList()
            //  暴露
            return {
                checkMenuLimit,
                token,
                props,
                //  字典
                dictionaryData,
                getTreeTableList,
                nodeClick,
                routeAdd,
                routeEdit,
                routeDel,
                handlePageChange,
                tableData,
                loadTableList,
                relationType,
                handleAdd,
                handleDel,
                formData,
                routeFormRef,
                stepTableRef,
                submitRouteForm,
                submitTypeForm,
                stepSelectionChange,
                submitStepForm,
                //  上传
                uploadSuccess,
            }
        }
    }
</script>

<style scoped lang="scss">
    .tree-icon{
        font-size: 16px;
        color: #2d8cf0;
        font-weight: bold;
        margin: 0 4px;
        cursor: pointer;
    }
    .tree-icon:hover{
        color: #2db7f5;
    }
</style>
