<template>
    <div class="edit" v-loading="loading">
        <div class="steps">
            <el-steps :active="active" align-center finish-status="success">
                <el-step title="基本配置"></el-step>
                <el-step title="流程节点"></el-step>
                <el-step title="检查步骤"></el-step>
            </el-steps>
        </div>
        <form-option v-if="active === 0" title="基本信息">
            <el-form :model="baseData" :rules="rules" ref="ruleForm" label-width="150px" class="custom-form">
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="模板名称" prop="template_name">
                            <el-input v-model="baseData.template_name" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="单位规模" prop="enforce_obj_type">
                            <el-select v-model="baseData.enforce_obj_type" placeholder="请选择">
                                <el-option
                                        v-for="item in unitSize"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="场所类型" prop="place_type">
                            <el-select v-model="baseData.place_type" placeholder="请选择">
                                <el-option
                                        v-for="item in placeType"
                                        :key="item.code"
                                        :label="item.name"
                                        :value="item.code">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="所在建筑" prop="architecture_type">
                            <el-radio-group v-model="baseData.architecture_type">
                                <el-radio label="1">高层建筑</el-radio>
                                <el-radio label="2">非高层建筑</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="消防安全" prop="hole_responsibility">
                            <el-checkbox v-model="baseData.hole_responsibility">负责整栋建筑消防安全</el-checkbox>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="状态" prop="usage_status">
                            <el-radio-group v-model="baseData.usage_status">
                                <el-radio label="0">停用</el-radio>
                                <el-radio label="1">启用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item>
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="warning" @click="resetForm">重置</el-button>
                    <el-button type="primary" @click="handleNext">下一步</el-button>
                </el-form-item>
            </el-form>
        </form-option>
        <form-option v-if="active === 1" title="流程节点">
            <template #optionRight>
                <el-button type="primary" size="medium" icon="el-icon-plus" @click="handleAddNode">新增节点</el-button>
            </template>
            <el-table
                    :data="nodes"
                    class="mg"
                    border>
                <el-table-column type="index" align="center" label="序号" width="80"/>
                <el-table-column prop="node_name" label="动线流程名称" show-overflow-tooltip/>
                <el-table-column prop="detail" show-overflow-tooltip label="详细说明"/>


                <el-table-column prop="action" label="操作" align="center" width="270">
                    <template slot-scope="scope">
<!--                        <el-button v-if="scope.$index > 0" type="text" icon="el-icon-arrow-up"-->
<!--                                   @click="handleMoveUpNode(scope.$index)">上移-->
<!--                        </el-button>-->
<!--                        <el-button v-if="scope.$index < nodes.length - 1" type="text" icon="el-icon-arrow-down"-->
<!--                                   @click="handleMoveDownNode(scope.$index)">下移-->
<!--                        </el-button>-->
                        <el-button type="text" icon="el-icon-edit" @click="handleEditNode(scope.row, scope.$index)">编辑
                        </el-button>
                        <el-button type="text" icon="el-icon-delete" @click="handleDeleteNode(scope.$index)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="mg">
                <el-button @click="handleSaveNodeInfo">暂存</el-button>
                <el-button type="warning" @click="handleBeforeStep">上一步</el-button>
                <el-button type="primary" @click="handleNodeNext">下一步</el-button>
            </div>
        </form-option>
        <form-option v-if="active === 2" title="检查步骤">
            <div class="nodes">
                <div class="node" v-for="(node, nodeIndex) in nodes" :key="nodeIndex">
                    <div class="header">
                        <div class="header-sec">
                            <div class="node-name">{{ node.node_name }}</div>
                            <el-tooltip class="item" effect="dark" :content="node.detail" placement="top">
                                <div class="node-detail">{{ node.detail }}</div>
                            </el-tooltip>
                        </div>
                        <div>
                            <el-button type="primary" size="medium" icon="el-icon-plus"
                                       @click="handleAddNodeItem(nodeIndex)">新增步骤
                            </el-button>
                        </div>
                    </div>
                    <el-table
                            :data="node.items"
                            border>
                        <el-table-column type="index" align="center" label="序号" width="80"/>
                        <el-table-column prop="enforce_class" show-overflow-tooltip label="检查类型">
                            <template slot-scope="scope">
                            <span v-if="scope.row.handbook">
                                {{ scope.row.handbook.enforce_class }}
                            </span>
                                <span v-else></span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="enforce_item" show-overflow-tooltip label="检查项">
                            <template slot-scope="scope">
                            <span v-if="scope.row.handbook">
                                {{ scope.row.handbook.enforce_item }}
                            </span>
                                <span v-else></span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="enforce_method" label="检查流程及方法" show-overflow-tooltip>
                            <template slot-scope="scope">
                            <span v-if="scope.row.handbook">
                                {{ scope.row.handbook.enforce_method }}
                            </span>
                                <span v-else></span>
                            </template>
                        </el-table-column>
                        <!--                        <el-table-column prop="enforce_class" label="检查类型" show-overflow-tooltip/>-->
                        <!--                        <el-table-column prop="enforce_item" show-overflow-tooltip label="检查项"/>-->
                        <!--                        <el-table-column prop="enforce_method" show-overflow-tooltip label="检查流程及方法"/>-->


                        <el-table-column prop="action" label="操作" align="center" width="270">
                            <template slot-scope="scope">
<!--                                <el-button v-if="scope.$index > 0" type="text" icon="el-icon-arrow-up"-->
<!--                                           @click="handleMoveUpItem(nodeIndex, scope.$index)">上移-->
<!--                                </el-button>-->
<!--                                <el-button v-if="scope.$index < node.items.length - 1" type="text"-->
<!--                                           icon="el-icon-arrow-down"-->
<!--                                           @click="handleMoveDownItem(nodeIndex, scope.$index)">下移-->
<!--                                </el-button>-->
                                <el-button type="text" icon="el-icon-edit"
                                           @click="handleEditItem(nodeIndex, scope.$index,scope.row)">
                                    编辑
                                </el-button>
                                <el-button type="text" icon="el-icon-delete"
                                           @click="handleDeleteItem(nodeIndex, scope.$index, scope.row)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div class="mg1">
                <el-button @click="handleSaveNodeInfo">暂存</el-button>
                <el-button type="warning" @click="handleBeforeStep">上一步</el-button>
                <el-button type="primary" @click="handleCommitData" :loading="saveLoading">完成</el-button>
            </div>
        </form-option>

        <el-dialog :title="nodeDialogTitle" v-if="showEditNodeDialog" :visible.sync="showEditNodeDialog">
            <edit-node ref="nodeDialog" :nodeData.sync="editNode" :nodeSort.sync="editNodeSort"
                       @changeNodeData="changeNodeData"></edit-node>
        </el-dialog>
        <el-dialog title="新增步骤" :visible.sync="showNodeItemDialog" class="custom-dialog-node">
            <add-node-item @cancel="showNodeItemDialog=false" @addData="addNodeItemDatas"></add-node-item>
        </el-dialog>
        <el-dialog title="检查配置" :visible.sync="addTemplateVisual" v-if="addTemplateVisual" class="custom-dialog-node">
            <template-add-new :item="chooseItem.data" @handleCancel="addTemplateVisual=false" @addTemplateData="addTemplateData">
            </template-add-new>
        </el-dialog>
    </div>
</template>

<script>
    import FormOption from '@/component/FormOption'
    import {getEnforceHandbook} from '@/api/book'
    import EditNode from './component/EditNode.vue'
    import AddNodeItem from './component/AddNodeItem.vue'
    import TemplateAddNew from "./component/TemplateAddNew";
    import {getPlaceTypes} from "@/api/resource";
    import TemplateAdd from "./component/TemplateAdd";
    import {resourceMixin} from '@/mixin/resource'
    import {addCheck, updateCheck, getCheckItem, removeNode, removeNodeItem, addCheckNew} from '@/api/check'

    export default {
        components: {
            FormOption,
            EditNode,
            AddNodeItem,
            //TemplateAdd,
            TemplateAddNew
        },
        mixins: [resourceMixin],
        data() {
            return {
                active: 0,
                loading: false,
                addTemplateVisual: false,
                baseData: {
                    enforce_class: null,
                    template_name: null,
                    enforce_obj_type: null,
                    place_type: null,
                    architecture_type: null,
                    usage_status: '1',
                    hole_responsibility: null,
                },
                rules: {
                    template_name: [
                        {required: true, message: '请输入模板名称', trigger: 'blur'},
                        {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
                    ],
                    usage_status: [
                        {required: true, message: '请选择状态', trigger: 'change'}
                    ]
                },
                nodes: [],
                editNode: null,
                editNodeSort: 0,
                showEditNodeDialog: false,
                nodeDialogTitle: '新增节点',
                showNodeItemDialog: false,
                addNodeItemIndex: 0,
                saveLoading: false,
                placeTypeList: [],
                chooseItem: {
                    nodeIndex: -1,
                    itemIndex: -1,
                    data: null
                }
            }
        },
        computed: {
            checkId() {
                return this.$route.query.id
            }
        },
        mounted() {
            this.getPlaceTypesAll();
            this.getCheckDetail()
        },
        methods: {
            async getPlaceTypesAll() {
                const list = await getPlaceTypes();
                if (list && list.length > 0) {
                    this.placeType = list;
                }
            },
            handleCancel() {
                this.$router.back()
            },
            getCheckDetail() {
                if (this.checkId) {
                    this.loading = true
                    getCheckItem(this.checkId).then(res => {
                        res.id = null;
                        res.template_name = res.template_name + '(复制)';
                        const data = Object.assign({}, res)
                        data.hole_responsibility = res.hole_responsibility === 1
                        if (data.nodes) {
                            let nodes = [];
                            data.nodes.map(node => {
                                node.id = null;
                                if (node.items && node.items.length > 0) {
                                    const items = []
                                    node.items.map(item => {
                                        item.id = null;
                                        const obj = Object.assign({}, item)
                                        if (item.hanbook) {
                                            obj.enforce_class = item.hanbook.enforce_class
                                            obj.enforce_item = item.hanbook.enforce_item
                                            obj.enforce_method = item.hanbook.enforce_method
                                            // obj.hanbook = undefined
                                        }
                                        if (item.item_type === '1' && item.item_content) {
                                            obj.enforce_class = '其它'
                                            obj.enforce_item = item.item_content
                                        }
                                        items.push(obj)
                                    })
                                    node.items = items
                                }
                                nodes.push(node);
                            })
                            data.nodes = nodes;
                        }
                        this.baseData = data;
                        this.nodes = data.nodes || []
                        console.log('node:', data.nodes)
                        this.loading = false
                    })
                }
            },
            resetForm() {
                this.baseData.template_name = ''
                this.baseData.enforce_obj_type = ''
                this.baseData.place_type = ''
                this.baseData.architecture_type = ''
                this.baseData.hole_responsibility = ''
                this.baseData.usage_status = '1'
            },
            handleNext() {
                const vm = this
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        vm.active = 1
                    }
                })
            },
            changeNodeData(data, index = 0) {
                if (this.nodes.length > index) {
                    this.nodes.splice(index, 1, data)
                } else {
                    this.nodes.push(data)
                }
                this.showEditNodeDialog = false
            },
            handleMoveUpNode(index) {
                if (index > 0) {
                    const data = this.nodes[index]
                    this.nodes.splice(index - 1, 0, data)
                    this.nodes.splice(index + 1, 1)
                }
            },
            handleMoveDownNode(index) {
                if (index < this.nodes.length - 1) {
                    const data = this.nodes[index]
                    this.nodes.splice(index + 2, 0, data)
                    this.nodes.splice(index, 1)
                }
            },
            handleAddNode() {
                this.nodeDialogTitle = '新增节点'
                this.editNodeSort = this.nodes.length
                this.showEditNodeDialog = true
            },
            handleEditNode(data, index) {
                this.nodeDialogTitle = '修改节点'
                this.editNode = data
                this.editNodeSort = index
                this.showEditNodeDialog = true
            },
            handleDeleteNode(index) {
                const data = this.nodes[index]
                if (data.id) {
                    removeNode(data.id).then(res => {
                        this.$message.success('节点删除成功')
                        this.nodes.splice(index, 1)
                    })
                } else {
                    this.nodes.splice(index, 1)
                }
            },
            handleSaveNodeInfo(needBack) {
                this.nodes.map((node, nodeIndex) => {
                    if (node.items) {
                        node.items.map((item, index) => {
                            item.sort = index
                        })
                    }
                    node.sort = nodeIndex
                })
                const obj = Object.assign(this.baseData, {
                    nodes: this.nodes
                })
                obj.hole_responsibility = obj.hole_responsibility ? '1' : '0'
                this.saveLoading = true
                if (obj.id) {
                    updateCheck(obj.id, obj).then(res => {
                        this.saveLoading = false
                        if (needBack) {
                            this.$message.success('保存成功')
                            this.handleCancel()
                        } else {
                            this.$message.success('暂存成功')
                        }
                    })
                } else {
                    addCheckNew(obj).then(res => {
                        this.saveLoading = false
                        if (res) {
                            this.baseData.id = res.id
                            if (needBack) {
                                this.$message.success('保存成功')
                                this.handleCancel()
                            }
                        }
                    })
                }
            },
            handleBeforeStep() {
                if (this.active > 0) {
                    this.active--
                }
            },
            handleNodeNext() {
                if (this.nodes.length > 0) {
                    this.active = 2
                } else {
                    this.$message.warning('请配置至少一个节点')
                }
            },
            handleAddNodeItem(nodeIndex) {
                this.addNodeItemIndex = nodeIndex
                this.showNodeItemDialog = true
            },
            checkNodeItemNotExist(id) {
                if (id) {
                    const list = this.nodes[this.addNodeItemIndex].items || []
                    const res = list.filter(item => id === item.id)
                    if (res && res.length > 0) {
                        return false
                    }
                }
                return true
            },
            addNodeItemDatas(items) {
                if (items) {
                    const node = this.nodes[this.addNodeItemIndex]
                    const res = node.items || []
                    items.map(item => {
                        if (this.checkNodeItemNotExist(item.item_id)) {
                            getEnforceHandbook(item.id).then(detail => {
                                detail.template_id = this.checkId
                                detail.handbook_id = detail.id;
                                detail.id = null;
                                //    detail.id = null;
                                detail.node_id = node.id
                                let handbook = Object.assign({}, detail);
                                detail.handbook = handbook;
                                res.push(detail)
                            })
                        }
                    })
                    this.nodes[this.addNodeItemIndex].items = res

                }
                this.showNodeItemDialog = false
            },
            handleMoveUpItem(row, index) {
                if (index > 0) {
                    const list = this.nodes[row].items
                    list.splice(index - 1, 0, list[index])
                    list.splice(index + 1, 1)
                }
            },
            handleMoveDownItem(row, index) {
                const list = this.nodes[row].items
                if (index < list.length - 1) {
                    list.splice(index + 2, 0, list[index])
                    list.splice(index, 1)
                }
            },
            handleEditItem(nodeIndex, itemIndex, row) {
                this.chooseItem.nodeIndex = nodeIndex;
                this.chooseItem.itemIndex = itemIndex;
                this.chooseItem.data = row.handbook;
                this.addTemplateVisual = true;
                // if (!row.item_id) {
                //     this.$router.push({
                //         path: '/monitor/template/add',
                //         query: {
                //             id: row.template_id,
                //             enforce_item: row.enforce_item
                //         }
                //     })
                // } else {
                //     this.$router.push({
                //         path: '/monitor/template/edit',
                //         query: {
                //             id: row.item_id
                //         }
                //     })
                // }
            },
            addTemplateData(data) {
                this.chooseItem.data.enforce_class = data.enforce_class;
                this.chooseItem.data.enforce_item = data.enforce_item;
                this.chooseItem.data.enforce_method = data.enforce_method;
                this.chooseItem.data.problems = data.problems;
                this.chooseItem.data.setting_expect = data.setting_expect;
                let item = this.nodes[this.chooseItem.nodeIndex]
                    .items[this.chooseItem.itemIndex];
                // tmpHandleBook.enforce_class = data.enforce_class;
                // tmpHandleBook.enforce_item = data.enforce_item;
                // tmpHandleBook.problems = data.problems;
                // tmpHandleBook.enforce_method = data.enforce_method;
                if (item.handbook) {
                    let tmpBook = item.handbook;
                    tmpBook.enforce_class = data.enforce_class;
                    tmpBook.enforce_item = data.enforce_item;
                    tmpBook.problems = data.problems;
                    tmpBook.enforce_method = data.enforce_method;
                } else {
                    item.handbook = data;
                }
                this.addTemplateVisual = false;
                // this.chooseItem.enforce_class: "消防安全管理"
                // enforce_item: "消防安全制度"
                // enforce_method: "dasd"
                // problems: Array(2)
                // setting_expect: "<p><strong>dsad</strong></p>"
            },
            handleDeleteItem(row, index, data) {
                this.nodes[row].items.splice(index, 1);
            },
            handleCommitData() {
                this.handleSaveNodeInfo(true)
            }
        }
    }
</script>

<style lang="scss" scoped>
    .edit {
        width: 100%;

        .steps {
            margin: 8px auto;
            width: 600px;
        }

        .custom-form {
            padding-bottom: 10px;
        }

        .mg {
            margin-top: 10px;
        }

        .mg1 {
            margin-top: 20px;
            padding-bottom: 20px;
        }

        .mg:last-child {
            padding-bottom: 20px;
        }

        .nodes {
            .node {
                margin-top: 20px;
            }

            .header {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .header-sec {
                    display: flex;
                    align-items: center;
                }

                .node-name {
                    font-size: 16px;
                    color: #343435;
                    font-weight: bold;
                }

                .node-detail {
                    margin-left: 15px;
                    font-size: 13px;
                    color: #888888;
                    max-width: 600px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
            }
        }
    }
</style>
