<template>
    <div class="testdiv">
        <div class="divborder newSearchDiv" style="margin:0px;">
            <div class="filter">
                <label>{{$t('100000')}}：</label>
                <Select
                    v-model="sectionid"
                    label-in-value
                    @on-change="departmentsearchchange"
                    clearable
                    class="searchSelect"
                >
                    <Option
                        v-for="item in department"
                        :value="item.id"
                        :key="item.id"
                    >{{ item.title }}</Option>
                </Select>
            </div>
            <div class="searchBtn">
                <Button
                type="success"
                icon="md-add-circle"
                class="fourWord"
                @click="Adddepartment()"
            >{{$t('100025')}}</Button>
            <Button
                type="success"
                icon="md-add-circle"
                class="fourWord intervalRight"
                @click="addusergroup()"
            >{{$t('100026')}}</Button>
            <Button
                type="warning"
                icon="ios-create-outline"
                class="twoWord"
                @click="edit()"
            >{{$t('1003')}}</Button>
            <Button
                type="error"
                icon="md-close-circle"
                class="twoWord intervalRight"
                @click="dele()"
            >{{$t('1004')}}</Button>
            <Button
                type="primary"
                icon="ios-create-outline"
                class="fourWord"
                @click="handlepower()"
            >{{$t('101091')}}</Button>
            </div>
        </div>
        <div class="divborder newTableDiv">
            <Table
                class="tableClass"
                @on-current-change="handleRowChange1"
                highlight-row
                :data="tableData1"
                :columns="tableColumns1"
            ></Table>
        </div>
        <div class="divborder newTableDiv">
            <Table
                class="tableClass"
                @on-current-change="handleRowChange"
                highlight-row
                :data="tableData2"
                :columns="tableColumns2"
            ></Table>
        </div>

        <Modal class="newModalClass" :title="title2" v-model="departmodal" :styles="{width:'600px'}">
            <div class="modal_body">
                    <div class="filter">
                        <label>
                           <i>*</i> {{$t('100027')}}：
                        </label>
                        <Input
                            class="searchInput"
                            type="text"
                            id="add_name"
                            v-model="editobj.title"
                        />
                    </div>
                    <div class="filter">
                        <label>
                           <i>*</i> {{$t('100035')}}：
                        </label>
                        <RadioGroup v-model="editobj.sectiontype">
                            <Radio label="1" :key="1" style="width:100px!important;">
                                <span v-text="$t('600608')"></span>
                            </Radio>
                            <Radio label="2" :key="2" style="width:100px!important;">
                                <span v-text="$t('600609')"></span>
                            </Radio>
                        </RadioGroup>
                    </div>
                    <div class="filter" style="display:flex;margin-bottom: 30px;">
                        <label>
                            <i >*</i>{{$t('100028')}}：
                        </label>
                        <Input
                            type="textarea"
                            id="add_desc"
                            v-model="editobj.description"
                            class="searchInput MaxWidth"
                            :autosize="{minRows: 2,maxRows: 2}"
                        />
                    </div>
            </div>
            <div slot="footer">
                <Button type="text" size="large" @click="cancle">{{$t("1033")}}</Button>
                <Button
                    type="primary"
                    v-if="optiontype===1"
                    size="large"
                    @click="Adddepartmentdata()"
                >{{$t("1002")}}</Button>
                <Button
                    type="primary"
                    v-if="optiontype===2"
                    size="large"
                    @click="editdata()"
                >{{$t("1003")}}</Button>
            </div>
        </Modal>

        <Modal class="newModalClass" :title="title3" v-model="groupmodal" :styles="{width:'630px'}">
            <div class="modal_body">
                    <div class="filter special_div">
                        <label>
                           <i>*</i>{{$t('100239')}}：
                        </label>
                        <Select
                            v-model="departmentid"
                            label-in-value
                            @on-change="departmentchange()"
                            clearable
                            class="searchSelect"
                        >
                            <Option
                                v-for="item in departmentlist"
                                :value="item.id"
                                :key="item.id"
                            >{{ item.title }}</Option>
                        </Select>
                    </div>
                    <div class="filter">
                        <label>{{$t('100034')}}：</label>
                        <Select v-model="usergroupid" label-in-value clearable class="searchSelect">
                            <Option
                                v-for="item in usergroup"
                                :value="item.id"
                                :key="item.id"
                                :disabled="seletshow"
                            >{{ item.title }}</Option>
                        </Select>
                    </div>
                    <div class="filter">
                        <label>
                            <i>*</i>{{$t('100029')}}：
                        </label>
                        <Input
                            class="searchInput"
                            type="text"
                            id="groupname"
                            v-model="editobj1.title"
                        />
                    </div>
                    <div class="filter">
                        <label>{{$t('100031')}}：</label>
                        <Input
                            class="searchInput"
                            type="text"
                            id="groupdesc"
                            v-model="editobj1.description"
                        />
                    </div>
            </div>
            <div slot="footer">
                <Button type="text" size="large" @click="cancle">{{$t("1033")}}</Button>
                <Button
                    type="primary"
                    v-if="optiontype===1"
                    size="large"
                    @click="Addusergroupdata()"
                >{{$t("1002")}}</Button>
                <Button
                    type="primary"
                    v-if="optiontype===2"
                    size="large"
                    @click="editdata()"
                >{{$t("1003")}}</Button>
            </div>
        </Modal>
        <!-- 设置权限 -->
        <Modal
            :title="title1"
            v-model="settingmodal"
            :styles="{width:'650px'}"
             class="newModalClass"
        >
            <Tabs type="card" value="1" v-model="type">
                <TabPane :label="$t(600662)" name="1">
                    <div class="modal_body">
                        <div style="width:560px;float:left;height:400px;padding-left:0px;overflow-x:auto;">
                            <div>
                                <Tree :data="powerdata" show-checkbox multiple ref="tree"></Tree>
                            </div>
                        </div>
                    </div>
                </TabPane>
                <TabPane :label="$t(600663)" name="2" :disabled="powerlimit==true">
                    <p>KPI</p>
                    <div>
                        <div class="filter">
                            <label>{{$t(100027)}}：</label>
                        </div>

                        <span>{{obj.sectionname}}</span>
                    </div>
                    <div>
                        <div class="filter">
                            <label>{{$t(100029)}}：</label>
                        </div>

                        <span>{{obj.title}}</span>
                    </div>
                    <div>
                        <div class="filter">
                            <label>{{$t(600661)}}：</label>
                            <Select v-model="otherdepart" multiple class="searchSelect MaxWidth nowropStyle">
                                <Option
                                    v-for="item in departmentlist"
                                    :value="item.id"
                                    :key="item.id"
                                >{{ item.title }}</Option>
                            </Select>
                        </div>
                    </div>
                </TabPane>
            </Tabs>

            <div slot="footer">
                <Button type="text" size="large" @click="cancle">{{$t("1033")}}</Button>
                <Button
                    type="primary"
                    size="large"
                    v-show="type==1"
                    @click="savepower"
                >{{$t("900552")}}</Button>
                <Button
                    type="primary"
                    size="large"
                    v-show="type==2"
                    @click="saveDepartPower"
                >{{$t(900306)}}</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import axios from '@/libs/api.request';

export default {
    data () {
        return {
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            title1: this.$t('101091'),
            tableData1: [],
            tableData2: [],
            departmodal: false,
            groupmodal: false,
            page: 1,
            pagesize: 10,
            total: 0,
            tableColumns1: [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    width: 90
                },
                {
                    title: this.$t('100027'),
                    key: 'title'
                },
                {
                    title: this.$t('100035'),
                    key: 'typename'
                },
                {
                    title: this.$t('100028'),
                    key: 'description'
                },
                {
                    title: this.$t('1020'),
                    key: 'create_time'
                }
            ],
            tableColumns2: [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    width: 90
                },
                {
                    title: this.$t('100029'),
                    key: 'title'
                },
                {
                    title: this.$t('100030'),
                    key: 'fatherUserGroupTitle',
                    render: (h, params) => {
                        var isNoFather =
                            params.row.fatherUserGroupTitle ===
                            this.$t('101051');
                        var color =
                            params.row.fatherUserGroupTitle ===
                            this.$t('101051')
                                ? 'gray'
                                : '';
                        return h('span', [
                            h(
                                isNoFather ? 'i' : 'p',
                                {
                                    style: {
                                        color: color
                                    }
                                },
                                params.row.fatherUserGroupTitle
                            )
                        ]);
                    }
                },
                {
                    title: this.$t('100031'),
                    key: 'description'
                },
                {
                    title: this.$t('100032'),
                    key: 'number'
                },
                {
                    title: this.$t('100033'),
                    key: 'sectionname'
                },
                {
                    title: this.$t('1020'),
                    key: 'create_time'
                }
            ],
            sectionid: 0,
            usergroupid: 0,
            department: [],
            editobj: {},
            editobj1: {},
            departmentlist: [],
            departmentid: 0,
            usergroup: [],
            settingmodal: false,
            powerdata: [],
            optiontype: 0,
            title2: this.$t('100025'),
            title3: this.$t('100026'),
            seletshow: false,
            type: '1',
            single: false,
            defaultdepart: '本部门',
            otherdepart: [],
            powerlimit: false
        };
    },
    created () {
        this.search(1, 10000);
        this.initdepartment();

        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
        this.tableColumns2 = this.$time.initTableTitle(this.tableColumns2)
    },
    methods: {
        cancle () {
            this.editobj = {};
            this.editobj1 = {};
            this.departmodal = false;
            this.groupmodal = false;
            this.settingmodal = false;
            this.optiontype = 0;
            this.search(1, 10000);
        },
        handlepower () {
            if (
                JSON.stringify(this.obj) === '{}' ||
                this.obj === undefined ||
                this.obj === null
            ) {
                this.$Message.error(this.$t('1043'));
                return false;
            }
            this.type = '1';
            var params = { roleid: this.obj.id };
            var url = '';
            if (this.obj.edittype === 1) {
                url = '/config/UserRole/getNormalUserRoleMaintenanceListEx';
            } else if (this.obj.edittype === 2) {
                url =
                    '/config/UserRole/getNormalSectionUserRoleMaintenanceListEx';
            }
            axios
                .request({
                    url: url,
                    params,
                    method: 'get'
                })
                .then(res => {
                    this.powerdata = [];
                    this.settingmodal = true;
                    let data = res.data.data;
                    data.forEach(item => {
                        let data = {};
                        data.id = item.id;
                        data.title = this.$t(item.title);
                        data.expand = item.expand;
                        data.checked = item.checked;
                        data.children = this.getchildren(item);
                        this.powerdata.push(data);
                    });

                    this.loadKpiPermission();
                });
        },
        getchildren (item) {
            let arry = [];
            if (item.children !== [] && item.children.length > 0) {
                item.children.forEach(child => {
                    let data = {};
                    data.id = child.id;
                    data.title = this.$t(child.title);
                    data.expand = child.expand;
                    data.checked = child.checked;
                    data.children = this.getchildren(child);
                    arry.push(data);
                });
            }
            return arry;
        },
        savepower () {
            let per = this.$refs.tree.getCheckedAndIndeterminateNodes();
            let permissions = [];
            per.forEach(item => permissions.push(item.id));
            var data = { roleid: this.obj.id, permissions: permissions };
            var url = '';
            if (this.obj.edittype === 1) {
                url = '/config/UserRole/setNormalUserRoleMaintenance';
            } else {
                url = '/config/UserRole/SetNormalUserGroupRoleMaintenance';
            }
            axios
                .request({
                    url: url,
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t('1064'));
                        this.settingmodal = false;
                        this.page = 1;
                        this.departmentsearchchange();
                    } else {
                        this.$Message.error(
                            this.$t('400045') + ':' + this.$t(res.data.msg)
                        );
                        this.departmentsearchchange();
                    }
                });
        },
        // 保存部门权限
        saveDepartPower () {
            if (this.obj.type == 1) {
                this.$Message.error('请选择岗位');
                return;
            }
            var data = {
                usergroup: this.obj.id,
                section: this.otherdepart
            };
            axios
                .request({
                    url: '/kpi/Authority/Modify',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t(1060));
                        this.otherdepart = [];
                        this.settingmodal = false;
                        this.search(this.page, this.pagesize);
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        loadKpiPermission () {
            this.otherdepart = [];
            axios
                .request({
                    url: '/kpi/Authority/Items?usergroup=' + this.obj.id,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        res.data.data.forEach(item =>
                            this.otherdepart.push(item.authorization)
                        );
                    }
                });
        },
        Adddepartment () {
            this.title2 = this.$t('100025');
            this.optiontype = 1;
            this.departmodal = true;
            this.editobj = {};
        },
        addusergroup () {
            this.title3 = this.$t('100026');
            this.optiontype = 1;
            this.groupmodal = true;
            this.departmentid = 0;
            this.usergroupid = 0;
            this.editobj1 = {};
            this.seletshow = false;
        },
        edit () {
            if (
                JSON.stringify(this.obj) === '{}' ||
                this.obj === undefined ||
                this.obj === null
            ) {
                this.$Message.error(this.$t('1043'));
                return false;
            }
            if (this.obj.edittype === 1) {
                this.title2 = this.$t('1003');
                this.optiontype = 2;
                this.editobj = {};
                this.departmodal = true;
                this.editobj.description = this.obj.description;
                this.editobj.title = this.obj.title;
                this.editobj.sectiontype = this.obj.type;
            } else if (this.obj.edittype === 2) {
                this.title3 = this.$t('1003');
                this.optiontype = 2;
                this.editobj1 = {};
                this.usergroupid = 0;
                this.groupmodal = true;
                this.departmentid = this.obj.sectionid;
                this.usergroupid = this.obj.parentid;
                this.departmentchange();
                this.editobj1.sectionid = this.obj.sectionid;
                this.editobj1.usergroupid = this.obj.parentid;
                this.editobj1.title = this.obj.title;
                this.editobj1.description = this.obj.description;
                if (this.editobj1.usergroupid === 0) {
                    this.seletshow = true;
                } else {
                    this.seletshow = false;
                }
            }
        },
        Adddepartmentdata () {
            if (
                this.editobj.description === null ||
                this.editobj.description === undefined ||
                this.editobj.description === ''
            ) {
                this.editobj.description = '';
            }
            var data = {
                title: this.editobj.title,
                type: this.editobj.sectiontype,
                description: this.editobj.description
            };
            if (
                data.title === '' ||
                data.title === undefined ||
                data.title === null
            ) {
                this.$Message.error(this.$t('100042'));
                return;
            }
            if (
                data.type === 0 ||
                data.type === '' ||
                data.type === null ||
                data.type === undefined
            ) {
                this.$Message.error(this.$t('5500102'));
                return;
            }
            axios
                .request({
                    url: '/config/ProjectSection/AddSection',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.departmodal = false;
                        this.optiontype = 0;
                        this.$Message.success(this.$t('1055'));
                        this.initdepartment();
                        this.departmentsearchchange();
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        Addusergroupdata () {
            if (
                this.editobj1.description === null ||
                this.editobj1.description === undefined ||
                this.editobj1.description === ''
            ) {
                this.editobj1.description = '';
            }
            if(this.departmentid===undefined||this.departmentid===0){
                this.$Message.error(this.$t('930016'));
                return false;
            }
            if(this.editobj1.title===undefined||this.editobj1.title===""){
                this.$Message.error(this.$t('101052'));
                return false;
            }
            var data = {
                title: this.editobj1.title,
                description: this.editobj1.description,
                parentid: this.usergroupid!=undefined?this.usergroupid.toString():"",
                sectionid: this.departmentid
            };
            
            axios
                .request({
                    url: '/config/ProjectUserGroup/AddUserGroup',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.groupmodal = false;
                        this.optiontype = 0;
                        this.$Message.success(this.$t('1055'));
                        this.departmentsearchchange();
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        editdata () {
            if (this.obj.edittype === 1) {
                if (
                    this.editobj.description === null ||
                    this.editobj.description === undefined ||
                    this.editobj.description === ''
                ) {
                    this.editobj.description = '';
                }
                let data = this.editobj;
                data.id = this.obj.id;
                data.type = this.editobj.sectiontype;
                if (
                    data.title === '' ||
                    data.title === undefined ||
                    data.title === null
                ) {
                    this.$Message.error(this.$t('9000002'));
                    return;
                }
                if (
                    data.type === 0 ||
                    data.type === '' ||
                    data.type === null ||
                    data.type === undefined
                ) {
                    this.$Message.error(this.$t('9000136'));
                    return;
                }
                axios
                    .request({
                        url: '/config/ProjectSection/UpdateSection',
                        data,
                        method: 'post'
                    })
                    .then(res => {
                        if (res.data.ret === 1) {
                            this.departmodal = false;
                            this.$Message.success(this.$t('1060'));
                            this.search(1, 10000);
                        } else {
                            this.$Message.error(this.$t(res.data.msg));
                        }
                    });
            } else if (this.obj.edittype === 2) {
                if (
                    this.editobj1.description === null ||
                    this.editobj1.description === undefined ||
                    this.editobj1.description === ''
                ) {
                    this.editobj1.description = '';
                }

                if(this.departmentid===undefined||this.departmentid===0){
                    this.$Message.error(this.$t('930016'));
                    return false;
                }
                if(this.editobj1.title===undefined||this.editobj1.title===""){
                    this.$Message.error(this.$t('101052'));
                    return false;
                }

                let data = this.editobj1;
                data.id = this.obj.id;
                data.sectionid = this.departmentid;
                data.parentid = this.usergroupid;
                axios
                    .request({
                        url: '/config/ProjectUserGroup/Update',
                        data,
                        method: 'post'
                    })
                    .then(res => {
                        if (res.data.ret === 1) {
                            this.departmodal = false;
                            this.groupmodal = false;
                            this.optiontype = 0;
                            this.$Message.success(this.$t('1060'));
                            this.search(1, 10000);
                        } else {
                            this.$Message.error(this.$t(res.data.msg));
                        }
                    });
            }
        },
        dele () {
            if (this.obj.id === undefined || this.obj === null) {
                this.$Message.error(this.$t('1017'));
                return false;
            } else {
                var url = '';
                if (this.obj.edittype === 1) {
                    url = '/config/ProjectSection/DeleteSection';
                } else if (this.obj.edittype === 2) {
                    url = '/config/ProjectUserGroup/Delete';
                }
                this.$Modal.confirm({
                    title: this.$t('1018'),
                    content: '',
                    width: '290px',
                    closable: true,
                    okText: this.$t('1004'),
                    onOk: () => {
                        axios
                            .request({
                                url: url + '?id=' + this.obj.id,
                                method: 'post'
                            })
                            .then(res => {
                                if (res.data.ret === 1) {
                                    this.initdepartment();
                                    this.departmentsearchchange();
                                    this.$Message.success(this.$t('1058'));
                                } else {
                                    this.$Message.error(this.$t(res.data.msg));
                                }
                            });
                    }
                });
            }
        },
        initdepartment () {
            axios
                .request({
                    url: '/config/ProjectUser/getUserDepartment',
                    method: 'get'
                })
                .then(res => {
                    this.department = res.data.data;
                    this.departmentlist = res.data.data;
                    // console.log(this.departmentlist);
                    if (this.department != null && this.department.length > 0) {
                        this.sectionid = this.department[0].id;
                        this.defaultdepart = this.department[0].title;
                        this.departmentsearchchange();
                    }
                });
        },
        departmentchange () {
            axios
                .request({
                    url:
                        '/config/projectuser/GetUserUserGroup?sectionid=' +
                        this.departmentid,
                    method: 'get'
                })
                .then(res => {
                    this.usergroup = res.data.data;
                });
        },
        departmentsearchchange () {
            this.search(1, 10000);
        },
        search (page, pagesize) {
            var params = {
                page: page,
                pagesize: pagesize,
                id: this.sectionid
            };
            axios
                .request({
                    url: '/config/ProjectSection/selectSectionItem',
                    params,
                    method: 'get'
                })
                .then(res => {
                    this.total = res.data.total;
                    this.mockTableData1(res.data.data);
                });
            axios
                .request({
                    url: '/config/ProjectUserGroup/SelectUserGroupItem2',
                    params,
                    method: 'get'
                })
                .then(res => {
                    this.total = res.data.total;
                    this.mockTableData2(res.data.data);
                });
            this.obj = {};
        },
        search1 () {
            var params = {
                id: this.sectionid
            };
            axios
                .request({
                    url: '/config/ProjectSection/selectSectionItem',
                    params,
                    method: 'get'
                })
                .then(res => {
                    this.total = res.data.total;
                    this.mockTableData1(res.data.data);
                });
        },
        search2 (page, pagesize) {
            var params = {
                page: page,
                pagesize: pagesize,
                id: this.sectionid
            };
            axios
                .request({
                    url: '/config/ProjectUserGroup/SelectUserGroupItem2',
                    params,
                    method: 'get'
                })
                .then(res => {
                    this.total = res.data.total;
                    this.mockTableData2(res.data.data);
                });
        },
        mockTableData1 (tablelist) {
            let data = [];
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        id: item.id,
                        title: item.title,
                        description: item.description,
                        create_time: item.create_time,
                        type: item.type.toString(),
                        typename: item.type.toString() === "1" ? this.$t('600608'): this.$t('600609'),
                        create_mid: item.create_mid,
                        role_id: item.role_id,
                        projectid: item.projectid,
                        edittype: 1
                    });
                }
            });
            this.tableData1 = data;
        },
        mockTableData2 (tablelist) {
            let data = [];
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        id: item.id,
                        sectionid: item.sectionid,
                        projectid: item.projectid,
                        title: item.title,
                        nickname: item.nickname,
                        description: item.description,
                        create_mid: item.create_mid,
                        time: item.time,
                        create_ip: item.create_ip,
                        parentid: item.parentid,
                        number: item.number,
                        status: item.status,
                        role_id: item.role_id,
                        fatherUserGroupTitle:
                            item.fatherUserGroupTitle ===
                            '<em class="text-muted">已经是父级</em>'
                                ? this.$t('101051')
                                : item.fatherUserGroupTitle,
                        sectionname: item.sectionname,
                        create_time: item.create_time,
                        edittype: 2
                    });
                }
            });
            this.tableData2 = data;
        },
        changecondition () {
            this.morecondition = !this.morecondition;
        },
        handlePageSize (value) {
            this.pagesize = value;
            this.tableData1 = this.search(1, 10000);
        },
        changePage (value) {
            this.page = value;
            this.tableData1 = this.search(1, 10000);
        },
        handleRowChange1 (currentRow, oldCurrentRow) {
            this.obj = currentRow;
            this.powerlimit = true;
            this.type = '1';
            if (this.obj.edittype === 1) {
                this.search2(1, 10000);
            } else if (this.obj.edittype === 2) {
                this.search1();
            }
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.obj = currentRow;
            this.powerlimit = false;

            if (this.obj.edittype === 1) {
                this.search2(1, 10000);
            } else if (this.obj.edittype === 2) {
                this.search1();
            }
            // alert(JSON.stringify(currentRow))
        }
    }
};
</script>
<style lang="less" scoped>

</style>
