<template>
    <el-container class="fullheight" style="border: 1px solid #eee">
        <ht-aside-tree
            type-key="SYS_DICT"
            :hasFooter="false"
            @node-click="handleNodeClick"
        />
        <el-container>
            <el-main class="main-ht-table">
                <ht-table
                    @load="loadData"
                    @select="selectDict"
                    @select-all="selectDict"
                    :data="data"
                    :pageResult="pageResult"
                    :selection="true"
                    :default-querys="defaultQuerys"
                    :default-sorter="[{direction: 'DESC', property: 'sn_'}]"
                    :quick-search-props="querySearch"
                    :show-export="false"
                    :show-custom-column="false"
                    ref="htTable"
                >
                    <template v-slot:toolbar>
                        <!-- <el-button-group> -->
                        <el-button
                            type="primary"
                            size="small"
                            @click="showDialog()"
                            icon="el-icon-plus"
                            >添加</el-button
                        >
                        <ht-delete-button
                            url="${portal}/sys/sysDictionary/v1/deleteDictionaries"
                            :htTable="$refs.htTable"
                            @after-delete="afterDelete"
                            requestMethod="post"
                            >删除</ht-delete-button
                        >
                        <el-button
                            icon="el-icon-unlock"
                            type="success"
                            plain
                            @click="handleDictFlag('启')"
                        >
                            启用</el-button
                        >
                        <el-button
                            type="danger"
                            plain
                            icon="el-icon-lock"
                            @click="handleDictFlag('禁')"
                            >禁用</el-button
                        >
                        <el-button
                            icon="el-icon-refresh"
                            type="primary"
                            plain
                            @click="handleSyncRedis()"
                            >同步缓存</el-button
                        >
                        <el-button
                            icon="el-icon-sort"
                            type="primary"
                            plain
                            @click="handleMoveDict()"
                            >移动字典</el-button
                        >
                        <!-- </el-button-group> -->
                    </template>
                    <template>
                        <ht-table-column
                            prop="name_"
                            label="名称"
                            :sortable="true"
                            :show-overflow-tooltip="true"
                        >
                            <template v-slot="{row}">
                                <el-link
                                    type="primary"
                                    @click="showDialog(row.id)"
                                    title="查看详情"
                                    >{{ row.name }}</el-link
                                >
                            </template>
                        </ht-table-column>
                        <ht-table-column
                            prop="code_"
                            label="编码"
                            :sortable="true"
                            :show-overflow-tooltip="true"
                        >
                            <template v-slot="{row}">
                                <span>{{ row.code }}</span>
                            </template>
                        </ht-table-column>
                        <!-- // _ID:(1：系统 2：租户） -->
                        <ht-table-column
                            prop="kind_id_"
                            label="类别"
                            :sortable="true"
                            :show-overflow-tooltip="true"
                        >
                            <template v-slot="{row}">
                                <el-tag v-if="row.kindId == 1">系统</el-tag>
                                <el-tag type="success" v-if="row.kindId == 2"
                                    >租户</el-tag
                                >
                            </template>
                        </ht-table-column>
                        <ht-table-column
                            prop="memo"
                            label="备注"
                            :show-overflow-tooltip="true"
                        >
                        </ht-table-column>
                        <ht-table-column
                            prop="flag_"
                            label="状态"
                            :sortable="true"
                            :show-overflow-tooltip="true"
                            :filters="filtersOptions"
                        >
                            <template v-slot="{row}">
                                <el-tag type="info" v-if="row.flag == -1"
                                    >草稿</el-tag
                                >
                                <el-tag type="success" v-if="row.flag == 1"
                                    >启用</el-tag
                                >
                                <el-tag type="danger" v-if="row.flag == 0"
                                    >禁用</el-tag
                                >
                            </template>
                        </ht-table-column>
                    </template>
                </ht-table>
            </el-main>
            <ht-sidebar-dialog
                width="48%"
                title="枚举字典表"
                class="sp-manager__dialog"
                :visible="dialogVisible"
                :before-close="beforeCloseDialog"
                v-if="dialogVisible"
            >
                <el-form v-form data-vv-scope="PortalSysDictionaryForm">
                    <el-row>
                        <el-col :span="10"
                            ><ht-form-item label="名称" label-width="60px">
                                <ht-input
                                    v-model="PortalSysDictionary.name"
                                    validate="required"
                                /> </ht-form-item
                        ></el-col>
                        <!-- <el-col :span="12"
                            >
                            <ht-form-item label="类别" label-width="60px">
                                <ht-radio
                                    v-model="PortalSysDictionary.kindId"
                                    :options="options.kindId"
                                    :props="{key: 'code', value: 'desc'}"
                                    validate="required"
                                /> </ht-form-item
                        ></el-col> -->
                        <el-col :span="10" :offset="4"
                            ><ht-form-item label="编码" label-width="60px">
                                <ht-input
                                    v-pinyin="PortalSysDictionary.name"
                                    v-model="PortalSysDictionary.code"
                                    validate="required"
                                /> </ht-form-item
                        ></el-col>
                        <el-col :span="24"
                            ><ht-form-item
                                label="备注"
                                label-width="60px"
                                width="100%"
                            >
                                <ht-input
                                    width="100%"
                                    v-model="PortalSysDictionary.memo"
                                /> </ht-form-item
                        ></el-col>
                    </el-row>

                    <el-row class="btn-group">
                        <el-button type="primary" @click="handleAdd"
                            >添加</el-button
                        >
                        <el-button
                            type="danger"
                            plain
                            @click="handleDictItemDel"
                            >删除</el-button
                        >
                        <el-button
                            type="success"
                            plain
                            @click="handleDictItemFlag(1)"
                            >启用</el-button
                        >
                        <el-button
                            type="danger"
                            plain
                            @click="handleDictItemFlag(0)"
                            >禁用</el-button
                        >
                        <el-button type="primary" plain @click="handleIndex"
                            >保存排序号</el-button
                        >
                    </el-row>
                    <el-table
                        class="edit-dict-table"
                        border
                        :height="tableHeight"
                        :data="dictItem"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column
                            type="selection"
                            header-align="center"
                            align="center"
                            width="45"
                        >
                        </el-table-column>
                        <el-table-column label="成员名称" header-align="center">
                            <template slot-scope="scope">
                                <ht-input
                                    :validate="{
                                        required: true,
                                        method: {
                                            callback: (value, args) =>
                                                checkRepeat(
                                                    value,
                                                    'name',
                                                    scope.row
                                                ),
                                            message: '成员名称重复',
                                        },
                                    }"
                                    v-model="scope.row.name"
                                >
                                </ht-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="成员值" header-align="center">
                            <template slot-scope="scope">
                                <ht-input
                                    :validate="{
                                        required: true,
                                        method: {
                                            callback: (value, args) =>
                                                checkRepeat(
                                                    value,
                                                    'value',
                                                    scope.row
                                                ),
                                            message: '成员值重复',
                                        },
                                    }"
                                    v-model="scope.row.value"
                                >
                                </ht-input>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="排序号"
                            header-align="center"
                            width="120px"
                        >
                            <template slot-scope="scope">
                                <ht-input
                                    width="100%"
                                    v-model="scope.row.sn"
                                    type="number"
                                    :min="1"
                                    :validate="{required: true}"
                                    @change="changeSN(scope.row, 'sn')"
                                ></ht-input>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="状态"
                            header-align="center"
                            width="66px"
                        >
                            <template slot-scope="scope">
                                <el-tag
                                    :type="
                                        scope.row.flag == -1
                                            ? 'info'
                                            : scope.row.flag == 1
                                            ? 'success'
                                            : 'danger'
                                    "
                                    >{{
                                        scope.row.flag == -1
                                            ? '草稿'
                                            : scope.row.flag == 1
                                            ? '启用'
                                            : '禁用'
                                    }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            width="90px"
                            header-align="center"
                        >
                            <template slot-scope="scope">
                                <el-button
                                    :disabled="!scope.row.id"
                                    type="text"
                                    :title="
                                        scope.row.id
                                            ? ''
                                            : '请先填写字典项并保存'
                                    "
                                    @click="loadSub(scope.row, 'setting')"
                                    >级联</el-button
                                >
                                <el-button
                                    :disabled="!scope.row.id"
                                    type="text"
                                    :title="
                                        scope.row.id
                                            ? ''
                                            : '请先填写字典项并保存'
                                    "
                                    @click="loadSub(scope.row, 'search')"
                                    >查看</el-button
                                >
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form>
                <lower-dict-modal ref="lowerDict"></lower-dict-modal>
                <div slot="footer" style="text-align: center">
                    <ht-submit-button
                        url="${portal}/sys/sysDictionary/v1/saveDictionary"
                        :model="PortalSysDictionary"
                        :request-method="saveMethod"
                        @before-save-data="beforeSaveData"
                        @after-save-data="afterSaveData"
                        @after-response-value="GetResponseValue"
                        scope-name="PortalSysDictionaryForm"
                        type="success"
                        >{{ $t('eip.common.save') }}</ht-submit-button
                    >
                    <ht-submit-button
                        url="${portal}/sys/sysDictionary/v1/saveDictionary"
                        :model="PortalSysDictionary"
                        :request-method="saveMethod"
                        @before-save-data="beforeSaveData"
                        @after-save-data="afterSaveData('close')"
                        scope-name="PortalSysDictionaryForm"
                        @click="beforeCloseDialog"
                        >{{ $t('eip.common.saveAndClose') }}</ht-submit-button
                    >
                    <el-button @click="beforeCloseDialog">{{
                        $t('eip.common.cancel')
                    }}</el-button>
                </div>
            </ht-sidebar-dialog>
            <ht-sidebar-dialog
                width="24%"
                title="移动字典"
                class="sp-manager__dialog"
                :visible="moveDialog"
                :before-close="beforeCloseMoveDialog"
            >
                <ht-sys-type-tree
                    type-key="SYS_DICT"
                    highlight-current
                    :hasFooter="false"
                    :hasNavbarCollapse="false"
                    :supportFilter="false"
                    ref="htSysTypeTree"
                    @node-click="handleMoveTreeClick"
                />
                <div slot="footer" style="text-align: center">
                    <el-button type="primary" @click="MoveDict">{{
                        $t('eip.common.save')
                    }}</el-button>
                    <el-button @click="beforeCloseMoveDialog">{{
                        $t('eip.common.cancel')
                    }}</el-button>
                </div>
            </ht-sidebar-dialog>
        </el-container>
    </el-container>
</template>
<script>
import portal from '@/api/portal'
import LowerDictModal from './LowerDictModal.vue'
import tenant from '@/store/tenant'
import user from '@/store/user'

const htAsideTree = () => import('@/components/common/HtAsideTree.vue')
const htSysTypeTree = () => import('@/components/common/HtSysTypeTree.vue')
export default {
    components: {
        htAsideTree,
        LowerDictModal,
        htSysTypeTree,
    },
    data() {
        return {
            tableHeight: 'calc(100vh - 318px)',
            dictItem: [],
            dialogVisible: false,
            filtersOptions: [
                {value: -1, text: '草稿'},
                {value: 1, text: '启用'},
                {value: 0, text: '禁用'},
            ],
            data: [],
            querySearch: [
                {
                    label: '名称',
                    prop: 'name_',
                },
                {
                    label: '编码',
                    prop: 'code_',
                },
            ],
            pageResult: {
                page: 1,
                pageSize: 50,
                total: 0,
            },
            options: {
                kindId: [
                    {code: 1, desc: '系统字典'},
                    {code: 2, desc: '租户字典'},
                ],
            },
            PortalSysDictionary: {
                name: '',
                code: '',
                kindId: 1,
                memo: '',
                details: [],
                treeId: '',
            },
            saveMethod: 'POST',
            multipleSelection: [],
            dictSelection: [],
            defaultQuerys: [],
            parantTreeId: '',
            // 移动字典
            moveDialog: false,
            moveDictionary: {},
            moveTreeId: '',
            currentDictId: '',
            snChange: null,
            tenantId: undefined, // -1 是超管,
            changeTree: false,
        }
    },
    mounted() {
        this.$validator = this.$root.$validator
    },
    methods: {
        // 树的点击回调  查询列表
        handleNodeClick(node) {
            this.changeTree = true
            if (node.parentId != 0) {
                this.$set(this.defaultQuerys, 0, {
                    property: 'TREE_ID_',
                    value: node.id,
                    operation: 'EQUAL',
                })
                this.parantTreeId = node.id
            } else {
                //清空旧的查询值
                this.defaultQuerys.splice(0)
                this.parantTreeId = ''
            }
            this.$refs.htTable.load()
        },
        // 加载字典
        loadData(param, cb) {
            console.log(param,'param')
            if (this.changeTree && this.parantTreeId) {
                param.querys = [
                    {
                        property: 'TREE_ID_',
                        value: this.parantTreeId,
                        operation: 'EQUAL',
                    },
                ]
            }else if (this.changeTree && !this.parantTreeId){
                param.querys = []
            }
            portal
                .loadDictList(param)
                .then((resp) => {
                    let response = resp
                    this.data = response.rows
                    this.pageResult = {
                        page: response.page,
                        pageSize: response.pageSize,
                        total: response.total,
                    }
                    this.changeTree = false
                })
                .finally(() => cb())
        },
        // 新增编辑
        showDialog(id) {
            if (
                user.state.currentUserDetail &&
                user.state.currentUserDetail.user
            ) {
                this.tenantId = user.state.currentUserDetail.user.tenantId
            }
            if (id) {
                this.currentDictId = id
                this.loadDictItem()
            } else {
                if (!this.parantTreeId) {
                    this.$message.warning('请先选择左侧添加的父节点！')
                } else {
                    this.dialogVisible = true
                }
            }
        },
        // 更新状态
        handleDictFlag(flag) {
            // this.dictSelection 选中的数据
            if (!this.dictSelection.length) {
                this.$message.warning(`请选择要${flag}用的数据`)
                return
            } else {
                let msg = `确定${flag}用选中数据吗?`
                this.$confirm(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(() => {
                        let ids = []
                        this.dictSelection.forEach((item) => {
                            ids.push(item.id)
                        })
                        let param = this.qs.stringify({
                            status: flag == '启' ? 1 : 0,
                            ids: ids.join(','),
                        })
                        // 调用接口 提交数据
                        portal.updateDictionariesStatus(param).then((res) => {
                            this.dictSelection = [];
                            this.$refs.htTable.load()
                        })
                    })
                    .catch(() => {
                        this.$message({
                            type: 'info',
                            message: `已取消${flag ? '启用' : '禁用'}`,
                        })
                    })
            }
        },
        // 清空选择项
        afterDelete(){
            this.dictSelection = [];
        },

        // 选择字典回调
        selectDict(selection, row) {
            this.dictSelection = selection
        },
        // 获取字典子表 --字典项
        loadDictItem() {
            let data = this.qs.stringify({id: this.currentDictId})
            portal.loadDictionaryById(data).then(
                (resp) => {
                    this.PortalSysDictionary = resp
                    if (this.PortalSysDictionary.details.length) {
                        this.PortalSysDictionary.details.sort((a, b) => {
                            return a.sn - b.sn
                        })
                        this.PortalSysDictionary.details.forEach(
                            (item, index) => {
                                item.key = new Date().getTime() + index
                            }
                        )
                        this.dictItem = [...this.PortalSysDictionary.details]
                    }
                    this.dialogVisible = true
                },
                (error) => {
                    reject(error)
                }
            )
        },
        // 子表改变排序号
        changeSN(row) {
            if (this.snChange == null) {
                this.snChange = {}
                this.snChange[row.id] = row.sn
            } else {
                this.snChange[row.id] = row.sn
            }
            console.log(this.snChange)
        },
        // 同步缓存
        handleSyncRedis() {
            portal
                .syncDictionaryRedis()
                .then((resp) => {
                    this.$message.success(resp.message)
                })
                .catch((err) => {
                    this.$message.warning(err)
                })
        },
        // 移动字典
        handleMoveDict() {
            if (!this.dictSelection.length) {
                this.$message.warning(`请选择要移动的字典`)
                return
            } else {
                this.moveDialog = true
            }
        },
        beforeCloseMoveDialog() {
            this.moveTreeId = ''
            this.moveDialog = false
        },
        MoveDict() {
            if (!this.moveTreeId) {
                this.$message.warning(`请选择移动的目标字典目录`)
                return
            }
            let ids = []
            this.dictSelection.forEach((item) => {
                ids.push(item.id)
            })
            let data = this.qs.stringify({
                treeId: this.moveTreeId,
                ids: ids.join(','),
            })
            portal
                .moveDictionaries(data)
                .then((res) => {
                    this.moveTreeId = ''
                    this.moveDialog = false
                    this.dictSelection = []
                    this.$refs.htTable.load()
                })
                .catch((err) => {
                    this.$message.warning(err)
                })
        },
        handleMoveTreeClick(node) {
            console.log(node)
            if (node.parentId != 0) {
                this.moveTreeId = node.id
            } else {
                this.moveTreeId = ''
            }
        },
        // 子表验证
        checkRepeat(value, column, currentItem) {
            return new Promise((resolve) => {
                let Temp = this.dictItem.filter(
                    (item) => item.key != currentItem.key
                )
                if (Temp.length) {
                    Temp.forEach((item) => {
                        if (item[column] == value) {
                            resolve(false)
                        }
                    })
                    resolve(true)
                } else {
                    resolve(true)
                }
            })
        },
        // 提交验证
        async beforeSaveData() {
            console.log(this.dictItem, this.tenantId)
            if (this.dictItem.length) {
                // this.checkDictItem();
                let TempArr = [...this.dictItem]
                TempArr.forEach((item) => {
                    delete item.key
                })
                this.PortalSysDictionary.details = TempArr
            }
            console.log(this.dictItem, 'beforeSaveData')
            if (!this.PortalSysDictionary.treeId) {
                this.PortalSysDictionary.treeId = this.parantTreeId
            }
            console.log(tenant)
            if (tenant.state.tenantId) {
                this.PortalSysDictionary.tenantId = tenant.state.tenantId
            }
            // 超管默认添加系统字典，其他默认是租户字典
            this.PortalSysDictionary.kindId = this.tenantId == '-1' ? 1 : 2
            this.isSubmit = true
        },
        handleAdd() {
            let length = this.dictItem.length
            let dictionaryId = ''
            if (this.PortalSysDictionary && this.PortalSysDictionary.id) {
                dictionaryId = this.PortalSysDictionary.id
            }
            this.dictItem.push({
                dictionaryId,
                name: '',
                value: '',
                sn: length + 1,
                flag: -1,
                key: new Date().getTime() + length,
            })
        },
        handleDictItemDel() {
            // 非草稿状态不可删除
            // 区别有id 没得id
            if (!this.multipleSelection.length) {
                this.$message.warning('请选择要删除得数据')
                return
            } else {
                // 过滤出草稿状态得数据
                let initDictItem = this.multipleSelection.filter(
                    (item) => item.flag == -1
                )
                if (!initDictItem.length) {
                    this.$message.warning('启用或禁用状态的数据，不可删除！')
                } else {
                    let msg =
                        '如存在未保存的字典成员,请先保存！如继续此操作未保存的编辑将被删除,是否继续?'
                    this.$confirm(msg, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    })
                        .then(() => {
                            // 收集已提交的数据id
                            let ids = [],
                                keys = []
                            initDictItem.forEach((item) => {
                                keys.push(item.key)
                                if (item.id) {
                                    ids.push(item.id)
                                }
                            })
                            // 本地删除草稿的数据
                            const dataSource = [...this.dictItem]
                            let dataTemp = dataSource.filter(
                                (item) => !keys.includes(item.key)
                            )
                            this.dictItem = dataTemp

                            if (ids.length > 0) {
                                // 提交数据
                                let params = this.qs.stringify({
                                    ids: ids.join(','),
                                })
                                portal.deleteDictItem(params).then(() => {
                                    this.loadDictItem()
                                    this.$message.success('删除成功')
                                })
                            }
                        })
                        .catch(() => {
                            this.$message({
                                type: 'info',
                                message: `已取消删除`,
                            })
                        })
                }
            }
        },
        handleDictItemFlag(status) {
            this.multipleSelection.forEach((item) => {
                item.keys
            })
            let hasNoSave = false
            if (this.multipleSelection.length <= 0) {
                this.$message.warning('请选择至少一条数据！')
                return
            } else {
                let ids = []
                this.multipleSelection.forEach((item) => {
                    if (!item.id) {
                        hasNoSave = true
                        return
                    }
                    ids.push(item.id)
                })
                if (ids.length <= 0) {
                    this.$message.warning('所选数据未保存，不能进行该操作！')
                    return
                }
                let query = {
                    ids: ids.join(','),
                    status,
                }
                let param = this.qs.stringify(query, {
                    indices: false,
                })
                let tag = status ? '启' : '禁'
                let msg
                if (hasNoSave) {
                    msg =
                        '存在未保存的字段成员,请先保存！如继续此操作未保存的编辑将被清除,是否继续?'
                } else {
                    msg = `确定${tag}用选中数据,是否继续?`
                }
                this.$confirm(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(() => {
                        // 调用接口 提交数据
                        portal.updateDictItemStatus(param).then(() => {
                            this.loadDictItem()
                            this.$message.success(
                                `${status ? '启用' : '禁用'}成功`
                            )
                        })
                    })
                    .catch(() => {
                        this.$message({
                            type: 'info',
                            message: `已取消${status ? '启用' : '禁用'}`,
                        })
                    })
            }
        },
        handleIndex() {
            if (this.snChange == null) {
                this.$message.warning('字典项排序号无更改')
            } else {
                portal.updateDictItemSequence(this.snChange).then(() => {
                    this.loadDictItem()
                    this.$message.success('排序号更新成功!')
                })
            }
        },
        // 子表的选择回调
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        // 打开级联字典弹窗
        loadSub(row, type) {
            console.log(row, type)
            this.$refs.lowerDict.open(row, type, this.currentDictId)
        },
        // 关闭前重置状态
        beforeCloseDialog() {
            this.PortalSysDictionary = {
                kindId: 1,
                name: '',
                code: '',
                memo: '',
                details: [],
                treeId: '',
            }
            this.dictItem = []
            this.currentDictId = ''
            this.dialogVisible = false
        },
        afterSaveData(close) {
            setTimeout(() => {
                if (close) {
                    this.beforeCloseDialog()
                } else {
                    this.loadDictItem()
                }
                this.$refs.htTable.load()
            }, 0)
        },
        GetResponseValue(value){
            this.currentDictId = value;
        }
    },
}
</script>

<style lang="scss" scoped>
.sp-manager__dialog /deep/ > .el-dialog > .el-dialog__body {
    height: calc(100% - 170px);
}
.sp-manager__dialog /deep/ .move-tree .el-aside {
    border-right: 0 !important;
}
.sp-manager__dialog /deep/ .edit-dict-table td .el-form-item__error {
    top: calc(78%);
}

.btn-group {
    margin-bottom: 10px;
}
.sp-manager__dialog /deep/ .el-form-item__content .inputs {
    width: 100%;
}
</style>
