<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-option label="九小场所" value="5"></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-show="active === 1" title="流程节点">
            <template #optionRight>
                <el-button type="primary" size="medium" icon="el-icon-plus" @click="handleAddNode">新增节点</el-button>
            </template>
            <div id="nodes" style="margin-top: 10px;">
                <el-table
                        :data="nodes"
                        ref="nodeTable"
                        row-key="idIndex"
                        class="custom-sortable-row"
                        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>
            <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-show="active === 2 && nodes" title="检查步骤">
            <div class="nodes" id="items">
                <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>
                    <node-items-table :nodeIndex="nodeIndex"
                                      v-if="!refreshItems"
                                      :items="node.items"
                                      @handleEditItem="handleEditItem"
                                      @handleDeleteItem="handleDeleteItem"
                                      @swapItems="swapItems"
                    >

                    </node-items-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" @addTemplateData="addTemplateData"
                              @handleCancel="addTemplateVisual=false">
            </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 NodeItemsTable from "./component/NodeItemsTable";
import {addCheck, updateCheck, getCheckItem, removeNode, removeNodeItem, addCheckNew} from '@/api/check'
import Sortable from 'sortablejs'
import { getUUID, notEmpty } from '@/utils/tool';

export default {
    components: {
        FormOption,
        EditNode,
        AddNodeItem,
        //TemplateAdd,
        TemplateAddNew,
        NodeItemsTable
    },
    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: [],
            refreshItems:false,
            chooseItem: {
                nodeIndex: -1,
                itemIndex: -1,
                data: null
            },
            sortableEl: null,
        }
    },
    computed: {
        checkId() {
            return this.$route.query.id
        }
    },
    mounted() {
        this.getPlaceTypesAll();
        this.getCheckDetail()
        // this.nodeDrop();
    },
    methods: {
        async getPlaceTypesAll() {
            const list = await getPlaceTypes();
            if (list && list.length > 0) {
                this.placeType = list;
            }
        },
        nodeDrop() {
            //行拖拽
            // const tbody = document.querySelector('#nodes .el-table__body-wrapper tbody')
            // const _this = this
            // Sortable.create(tbody, {
            //     onEnd({newIndex, oldIndex}) {
            //         const currRow = _this.nodes.splice(oldIndex, 1)[0]
            //         _this.nodes.splice(newIndex, 0, currRow)
            //     }
            // })
            if (this.sortableEl) {
                return
            }
            const el = this.$refs.nodeTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
            const vm = this;
            this.sortableEl = Sortable.create(el, {
                ghostClass: 'custom-sortable',
                forceFallback: true,
                setData: function(dataTransfer) {
                    dataTransfer.setData('Text', '')
                },
                onEnd: evt => {
                    const targetRow = vm.nodes.splice(evt.oldIndex, 1)[0];
                    vm.nodes.splice(evt.newIndex, 0, targetRow);
                }
            })
        },
        handleCancel() {
            this.$router.back()
        },
        getCheckDetail() {
            if (this.checkId) {
                this.loading = true
                getCheckItem(this.checkId).then(res => {
                    const data = Object.assign({}, res)
                    data.hole_responsibility = res.hole_responsibility === 1
                    if (data.nodes) {
                        let nodes = [];
                        data.nodes.map(node => {
                            node.idIndex = `${node.id}`;
                            if (node.items && node.items.length > 0) {
                                const items = []
                                node.items.map(item => {
                                    const obj = Object.assign({}, item);
                                    obj.idIndex = item.id;
                                    //obj.item_id = item.hanbook && item.hanbook.id || item.id
                                    if (item.handbook) {
                                        obj.enforce_class = item.handbook.enforce_class
                                        obj.enforce_item = item.handbook.enforce_item
                                        obj.enforce_method = item.handbook.enforce_method
                                        // obj.hanbook = undefined
                                        obj.handbook.fullName = obj.handbook.full_name;
                                        if (notEmpty(obj.handbook.full_name) && notEmpty(obj.handbook.enforce_class)) {
                                            obj.handbook.fullName = obj.handbook.full_name.replace(obj.handbook.enforce_class+'---', '');
                                        }
                                    }
                                    if (item.item_type === '1' && item.item_content) {
                                        obj.enforce_class = '其它'
                                        obj.enforce_item = item.item_content
                                    }
                                    items.push(obj)
                                })
                                items.sort((a, b) => a['sort'] > b['sort'] ? 1 : -1);
                                node.items = items
                            }
                            nodes.push(node);
                        })
                        nodes.sort((a, b) => a['sort'] > b['sort'] ? 1 : -1);
                        data.nodes = nodes;
                    }
                    this.baseData = data;
                    this.nodes = data.nodes || []
                    this.loading = false
                    // this.$nextTick(() => {
                    //     this.nodeDrop();
                    // });
                })
            }
        },
        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'
        },
        swapItems(nodeIndex, itemIndex1, itemIndex2) {
            const items = this.nodes[nodeIndex].items;
            const currRow = items.splice(itemIndex1, 1)[0];
            items.splice(itemIndex2, 0, currRow);
            // this.refreshItemsNeed();
            // let that = this;
            // setTimeout(function () {
            //     that.refreshItemsNeed();
            // }, 50)
        },
        refreshItemsNeed(){
            this.refreshItems=!this.refreshItems;
        },
        handleNext() {
            const vm = this
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    vm.active = 1
                    vm.$nextTick(() => {
                        vm.nodeDrop();
                    });
                }
            })
        },
        changeNodeData(data, index = 0) {
            if (!data.idIndex) {
                data.idIndex = data.id ? data.id : getUUID(16);
            }
            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.editNode = null
            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;
                        // if (item.handbook) {
                        //     item.handbook.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('暂存成功')
                    }
                }).catch(() => {
                    this.saveLoading = false;
                })
            } else {
                addCheckNew(obj).then(res => {
                    this.saveLoading = false
                    if (res) {
                        this.baseData.id = res.id
                        if (needBack) {
                            this.$message.success('保存成功')
                            this.handleCancel()
                        }
                    }
                }).catch(() => {
                    this.saveLoading = false;
                })
            }
        },
        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)) {
                        // console.log(item)
                        if (item.item_type !== '1') {
                            getEnforceHandbook(item.id).then(detail => {
                                detail.template_id = this.checkId;
                                detail.handbook_id = detail.id;
                                detail.id = null;
                                detail.idIndex = getUUID(16);
                                detail.item_type = '0';
                                detail.item_content = detail.enforce_content;
                                detail.node_id = node.id;
                                const handbook = Object.assign({}, detail);
                                detail.handbook = handbook;
                                handbook.fullName = handbook.full_name;
                                if (notEmpty(handbook.full_name) && notEmpty(handbook.enforce_class)) {
                                    handbook.fullName = handbook.full_name.replace(handbook.enforce_class+'---', '');
                                }
                                res.push(detail)
                            })
                        } else {
                            item.idIndex = getUUID(16);
                            item.item_id = new Date().getTime();
                            item.item_type = '1';
                            item.enforce_content = item.item_content;
                            let handbook = Object.assign({}, item);
                            item.handbook = handbook;
                            item.template_id = this.checkId;
                            item.node_id = node.id;
                            res.push(item)
                        }
                    }
                })
                this.nodes[this.addNodeItemIndex].items = res

            }
            this.showNodeItemDialog = false
            // this.$nextTick(() => {
            //     this.nodeDrop();
            // });
        },
        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;
        // },
        handleEditItem(nodeIndex, itemIndex) {
            let row = this.nodes[nodeIndex].items[itemIndex];
            this.chooseItem.nodeIndex = nodeIndex;
            this.chooseItem.itemIndex = itemIndex;
            this.chooseItem.data = row.handbook;
            this.addTemplateVisual = true;
        },
        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];
            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;
            }
            if (data.problems && data.problems.length) {
              const close = data.problems.findIndex(it => !!(it.problem_desc && !it.problem_images))
              if (close > -1) {
                this.$message.error('请上传问题相关图片')
                return
              }
            }
            console.log('this.chooseItem', this.chooseItem)
            this.addTemplateVisual = false;
        },
        handleDeleteItem(nodeIndex, itemIndex) {
            let data = this.nodes[nodeIndex].items[itemIndex];
            if (data.id) {
                removeNodeItem(data.id).then(res => {
                    this.$message.success('节点信息删除成功')
                    this.nodes[nodeIndex].items.splice(itemIndex, 1)
                })
            } else {
                this.$message.success('节点信息删除成功');
                this.nodes[nodeIndex].items.splice(itemIndex, 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>
