<template>
    <ap-container>
        <ap-aside margin="1111">
            <div class="layout-aside-header">
                <div class="layout-aside-header-title">组织部门</div>
            </div>
            <div>
                <el-input placeholder="关键字过滤" v-model="treeFilterText"></el-input>
            </div>
            <div class="layout-aside-content" v-loading="loadingTreeFlag">
                <el-tree
                    ref="tSysOrgTree"
                    node-key="fdId"
                    :data="treeData"
                    :props="{children: 'children',label: 'fdName'}"
                    :check-on-click-node="true"
                    :highlight-current="true"
                    :expand-on-click-node="false"
                    :check-strictly="false"
                    :filter-node-method="filterTreeNode"
                    @node-click="clickTreeEvent">
                </el-tree>
            </div>
        </ap-aside>
        <ap-split-panel></ap-split-panel>
        <ap-container>
            <ap-header margin="1110">
                <el-form ref="tSysPersonSearchForm" :model="tSysPersonSearchForm" :rules="tSysPersonSearchFormRules"
                         :inline="true" class="layout-header-form" @submit.native.prevent="searchEvent">
                    <el-form-item label="搜索:" class="layout-header-form-item" prop="likeStr">
                        <el-input v-model="tSysPersonSearchForm.likeStr" placeholder="姓名/工号/部门"></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" @click="searchEvent">查询</el-button>
            </ap-header>
            <ap-main margin="0110">
                <ap-table ref="tSysPersonTableRef" :options.sync="tSysPersonTable"></ap-table>
            </ap-main>
        </ap-container>

        <el-dialog :title="dialogInfo.title" :visible.sync="dialogInfo.isVisible" width="1100px"
                   @close="resetTSysPersonForm">
            <el-form ref="tSysPersonFormRef" :model="tSysPersonForm" :rules="tSysPersonFormRules"
                     v-loading="dialogInfo.formIsLoading"
                     label-width="80px" :inline="true" class="ap-form">

                <div class="ap-form-row">
                    <el-form-item label='id' prop='fdId'>
                        <el-input v-model='tSysPersonForm.fdId' disabled></el-input>
                    </el-form-item>
                    <el-form-item label='部门' prop='fdDeptId'>
                        <el-select v-model="tSysPersonForm.fdDeptId" placeholder="请选择" @change="deptChangeEvent"
                                   style="width: 350px;" filterable>
                            <el-option v-for="item in orgList" :key="item.fdId" :label="item.fdFullName"
                                       :value="item.fdId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="ap-form-row">
                    <el-form-item label='姓名' prop='fdName'>
                        <el-input v-model='tSysPersonForm.fdName'></el-input>
                    </el-form-item>
                    <el-form-item label='工号' prop='fdNo'>
                        <el-input v-model='tSysPersonForm.fdNo'></el-input>
                    </el-form-item>
                    <el-form-item label='性别' prop='fdSex'>
                        <el-radio-group v-model="tSysPersonForm.fdSex">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="0">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>

                <div class="ap-form-row">
                    <el-form-item label='用工类型' prop='fdWorkType'>
                        <el-select v-model="tSysPersonForm.fdWorkType" placeholder="请选择">
                            <el-option v-for="item in personWorkTypeList" :key="item.value" :label="item.key"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label='职能类型' prop='fdType'>
                        <el-select v-model="tSysPersonForm.fdType" placeholder="请选择">
                            <el-option v-for="item in personTypeList" :key="item.value" :label="item.key"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="ap-form-row">
                    <el-form-item label='岗位' prop='fdJob'>
                        <el-input v-model='tSysPersonForm.fdJob'></el-input>
                    </el-form-item>
                    <el-form-item label='岗位职称' prop='fdJobTitle'>
                        <el-select v-model="tSysPersonForm.fdJobTitle" placeholder="请选择">
                            <el-option v-for="item in personTitleList" :key="item.value" :label="item.key"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="ap-form-row">
                    <el-form-item label='手机号码' prop='fdMobile'>
                        <el-input v-model='tSysPersonForm.fdMobile'></el-input>
                    </el-form-item>
                    <el-form-item label='短号' prop='fdPhoneShort'>
                        <el-input v-model='tSysPersonForm.fdPhoneShort'></el-input>
                    </el-form-item>
                    <el-form-item label='邮箱' prop='fdEmail'>
                        <el-input v-model='tSysPersonForm.fdEmail'></el-input>
                    </el-form-item>
                </div>
                <el-form-item label='身份证' prop='fdIdCard'>
                    <el-input v-model='tSysPersonForm.fdIdCard'></el-input>
                </el-form-item>
                <el-form-item label='生日' prop='fdBirthday'>
                    <el-date-picker type="date" placeholder="选择日期" value-format="timestamp"
                                    v-model="tSysPersonForm.fdBirthday"></el-date-picker>
                </el-form-item>
                <div class="ap-form-row">
                    <el-form-item label='入职时间' prop='fdJoinDate'>
                        <el-date-picker type="date" placeholder="选择日期" value-format="timestamp"
                                        v-model="tSysPersonForm.fdJoinDate"></el-date-picker>
                    </el-form-item>
                    <el-form-item label='离职时间' prop='fdLeaveDate'>
                        <el-date-picker type="date" placeholder="选择日期" value-format="timestamp"
                                        v-model="tSysPersonForm.fdLeaveDate"></el-date-picker>
                    </el-form-item>
                    <el-form-item label='离职方式' prop='fdLeaveType'>
                        <el-input v-model='tSysPersonForm.fdLeaveType'></el-input>
                    </el-form-item>
                </div>
                <div class="ap-form-row">
                    <el-form-item label='状态' prop='fdStatus'>
                        <el-radio-group v-model="tSysPersonForm.fdStatus">
                            <el-radio :label="1">在职</el-radio>
                            <el-radio :label="0">离职</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label='是否有效' prop='fdDisabled'>
                        <el-radio-group v-model="tSysPersonForm.fdDisabled">
                            <el-radio :label="0">有效</el-radio>
                            <el-radio :label="1">失效</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>
                <el-form-item label='备注' prop='fdComment'>
                    <el-input v-model='tSysPersonForm.fdComment'></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer">
                <el-button @click="dialogInfo.isVisible = false">取 消</el-button>
                <el-button v-if="hasEditPermission()" type="primary" @click="saveTSysPersonForm"
                           :loading="dialogInfo.saveBtnIsLoading">确 定</el-button>
                <el-button v-else type="warning" >无编辑同步用户权限</el-button>
            </span>
        </el-dialog>
    </ap-container>
</template>

<script>
import {convertToTreeData, getTreeChildrenIdsById} from 'ap-util/util/DataUtil'
import {hasPermission} from 'ap-util/util/LoginUserUtil'
export default {
    name: 'SysPerson',
    data() {
        let tSysPersonCols = [
            {
                prop: 'fdName',
                label: '名称',
                width: 100,
                type: 'input'
            }, {
                prop: 'fdJoinDate',
                label: '日期',
                type: 'datePicker',
                width: 100,
                align: "center",
                datePickerFormat: 'yyyy-MM-dd'
            }, {
                prop: 'fdSex',
                label: '性别',
                type: 'select',
                width: 60,
                align: "center",
                selectOptions: [{label: "男", value: "1"}, {label: "女", value: "0"}]
            }, {
                prop: 'fdNo',
                label: '工号',
                width: 120,
                type: 'input'
            }, {
                prop: 'fdDeptName',
                label: '部门名称',
                width: 120,
                type: 'input'
            }, {
                prop: 'fdFullName',
                label: '全称',
                type: 'input'
            }, {
                prop: 'fdJob',
                label: '岗位',
                width: 120,
                type: 'input'
            }, {
                prop: 'fdJobTitle',
                label: '岗位职称',
                width: 100,
                type: 'select',
                selectOptionsKey: {label: "key", value: "value"},
                selectOptionsRemote: 'personTitleList'
            }, {
                prop: 'fdSourceId',
                label: '来源',
                type: 'input',
                width: 70,
                align: "center",
                html: function (value, row) {
                    if (value == null || value == "") {
                        return '<div class="ap-color-yellow">手动</div>'
                    } else {
                        return '<div class="ap-color-green">同步</div>'
                    }
                }
            }, {
                prop: 'fdStatus',
                label: '状态',
                type: 'input',
                width: 80,
                align: "center",
                html: function (value, row) {
                    if (value == 0) {
                        return '<div class="ap-tag-danger">离职</div>'
                    } else if (value == 1) {
                        return '<div class="ap-tag-success">在职</el-tag>';
                    }
                }
            }, {
                prop: 'fdDisabled',
                label: '是否有效',
                type: 'input',
                align: "center",
                width: 80,
                html: function (value, row) {
                    if (value == 1) {
                        return '<div class="ap-tag-danger">失效</div>'
                    } else if (value == 0) {
                        return '<div class="ap-tag-success">有效</el-tag>';
                    }
                }
            },
        ];
        let toolbarBtn = [
            {
                btnType: "primary",
                text: "更新人员部门",
                icon: "el-icon-magic-stick",
                onClick: this.refreshPersonDept
            },
            "separator",
            {type: "add", onClick: this.openAddDialog},
            {type: "edit", onClick: this.openEditDialog},
            "del", "refresh", "save"
        ];
        let tSysPersonTable = {
            title: "人员列表",
            columns: tSysPersonCols,
            dataUrl: "/apm/sys/person/getTSysPersonGridList",
            deletePk: "fdId", // 默认fdId
            deleteUrl: "/apm/sys/person/updateTSysPersonForDelete",
            toolbarBtn: toolbarBtn,
            beforeDelete: () => {
                if (!this.hasEditPermission()) {
                    this.$message.error("删除失败！没有删除同步用户的权限")
                    return false;
                }
                return true;
            },
            params: () => {
                return {
                    likeStr: this.tSysPersonSearchForm.likeStr,
                    treeSelectedValues: this.treeSelectedValues
                }
            }
        };
        let tSysPersonForm = {
            fdId: '',
            fdName: '',
            fdSex: 1,
            fdNo: '',
            fdDeptId: '',
            fdDeptName: '',
            fdWorkType: '',
            fdType: '',
            fdJob: '',
            fdJobTitle: null,
            fdEmail: '',
            fdMobile: '',
            fdPhoneShort: '',
            fdIdCard: '',
            fdBirthday: null,
            fdStatus: 1,
            fdJoinDate: null,
            fdLeaveDate: null,
            fdLeaveType: '',
            fdDeletedDate: null,
            fdDisabledDate: null,
            fdDeleted: '',
            fdDisabled: 0,
            fdComment: '',
        };
        return {
            // ----- 左侧树 -----
            loadingTreeFlag: false,
            treeFilterText: '',
            treeData: [],
            treeSelectedValues: "",
            // ----- 右侧 -----
            orgList: [],
            personTitleList: [],
            personTypeList: [],
            personWorkTypeList: [],
            tSysPersonTable: tSysPersonTable,
            tSysPersonForm: tSysPersonForm,
            tSysPersonFormRules: {

            },
            dialogInfo: {
                title: "",
                isAdd: false,
                isVisible: false,
                saveBtnIsLoading: false,
                formIsLoading: false
            },
            tSysPersonSearchForm: {
                likeStr: ""
            },
            tSysPersonSearchFormRules: {

                likeStr: [{min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}]
            }
        }
    },
    watch: {
        treeFilterText(val) {
            // 过滤值修改，更新tree
            this.$refs.tSysOrgTree.filter(val);
        },
    },
    created() {
        this.loadTreeData();
        this.initEditInfo();
    },
    methods: {
        hasEditPermission() {
            return hasPermission("SYS-ORG-SYNC-EDIT");
        },
        // 左侧树：加载数据
        loadTreeData() {
            this.loadingTreeFlag = true;
            // 加载数据
            this.$request({
                url: '/apm/sys/org/getTSysOrgList',
                method: 'post'
            }).then(response => {
                // 数据格式转换：数组 -> tree
                this.treeData = convertToTreeData(response.data, {
                    idKey: "fdId",
                    parentKey: "fdParentId",
                    childrenKey: "children",
                });
            }).finally(() => {
                this.loadingTreeFlag = false;
            })
        },
        // 左侧树：过滤节点
        filterTreeNode(value, data) {
            if (!value) return true;
            return data.fdName.indexOf(value) !== -1;
        },
        // 左侧树：click事件
        clickTreeEvent(data, node, comp) {
            this.treeSelectedValues = getTreeChildrenIdsById(this.treeData, data.fdId);
            this.tSysPersonTable.title = `人员列表 - ${data.fdFullName}`;
            this.tSysPersonForm.fdDeptId = data.fdId;
            this.$refs.tSysPersonTableRef.refresh();
        },
        initEditInfo() {
            this.$request({
                url: '/apm/sys/person/getEditInfo',
                method: 'post',
                data: {}
            }).then(response => {
                this.personWorkTypeList = response.data.personWorkTypeList;
                this.personTypeList = response.data.personTypeList;
                this.orgList = response.data.orgList;
                this.personTitleList = response.data.personTitleList;
            }).finally(() => {
                this.dialogInfo.formIsLoading = false;
            })
        },
        // 右侧：打开添加dialog
        openAddDialog() {
            this.dialogInfo.isAdd = true;
            this.dialogInfo.title = "添加人员信息";
            this.dialogInfo.isVisible = true;
        },
        // 右侧：打开编辑dialog
        openEditDialog() {
            let selectedRows = this.$refs.tSysPersonTableRef.getSelection();
            if (selectedRows.length < 1) {
                this.$message.error("请选择需要编辑的行！")
                return;
            }
            if (selectedRows.length > 1) {
                this.$message.error("只能选择单行数据进行编辑！")
                return;
            }

            this.dialogInfo.isAdd = false;
            this.dialogInfo.title = "编辑人员信息"
            this.dialogInfo.isVisible = true;
            this.dialogInfo.formIsLoading = true;
            // 获取单条数据
            this.$request({
                url: '/apm/sys/person/getTSysPersonByFdId',
                method: 'post',
                data: {
                    fdId: selectedRows[0].fdId
                }
            }).then(response => {
                this.tSysPersonForm = response.data;
            }).finally(() => {
                this.dialogInfo.formIsLoading = false;
            })
        },
        // 右侧：重置dialog表单
        resetTSysPersonForm() {
            this.$refs.tSysPersonFormRef.resetFields();
        },
        // 右侧：dialog表单保存
        saveTSysPersonForm() {
            // 表单rules认证
            this.$refs.tSysPersonFormRef.validate((valid) => {
                if (!valid) {
                    this.$message.error('数据校验错误！');
                    return false;
                }
                this.dialogInfo.saveBtnIsLoading = true;

                let fnName = this.dialogInfo.isAdd ? "insertTSysPerson" : "updateTSysPerson";
                // 添加数据
                this.$request({
                    url: '/apm/sys/person/' + fnName,
                    method: 'post',
                    data: this.tSysPersonForm
                }).then(response => {
                    this.$message.success(`保存成功！`)
                    this.dialogInfo.isVisible = false;
                    // 刷新表格
                    this.$refs.tSysPersonTableRef.refresh();
                }).finally(() => {
                    this.dialogInfo.saveBtnIsLoading = false;
                })
            });
        },
        // 右侧：查询事件
        searchEvent() {
            // 表单rules认证
            this.$refs.tSysPersonSearchForm.validate((valid) => {
                if (!valid) {
                    this.$message.error('搜索条件格式不正确！');
                    return false;
                }
                this.$refs.tSysPersonTableRef.refresh();
            });
        },
        deptChangeEvent(value) {
            let orgList = this.orgList;
            for (let i = 0; i < orgList.length; i++) {
                if (orgList[i].fdId == value) {
                    if (this.dialogInfo.isAdd) {
                        this.tSysPersonForm.fdDeptName = orgList[i].fdName;
                    } else {
                        this.tSysPersonForm.fdDeptName = orgList[i].fdName;
                    }
                    return
                }
            }
        },
        // 刷新人员部门信息
        refreshPersonDept(){
            this.$request({
                url: '/apm/sys/person/refreshPersonDept',
                method: 'post',
            }).then(response => {
                this.$message.success(`更新成功！`);
                // 刷新表格
                this.$refs.tSysPersonTableRef.refresh();
            }).finally(() => {
            });
        }
    }
}
</script>

<style scoped>
</style>