<template>
    <el-container class="fullheight" style="border: 1px solid #eee">
        <el-aside
            class="fullheight"
            width="230px"
            style="border-right: 1px solid #eee"
            v-show="true"
        >
            <div>
                <div v-if="true" class="tree-header flex">
                    <el-input
                        placeholder="请输入关键字进行过滤"
                        v-model="filterText"
                        clearable
                    >
                        <i class="el-input__icon el-icon-search"></i>
                    </el-input>
                    <div
                        :class="
                            false
                                ? 'tree-button-group is-ie-explorer flex'
                                : 'tree-button-group flex'
                        "
                    >
                        <i
                            :class="{
                                'icon-zhankai': !isExpand,
                                'icon-shouqi': isExpand,
                            }"
                            :title="isExpand ? '收起' : '展开'"
                            @click="handleExpandCollapse"
                        />
                        <i
                            class="icon-sync"
                            :class="{'icon-spin': loading}"
                            title="刷新"
                            @click="refresh"
                        />
                    </div>
                </div>
                <el-tree
                    v-if="options.length"
                    :style="{background: true ? '#fafafa' : ''}"
                    :data="options"
                    :props="defaultProps"
                    :default-expand-all="isExpand"
                    :filter-node-method="filterNode"
                    :default-expanded-keys="defaultShowNodes"
                    :defaultExpandParent="true"
                    node-key="id"
                    :expand-on-click-node="false"
                    highlight-current
                    @node-click="handleNodeClick"
                    @node-expand="handleNodeExpand"
                    @node-collapse="handleNodeCollapse"
                    ref="elTree"
                >
                    <!-- 作用域插槽：插槽prop -->
                    <span class="custom-tree-node" slot-scope="{node, data}">
                        <span class="show-ellipsis" :title="node.name">
                            {{ data.name }}</span
                        >
                        <el-dropdown @command="handleCommand">
                            <span class="el-dropdown-link">
                                <i class="icon-more" title="更多操作" />
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <!-- <el-dropdown-item v-if="typeKey=='appType' && data.parentId!='1293129463957164032'" icon="el-icon-plus" :command="{node:node,data,action:'add'}">添加</el-dropdown-item> -->
                                <el-dropdown-item
                                    icon="el-icon-plus"
                                    :command="{node: node, data, action: 'add'}"
                                    >添加</el-dropdown-item
                                >
                                <el-dropdown-item
                                    icon="el-icon-edit"
                                    v-if="
                                        data.parentId != null &&
                                        data.parentId != '0'
                                    "
                                    :command="{
                                        node: node,
                                        data,
                                        action: 'edit',
                                    }"
                                    >编辑</el-dropdown-item
                                >
                                <!-- <el-dropdown-item
                  v-if="typeKey == 'appType' && data.parentId != '0'"
                  icon="el-icon-setting"
                  :command="{node: node, data, action: 'auth'}"
                  >权限</el-dropdown-item
                > -->
                                <el-dropdown-item
                                    icon="el-icon-delete"
                                    v-if="
                                        data.parentId != null &&
                                        data.parentId != '0'
                                    "
                                    :command="{
                                        node: node,
                                        data,
                                        action: 'delete',
                                    }"
                                    divided
                                    >删除</el-dropdown-item
                                >
                            </el-dropdown-menu>
                        </el-dropdown>
                    </span>
                </el-tree>
                <!-- <el-footer height="30px" class="el-aside-footer" v-if="true">
          <el-switch
            class="footer"
            v-model="showCheckbox"
            active-text="多选"
            inactive-text="单选"
          ></el-switch>
        </el-footer> -->
            </div>
        </el-aside>
        <el-container>
            <el-main class="main-ht-table">
                <ht-table
                    @load="loadData"
                    :data="data"
                    :pageResult="pageResult"
                    :selection="true"
                    :quickSearchProps="searchId"
                    :show-export="false"
                    :show-custom-column="false"
                    :default-querys="[{property: 'parent_id_', value: 'root'}]"
                    :default-sorter="[{direction: 'ASC', property: 'sn_'}]"
                    ref="htTable"
                >
                    <template v-slot:toolbar>
                        <el-row>
                            <el-button
                                size="small"
                                type="primary"
                                @click="showDialog()"
                                icon="el-icon-plus"
                                >添加</el-button
                            >
                            <ht-delete-button
                                :url="port + url.del"
                                :htTable="$refs.htTable"
                                requestMethod="POST"
                                >删除</ht-delete-button
                            >
                            <el-popconfirm
                                title="确认保存序列号吗？"
                                @onConfirm="updateSequence"
                            >
                                <el-button
                                    type="primary"
                                    slot="reference"
                                    icon="el-icon-sort"
                                    :style="{marginLeft: '10px'}"
                                    plain
                                    >保存序列号</el-button
                                >
                            </el-popconfirm>
                        </el-row>
                    </template>
                    <template>
                        <ht-table-column
                            type="index"
                            width="50"
                            align="center"
                            label="序号"
                        />
                        <ht-table-column
                            prop="name"
                            label="省份名称"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <el-link
                                    type="primary"
                                    @click="updateAdstration(scope)"
                                    >{{ scope.row.name }}</el-link
                                >
                            </template>
                        </ht-table-column>
                        <ht-table-column
                            prop="code"
                            label="编码"
                            :show-overflow-tooltip="true"
                        >
                        </ht-table-column>
                        <ht-table-column
                            prop="longitude"
                            label="经度"
                            :show-overflow-tooltip="true"
                        >
                        </ht-table-column>
                        <ht-table-column
                            prop="latitude"
                            label="维度"
                            :show-overflow-tooltip="true"
                        >
                        </ht-table-column>
                        <!-- label="名称全路径" -->
                        <ht-table-column
                            prop="fullName"
                            label="路径"
                            :show-overflow-tooltip="true"
                        >
                        </ht-table-column>
                        <!-- <ht-table-column
          prop="hasChildren"
          label="子节点个数"
          :sortable="true"
          :show-overflow-tooltip="true"
        >
        </ht-table-column> -->
                        <!-- <ht-table-column
          prop="levelCode"
          label="当前层级（province：省，city：市，county：区/县，town：乡镇，village：村）"
          :sortable="true"
          :show-overflow-tooltip="true"
        >
        </ht-table-column> -->
                        <ht-table-column
                            prop="sn"
                            width="160"
                            label="排序号"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <el-input-number
                                    v-model="scope.row.sn"
                                    controls-position="right"
                                    @change="handleChangeSequ(scope)"
                                    :min="1"
                                ></el-input-number>
                            </template>
                        </ht-table-column>
                    </template>
                </ht-table>
                <ht-sidebar-dialog
                    width="28%"
                    title="系统行政区划"
                    class="sp-manager__dialog"
                    :visible="dialogVisible"
                    close-on-click-modal
                    :before-close="beforeCloseDialog"
                >
                    <el-form v-form data-vv-scope="PortalSysAreasForm">
                        <ht-form-item
                            label-width="130px"
                            label="父级行政区划名称"
                        >
                            <el-cascader
                                ref="cascader"
                                v-model="checkValue"
                                :options="options"
                                filterable
                                :props="{
                                    label: 'name',
                                    value: 'id',
                                    checkStrictly: true,
                                }"
                                @change="handleChange"
                            ></el-cascader>
                        </ht-form-item>
                        <ht-form-item label-width="130px" label="行政区划名称">
                            <ht-input
                                v-model="PortalSysAreas.name"
                                validate="required"
                                prop="name"
                                placeholder="请输入行政区划名称"
                            />
                        </ht-form-item>
                        <ht-form-item label-width="130px" label="行政区划编码">
                            <ht-input
                                v-model="PortalSysAreas.code"
                                :validate="{
                                    required: true,
                                    min: '15',
                                    max: '15',
                                    regex: {
                                        exp: '^[0-9]+$',
                                        message: '请输入正确格式的编码格式!',
                                    },
                                }"
                                placeholder="请输入行政区划编码"
                            />
                            <div>
                                <cite name="duoyu" style="color: #aaa">
                                    每三位编码组成一个识别码，总共15位数，依次指定省（自治区、直辖市、特别行政区），市（地区、自治州、盟），县（市辖区、县级市、旗），乡镇，村
                                </cite>
                            </div>
                        </ht-form-item>
                        <!-- <ht-form-item label="上级_ID">
          <ht-input v-model="PortalSysAreas.parentId" validate="required" />
        </ht-form-item> -->
                        <!-- <ht-form-item label="ID全路径">
          <ht-input v-model="PortalSysAreas.fullId" validate="required" />
        </ht-form-item> -->
                        <!-- <ht-form-item label-width="130px" label="名称全路径">
          <ht-input v-model="PortalSysAreas.fullName" validate="required" />
        </ht-form-item> -->
                        <!-- <ht-form-item label="子节点个数">
          <ht-input v-model="PortalSysAreas.hasChildren" validate="required" />
        </ht-form-item> -->
                        <!-- <ht-form-item
          label="当前层级（province：省，city：市，county：区/县，town：乡镇，village：村）"
        >
          <ht-input v-model="PortalSysAreas.levelCode" validate="required" />
        </ht-form-item> -->
                        <ht-form-item label-width="130px" label="经度">
                            <ht-input
                                :validate="{
                                    regex: {
                                        exp: '^[0-9]+(.[0-9]{1,6})?$',
                                        message: '格式错误,请根据提示填写',
                                    },
                                    max_value: '180',
                                }"
                                v-model="PortalSysAreas.longitude"
                                placeholder="请输入行政区划经度"
                            />
                            <div>
                                <cide name="duoyu" style="color: #aaa">
                                    经度整数部分为0-180,小数部分为0到6位!
                                </cide>
                            </div>
                        </ht-form-item>
                        <ht-form-item label-width="130px" label="纬度">
                            <ht-input
                                :validate="{
                                    regex: {
                                        exp: '^[0-9]+(.[0-9]{1,6})?$',
                                        message: '格式错误,请根据提示填写',
                                    },
                                    max_value: '90',
                                }"
                                v-model="PortalSysAreas.latitude"
                                placeholder="请输入行政区划纬度"
                            />
                            <div>
                                <cide name="duoyu" style="color: #aaa">
                                    纬度整数部分为0-90,小数部分为0到6位!
                                </cide>
                            </div>
                        </ht-form-item>
                        <!-- <ht-form-item label="排序号">
          <ht-input v-model="PortalSysAreas.sn" validate="required" />
        </ht-form-item> -->
                    </el-form>
                    <div slot="footer" style="text-align: center">
                        <ht-submit-button
                            :url="port + url.add"
                            :model="PortalSysAreas"
                            :request-method="saveMethod"
                            scope-name="PortalSysAreasForm"
                            @after-save-data="afterSaveData"
                            >保存</ht-submit-button
                        >
                        <el-button @click="beforeCloseDialog"> 取消 </el-button>
                    </div>
                </ht-sidebar-dialog>
            </el-main>
        </el-container>
    </el-container>
</template>
<script>
import req from '@/request.js'
import portal from '@/api/portal.js'
export default {
    data() {
        return {
            loading: false,
            filterText: '',
            defaultProps: {
                children: 'children',
                label: 'name',
            },
            checkValue: null,
            options: [],
            isExpand: false,
            searchId: [{label: '省份名称', prop: 'name_'}],
            dialogVisible: false,
            data: [],
            pageResult: {
                page: 1,
                pageSize: 50,
                total: 0,
            },
            PortalSysAreas: {},
            saveMethod: 'POST',
            port: window.context.portal,
            // port: 'http://8kmbcr.natappfree.cc',
            url: {
                tree: '/sys/sysAreas/v1/querySysAreas',
                list: '/sys/sysAreas/v1/slicedQuerySysAreas',
                add: '/sys/sysAreas/v1/saveSysAreas',
                del: '/sys/sysAreas/v1/deleteBatch',
            },
            sequence: {},
            currentNode: {},
            defaultShowNodes: [],
        }
    },
    mounted() {
        this.$validator = this.$root.$validator
    },
    created() {
        this.loadTree()
    },
    watch: {
        filterText(val) {
            this.$refs.elTree.filter(val)
        },
    },
    methods: {
        handleChangeSequ(res) {
            this.sequence[res.row.id] = res.row.sn
            console.log(this.sequence)
        },
        handleNodeExpand(data) {
            let flag = false
            this.defaultShowNodes.some((item) => {
                if (item === data.id) {
                    // 判断当前节点是否存在， 存在不做处理
                    flag = true
                    return true
                }
            })
            if (!flag) {
                // 不存在则存到数组里
                this.defaultShowNodes.push(data.id)
            }
            console.log(this.defaultShowNodes)
        },
        handleNodeCollapse(data) {
            this.defaultShowNodes = this.defaultShowNodes.filter(item=>item!==data.id)
        },
        handleCommand(command) {
            let node = command.node
            let data = command.data
            let action = command.action
            switch (action) {
                case 'add':
                    this.checkValue = data.id
                    this.PortalSysAreas.parentId = data.id
                    this.getLevenlCode(data.levelCode)
                    this.showDialog()
                    break
                case 'edit':
                    // this.showDialog(data, action)
                    let rows = {}
                    rows.row = data
                    this.updateAdstration(rows)
                    console.log(rows)
                    break
                case 'delete':
                    let headers = {
                        'Content-type': 'application/x-www-form-urlencoded',
                    }
                    let params = 'ids=' + data.id
                    let dt = {
                        data: params,
                        method: 'post',
                        headers,
                    }
                    portal.deleteAdstration(dt).then((res) => {
                        this.$message({
                            type: res.state ? 'success' : 'error',
                            message: res.message,
                        })
                        this.refresh()
                    })
                    break
                case 'moveto':
                    this.$message('暂未提供该功能')
                    break
                case 'auth':
                    this.auth(data)
                    break
                default:
                    break
            }
        },
        refresh() {
            this.loading = true
            this.filterText = ''
            this.checkValue = null
            this.loadTree()
            setTimeout(() => {
                this.loading = false
                this.isExpand = false
                this.$refs.htTable.loading = false
            }, 3000)
        },
        updateAdstration(rows) {
            this.checkValue = rows.row.id
            this.PortalSysAreas = JSON.parse(JSON.stringify(rows.row))
            this.dialogVisible = true
        },
        // 数组转换为树结构
        jsonToTree(jsonData, id, pid) {
            let result = [],
                temp = {}
            for (let i in jsonData) {
                temp[jsonData[i][id]] = jsonData[i] // 以id作为索引存储元素，可以无需遍历直接定位元素
            }
            for (let j in jsonData) {
                let currentElement = jsonData[j]
                if (currentElement.id !== 'root') {
                    currentElement.fullName = '/China' + currentElement.fullName
                    currentElement.fullId = '/root' + currentElement.fullId
                }
                let tempCurrentElementParent = temp[currentElement[pid]] // 临时变量里面的当前元素的父元素

                if (tempCurrentElementParent) {
                    // 如果存在父元素
                    if (!tempCurrentElementParent['children']) {
                        // 如果父元素没有chindren键
                        tempCurrentElementParent['children'] = [] // 设上父元素的children键
                    }
                    tempCurrentElementParent['children'].push(currentElement) // 给父元素加上当前元素作为子元素
                } else {
                    // 不存在父元素，意味着当前元素是一级元素
                    result.push(currentElement)
                }
            }
            return result
        },
        // 树状菜单的全部展开和收起
        handleExpandCollapse() {
            this.isExpand = !this.isExpand
            console.log(this.$refs.elTree.store._getAllNodes())
            let elTree = this.$refs.elTree
            for (var i = 0; i < elTree.store._getAllNodes().length; i++) {
                elTree.store._getAllNodes()[i].expanded = this.isExpand
            }
        },
        filterNode(value, data) {
            if (!value) return true
            return data.name.indexOf(value) !== -1
        },
        handleChange(data) {
            this.PortalSysAreas.parentId = data[data.length - 1]
            this.getLevenlCode(
                this.$refs.cascader.getCheckedNodes()[0].data.levelCode
            )
        },
        getLevenlCode(levelcode) {
            switch (levelcode) {
                case 'COUNTRY':
                    this.PortalSysAreas.levelCode = 'province'
                    break
                case 'province': //省
                    this.PortalSysAreas.levelCode = 'city'
                    break
                case 'city': //市
                    this.PortalSysAreas.levelCode = 'country'
                    break
                case 'country': //区县
                    this.PortalSysAreas.levelCode = 'town'
                    break
                case 'town': //乡镇
                    this.PortalSysAreas.levelCode = 'village'
                    break
                case 'village': //村
                    break
                default:
                    this.PortalSysAreas.levelCode = ''
                    break
            }
        },
        updateSequence() {
            this.$refs.htTable.loading = true
            if (Object.keys(this.sequence).length) {
                portal.updateSequence(this.sequence).then((res) => {
                    if (res.state) {
                        this.$message({
                            type: 'success',
                            message: res.message,
                        })
                    }
                    this.$refs.htTable.loading = false
                })
            } else {
                this.$message({
                    type: 'warning',
                    message: '保存号未修改',
                })
            }
        },
        clickTest() {
            if (this.$refs.htTable.selection.length == 0) {
                this.$message({
                    showClose: false,
                    type: 'error',
                    message: '请至少选择一条数据',
                })
                return
            }
        },
        handleNodeClick(item, node, tree) {
            console.log(item, node, tree)
            // this.data = item.children
            let query = {
                pageBean: {page: 1, pageSize: 50, total: 1},
                querys: [
                    {
                        group: 'main',
                        operation: 'EQUAL',
                        property: 'parent_id_',
                        relation: 'AND',
                        value: item.id,
                    },
                ],
                sorter: [{direction: 'ASC', property: 'sn_'}],
            }
            this.loadData(query)
            this.checkValue = item.id
            this.PortalSysAreas.parentId = item.id
            this.getLevenlCode(item.levelCode)
        },
        treeCheck(item, list) {
            console.log(item, list)
        },
        showDialog() {
            if (this.PortalSysAreas.parentId && this.PortalSysAreas.levelCode) {
                this.saveMethod = 'POST'
                this.dialogVisible = true
            } else {
                this.$message({
                    type: 'warning',
                    message: '请选择左侧添加父节点',
                })
            }
            // if (id) {
            //   this.saveMethod = 'PUT'
            //   this.$http
            //     .get('http://mv9hps.natappfree.cc/portalSysAreas/v1/' + id)
            //     .then(
            //       (resp) => {
            //         this.PortalSysAreas = resp.data
            //         this.dialogVisible = true
            //       },
            //       (error) => {
            //         reject(error)
            //       }
            //     )
            // } else {
            // this.saveMethod = 'POST'
            // this.dialogVisible = true
            // }
        },
        beforeCloseDialog() {
            // this.refresh()
            this.PortalSysAreas.name = ''
            this.PortalSysAreas.code = ''
            this.PortalSysAreas.longitude = ''
            this.PortalSysAreas.latitude = ''
            this.dialogVisible = false
        },
        // 查树
        loadTree() {
            req.post(this.port + this.url.tree)
                .then(
                    (resp) => {
                        console.log('返回数据', resp)
                        let response = []
                        if (resp.data.length) {
                            response = resp.data
                        }
                        this.getListTree(response)
                    },
                    (error) => {
                        reject(error)
                    }
                )
                .finally(() => {})
        },
        // 查列表
        loadData(param, cb) {
            console.log(param)
            // console.log(this.$http, 'http')
            // param.sorter = [
            //   {
            //     direction: 'ASC',
            //     property: 'sn_',
            //   },
            // ]
            req.post(this.port + this.url.list, param)
                .then(
                    (resp) => {
                        let response = resp.data
                        this.data = response.rows
                        this.pageResult = {
                            page: response.page,
                            pageSize: response.pageSize,
                            total: response.total,
                        }
                        console.log('返回数据', resp)
                        // this.getListTree(resp)
                        // this.data = arr
                    },
                    (error) => {
                        reject(error)
                    }
                )
                .finally(() => {
                    cb ? cb() : null
                })
        },
        async getListTree(data) {
            let rootTree = {
                code: 'China',
                fullId: '/root',
                fullName: '/China',
                hasChildren: 0,
                id: 'root',
                latitude: 0,
                levelCode: 'COUNTRY',
                longitude: 0,
                name: '中国',
                parentId: null,
                pkVal: '',
                sn: 0,
            }
            // if(response.data.rows.length > 1)
            data.unshift(rootTree)
            if (data.length > 1) {
                let rows = this.jsonToTree(data, 'id', 'parentId')
                console.log(rows, 'ttt')
                if (rows.length == 1) {
                    this.options = rows
                    // this.data = rows[0].children
                } else {
                    let arr = []
                    arr.push(rows[1])
                    this.options = arr
                    // this.data = arr
                }
            } else {
                this.options = data
            }
        },
        afterSaveData() {
            setTimeout(() => {
                this.beforeCloseDialog()
                this.$refs.htTable.load()
                this.loadTree()
            }, 500)
        },
    },
}
</script>

<style lang="scss" scoped>
.sp-manager__dialog /deep/ > .el-dialog > .el-dialog__body {
    height: calc(100% - 170px);
}
</style>

<style scoped>
div[aria-invalid='true'] >>> .el-input__inner,
div[aria-invalid='true'] >>> .el-input__inner:focus {
    border-color: #f56c6c;
}
.is-ie-explorer {
    margin-right: 25px;
}

div.tree-button-group i {
    cursor: pointer;
    display: inline;
    font-size: 18px;
    font-weight: bold;
    margin-right: 10px;
}

div.tree-button-group i:hover {
    color: lightcoral;
}

div.tree-header {
    min-height: 30px;
}

.tree-button-group {
    margin-left: 10px;
}

div.tree-header >>> .el-input__inner {
    border-width: 0;
    padding-right: 0;
}

.custom-tree-node {
    width: calc(100% - 40px);
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.custom-tree-node i {
    visibility: hidden;
    font-weight: bold;
}

.custom-tree-node:hover i {
    visibility: visible;
}

>>> .show-ellipsis {
    display: block;
    width: calc(100% - 25px);
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

span.full-width {
    width: 100%;
}
</style>
