<template>
  <div class="div_main">
      <div class="div_search">
        <el-form :model="dataForm" ref="queryForm" :inline="true" @keyup.enter.native="getDataList()">
            <el-form-item label="所属组织" prop="deptName">
                <el-cascader
                        placeholder="请选择所属组织"
                        :options="agencytree"
                        v-model="dataForm.agencyId"
                        :props="{ expandTrigger: 'hover', label: 'orgName', value: 'orgId', children: 'subOrgList' }"
                        clearable/>
            </el-form-item>
            <el-form-item label="部门名称" prop="deptName">
                <el-input v-model="dataForm.axisName" placeholder="请输入部门名称" clearable size="small" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getDataList()">搜索</el-button>
                <el-button style="margin-left:10px"
                           class="diy-button--reset"
                           size="small">重置</el-button>
            </el-form-item>
        </el-form>
      </div>
      <div class="div_table">
        <div class="div_btn">
            <el-button style=""
                    class="diy-button--add"
                    size="small"
                    @click="handleAdd()">{{ $t('add') }}</el-button>
        </div>
        <!-- 列表表格 -->
        <el-table
            class="table"
            v-loading="dataListLoading"
            :data="dataList"
            :default-expand-all="true"
            row-key="id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            :header-cell-style="{background:'#2195FE',color:'#FFFFFF'}">
            <el-table-column prop="name" label="动力主轴"></el-table-column>
            <el-table-column prop="categoryCode" :formatter="categoryCodeFormatter" label="类别" ></el-table-column>
            <el-table-column prop="leaderName" label="负责人" width="100"></el-table-column>
            <el-table-column prop="leaderMobile" label="联系方式" width="110"></el-table-column>
            <el-table-column prop="createdTime" label="创建时间" width="160"></el-table-column>
            <el-table-column label="操作" align="center" width="300">
                <template slot-scope="scope">
                    <!-- <el-button size="mini" type="danger" icon="el-icon-edit" @click="addOrUpdateHandle(scope.row.id)">修改</el-button> -->
                    <el-button size="mini" type="danger" icon="el-icon-edit" @click="handleEdit(scope.row.id)">修改</el-button>
                    <el-button size="mini" type="warning" icon="el-icon-edit" @click="deleteHandle_my(scope.row.id)">删除</el-button>
                    <el-button size="mini" type="primary" icon="el-icon-user" @click="add_edit_Leader(scope.row.id, scope.row.leaderId, scope.row.structLevel)">负责人</el-button>
                </template>
            </el-table-column>
        </el-table>
      </div>
        <!-- 弹窗, 新增 / 修改 -->
        <el-dialog :visible.sync="formShow"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :title="formTitle"
                width="850px"
                top="5vh"
                class="dialog-h"
                @closed="diaClose">
        <poweraxis-form ref="ref_form"
                        @dialogCancle="addFormCancle"
                        @dialogOk="addFormOk"></poweraxis-form>
        </el-dialog>
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
        <el-dialog  :visible.sync="leaderVisible"
                    :close-on-click-modal="false"
                    :close-on-press-escape="false"
                    title="负责人"
                    width="850px"
                    top="5vh"
                    class="dialog-h"
                    @closed="leaderDiaClose">
            <add-leader ref="ref_leader"
                        @leaderCancle="addleaderCancle"
                        @leaderOk="addleaderOk"></add-leader>
        </el-dialog>
    </div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import { handleTree } from "@/utils/treeSelect";
import Treeselect from "@riophae/vue-treeselect";
import AddOrUpdate from './poweraxis-add-or-update'
import poweraxisForm from './poweraxisForm'
import mixinViewModule from '@/mixins/view-module'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import AddLeader from './poweraxis_add_leader.vue';
export default {
    mixins: [mixinViewModule],
    components: { 
      Treeselect,
      AddOrUpdate,
      AddLeader,
      poweraxisForm
    },
    data(){
        return{
            mixinViewModuleOptions: {
                createdIsNeed: false,
                activatedIsNeed: false, // 此⻚⾯是否在激活（进⼊）时，调⽤查询数据列表接⼝？
                getDataListIsPage: false, // 数据列表接⼝，是否需要分⻚？
            },
            dataForm:{ // 查询参数
             agencyId: '', // 组织ID
             axisName: '', // 动力主轴节点名称
             leaderName: '' // 动力主轴节点负责人
            },
            agencytree: [], // 所属组织
            dataList:[], // 列表
            structCategoryArr: [], // 查询动力主轴标签类别
            leaderCategoryArr: [], // 查询动力主轴负责人标签类别
            leaderVisible: false,
            axisStructId: '', // 动力主轴id 添加负责人的时候用
            structLevel: null, // 动力主轴节点级别 添加负责人的时候用
            leaderId: '',
            dataListLoading: false,
            //form相关
            formShow: false,
            formTitle: '新增',
        }
    },
    async created(){
        this.dataListLoading = true
        await this.getDataList()
        await this.getAgencyTree()
        await this.getTagCategoryArr()
        this.dataListLoading = false
    },
    mounted(){
        this.customerId = localStorage.getItem('customerId')
        this.agencyId = localStorage.getItem('agencyId')
    },
    methods:{
        handleEdit (id) {
            this.formTitle = '修改'
            this.formShow = true
            this.$nextTick(() => {
                this.$refs.ref_form.initForm('edit', id)
            })
        },
        handleAdd () {
            this.formTitle = '新增'
            this.formShow = true
            this.$nextTick(() => {
                this.$refs.ref_form.initForm('add')
            })
        },
        addFormCancle () {
            this.formShow = false
        },
        addFormOk () {
            this.formShow = false
            this.getDataList()
        },
        diaClose () {
        // this.$refs.ref_form.resetData()
        this.formShow = false
        },
        // 获取组织列表
        async getAgencyTree(){
            const url = '/data/aggregator/org/agencytree'

            let params = {
                agencyId:  localStorage.getItem('agencyId'),
                client:'gov'
            }
            const { data, code, msg } = await requestPost(url,params)
            if (code === 0) {
                let _data
                if (data) {
                    _data = this.removeByOrgType(data, 'agency')
                    if (_data) {
                        this.agencytree = this.removeEmptySubOrgList(_data)
                    }
                }
            } else {
                this.$message.error(msg)
            }
        },
        removeByOrgType (orgArray, orgType) {
            if (orgArray && orgArray.length > 0) {
                for (let p = orgArray.length - 1; p >= 0; p--) {
                    let orgInfo = orgArray[p]
                    if (orgInfo) {
                        if (orgInfo.orgType !== orgType) {
                            orgArray.splice(p, 1)
                        } else {
                            this.removeByOrgType(orgInfo.subOrgList, orgType)
                        }
                    }
                }
            }
            return orgArray
        },
        removeEmptySubOrgList (orgArray) {
            orgArray.forEach((orgInfo) => {
                if (orgInfo && orgInfo.subOrgList) {
                    if (orgInfo.subOrgList.length === 0) {
                        orgInfo.subOrgList = undefined
                    } else {
                        this.removeEmptySubOrgList(orgInfo.subOrgList)
                    }
                }
            })
            return orgArray;
        },
        // 初始化动力主轴组织树
        async getDataList () {
            const url = '/pli/power/axisStruct/list4Tree'

            const { data, code, msg } = await requestPost(url, this.queryParams)

            if (code === 0) {
                this.dataList = handleTree(data, 'id', 'pid');
            } else {
                this.$message.error(msg)
                
            }
        },
        // 获取动力主轴标签
        async getTagCategoryArr(){
            const url = '/pli/power/axisTag/listSimpleAll'

            let params = {}

            const { data, code, msg } = await requestPost(url, params)

            if (code === 0) {
                data.forEach((item) => {
                    if (item.tagCategory === 'struct') {
                        this.structCategoryArr = item.tagList
                    }
                    if (item.tagCategory === 'leader') {
                        this.leaderCategoryArr = item.tagList
                    } 
                })
            } else {
                this.$message.error(msg)
            }
        },
        categoryCodeFormatter (row) {
            let ca = ''
            this.structCategoryArr.forEach((tagCategory) => {
                if (tagCategory.categoryCode === row.categoryCode) {
                    ca = tagCategory.categoryName
                }
            })
            return ca
        },
        // 删除方法
        deleteHandle_my(id) {
            this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
                confirmButtonText: this.$t('confirm'),
                cancelButtonText: this.$t('cancel'),
                type: 'warning'
            }).then(() => {
                this.submitDelete(id)
            }).catch(() => {})
        },
        async submitDelete(id){
            const url = '/pli/power/axisStruct/deleteById/'+ id
            const { code, msg } = await requestPost(url)
            if (code === 0) {
                this.$message.success("删除成功")
                this.getDataList()
            } else {
                this.$message.error(msg)
            }
        },
        // 添加负责人
        add_edit_Leader(axisStructId, leaderId, structLevel) {
            this.leaderVisible = true
            let agencyObj = {
                axisStructId: axisStructId,
                structLevel: structLevel,
                leaderId: leaderId,
            }
            this.$nextTick(() => {
                this.$refs.ref_leader.initForm(agencyObj)
            })
        },
        addleaderOk() {
            this.leaderVisible = false
            this.axisStructId = ''
            this.getDataList()
        },
        addleaderCancle() {
           this.leaderVisible = false
        },
        leaderDiaClose() {
           this.leaderVisible = false
        },
        // 取消按钮 
        handleCancle () {
            console.log('取消：：：：')
        // this.resetData()
        // this.$emit('dialogCancle')
        }
    }
}
</script>

<style lang="scss" scoped >
.div_main {
  width: 100%;
}

.div_search {
  background: #ffffff;
  border-radius: 4px;
  padding: 30px 20px 5px;
  box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
}

.item_width_1 {
  width: 260px;
}
.item_width_2 {
  width: 495px;
}

.div_table {
  background: #ffffff;
  box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin-top: 15px;
  padding: 23px 30px 10px;

  .table {
    margin-top: 20px;
  }
}

.div_btn {
}

.el-row {
  /* margin-bottom: 20px; */
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
  margin-right: 50px;
}
</style>