<template>
  <div>
    <el-container>
      <div class="block-l">
        <el-card shadow="hover">
        <div class="left_list">
        <el-row>
          <span style="padding-left: 25px;" v-if="dialogfrom=='message'">应急通讯录</span>
          <span style="padding-left: 25px;" v-else>联动通讯录</span>
          <el-link v-if="dialogfrom!='index'&&dialogfrom!='message'" :underline="false" style="margin:0 20px;" type="primary" @click="addOrg()">添加组织</el-link>
          <el-link :underline="false" type="primary" @click="confirmOutput()" v-if="dialogfrom!='message'">导出</el-link>
        </el-row>

        <div>
          <el-tree
            ref="selectTree"
            :data="orgData"
            accordion
            node-key="id"
            @node-click="setOrgId"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>
                <i v-if="data.level == 0" class="el-icon-s-home" />
                <i v-else-if="data.level == 1" class="el-icon-menu" />
                <i v-else class="el-icon-link" />
                {{ node.label }}
              </span>
              &nbsp; &nbsp;
              <div v-if="data.show == true&&dialogfrom!='index'&&dialogfrom!='message'" style="display: inline-block;float: right;position: absolute;right: 2%;" width="100" >
                <el-link :underline="false" size="mini" style="float: right" type="danger" @click="removeOrg(data)">&nbsp;删除&nbsp;</el-link>
              &nbsp; &nbsp;
                <el-link :underline="false" size="mini" style="float: right" type="primary" @click="editOrg(data)">&nbsp;修改&nbsp;</el-link>
              </div>

              <span v-if="data.level == 0">
                <el-link class="space" type="primary" @click="() => unFoldAll()">展开</el-link>
                <el-link class="space" type="primary" @click="() => collapseAll()">折叠</el-link>
              </span>
            </span>
          </el-tree>

        </div>
        </div>
        </el-card>
      </div>

      <el-container>
        <el-header style="height: 85px">
          <div style="width: 100%;text-align: center;margin-top: 20px">
            <span style="font-size: 25px;">
              &nbsp;{{ orgName }}
            </span>
          </div>
          <el-button v-if="dialogfrom!='index'&&dialogfrom!='message'" class="ch-button" size="small" style="float: right; margin-top: 4px" @click="handleAdd()">
            <i class="el-icon-menu" />&nbsp;新增
          </el-button>
        </el-header>
        <el-main>
          <el-row class="handle-box">
            <el-col :span="24" style="position: relative;">
              <el-checkbox ref="checkAll" v-model="pageChecked" @change="checkedChange" :indeterminate="isIndeterminate" class="selectAll" v-if="AllData.length>0&&dialogfrom=='message'"></el-checkbox>
              <el-table
                v-loading="loading"
                :data="AllData" :max-height="tableMax"
                row-class-name="g_table_row"
                stripe class="schemeIn"
                ref="mListTable"
                @select="handleSelectionChange" @select-all="selectAll"
              >
                <el-table-column label="序号" type="index" width="60" />
                <el-table-column v-if="false" prop="id" />
                <el-table-column v-if="false" prop="orgId" />
                <el-table-column label="姓名" prop="name" />
                <el-table-column label="部门" prop="department" />
                <el-table-column label="岗位" prop="post" />
                <el-table-column label="联系方式" prop="phone" />
                <el-table-column fixed="left" type="selection" width="55"  v-if="dialogfrom=='message'"/>
                <el-table-column v-if="dialogfrom!='index'&&dialogfrom!='message'" align="center" header-align="center" label="操作" width="150">
                  <template scope="scope">
                    <el-link :underline="false" size="mini" type="primary" @click="handleEdit(scope.row)"> 修改&nbsp; </el-link>
                    <el-link :underline="false" size="mini" type="primary" @click="handleDel(scope.row)"> 删除&nbsp; </el-link>
                  </template>
                </el-table-column>
              </el-table>
              <div class="table-page">
                <el-pagination
                  :current-page.sync="currentPage"
                  :page-size="pageSize"
                  :total="allpage"
                  background
                  layout="total, prev, pager, next"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-col>
          </el-row>

        </el-main>
        <el-footer />
      </el-container>
    </el-container>
    <!--组织-->
    <el-dialog v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :title="dialogTitleOrg"
      :visible.sync="dialogVisibleOrg"
      style="text-align: left"
      top="50px" class="statistic_base"
      width="50%"
    >
      <el-form ref="formOrg" :model="formOrg" :rules="rulesOrg" style="width: 100%; padding: 5px">
        <el-row>
          <el-col style="padding-bottom: 10px">
            <!-- <span class="card_title">基本信息</span> -->
            <el-card shadow="always" style="padding: 15px 5px 5px 15px">

              <el-row>
                <el-col :span="3" class="col-txt">
                  <span class="span_red">*</span>
                  <span>组织名称</span>
                </el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item prop="name">
                    <el-input v-model="formOrg.name" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisibleOrg = false">取 消</el-button>
        <el-button type="primary" @click="confirmSubmitOrg()">确 定</el-button>
      </div>
    </el-dialog>

    <!--人员-->
    <el-dialog v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      style="text-align: left"
      top="50px" class="statistic_base"
      width="75%"
      @open="dlgOpen"
    >
      <el-form ref="form" :model="form" :rules="rules" style="width: 100%; padding: 5px">
        <el-row>
          <el-col style="padding-bottom: 10px">
            <!-- <span class="card_title">基本信息</span> -->
            <el-card shadow="always" style="padding: 15px 5px 5px 15px">
              <el-row>
                <el-col :span="3" class="col-txt">
                  <span>组织名称</span>
                </el-col>
                <el-col :span="10" class="col-input">
                  {{ form.orgName }}
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="3" class="col-txt">
                  <span class="span_red">*</span>
                  <span>姓名</span>
                </el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item prop="name">
                    <el-input v-model="form.name" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="3" class="col-txt">
                  <span>部门</span>
                </el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item prop="department">
                    <el-input v-model="form.department" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="3" class="col-txt">
                  <span>岗位</span>
                </el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item prop="post">
                    <el-input v-model="form.post" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="3" class="col-txt">
                  <span class="span_red">*</span>
                  <span>联系方式</span>
                </el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item prop="phone">
                    <el-input v-model="form.phone" />
                  </el-form-item>
                </el-col>
              </el-row>

            </el-card>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确 定</el-button>
      </div>

    </el-dialog>

  </div>
</template>
<script>
import Base from '@/views/base/base'
import BaseData from '@/views/base/baseData'
import '../../assets/drag'

export default {
    name: 'Personnel',
    components: {},
    mixins: [Base, BaseData],
    props: ['dialogfrom'],
    data() {
        return {
            // 列表相关
            search: {},
            AllData: [],
            orgData: [],
            loading: false,
            loadingOrg: false,
            // 弹框相关
            dialogVisible: false,
            dialogTitle: '',
            dialogVisibleOrg: false,
            dialogTitleOrg: '',
            isAdd: true,
            isAddOrg: true,
            form: this.initForm(),
            formOrg: this.initFormOrg(),
            rules: {
                name: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
                phone: [{ required: true, message: '请填写联系方式', trigger: 'blur' },
                    {
                        validator: function(rule, value, callback) {
                            if (/^(13[0-9]|14[0-9]|15[0-9]|16[6]|18[0-9]|19[6,9]|17[0-9])\d{8}$/i.test(value) === false) {
                                callback(new Error('请输入正确的手机号'))
                            } else {
                                // 校验通过
                                callback()
                            }
                        },
                        trigger: 'blur'
                    }]
            },
            rulesOrg: {
                name: [{ required: true, message: '请填写组织名称', trigger: 'blur' }]
            },
            orgId: '',
            orgName: '',
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            saveCheckList: [],
            pageChecked:false,
            isIndeterminate:false,
        }
    },
    watch:{
      saveCheckList(val){
        this.$emit('getUser',val)
      }
    },
    mounted() {
        console.log(this.dialogfrom)
        this.getOrgDate()
    },
    methods: {
        handleSelectionChange(selection,row){
          console.log("selection", selection);
	      // 从保存项saveCheckList里面寻找,如果找到了row则删除，如果没找到则添加
	      let fitemIndex = this.saveCheckList.findIndex((item) => {
	        return item.id == row.id;
	      });
	      if (fitemIndex < 0) {
	        this.saveCheckList.push(row);
	      } else {
	        this.saveCheckList.splice(fitemIndex, 1);
	      }
	      console.log("this.saveCheckList", this.saveCheckList);
        },
        selectAll(val){
        console.log("selectAll", val);
	      // 如果为空，则为清除选项状态，此时将table中的所有内容都从saveCheckList移除
	      if (val && val.length == 0) {
	        this.AllData.forEach((row) => {
	          // 从保存项saveCheckList里面寻找,如果找到了row则删除，如果没找到则添加
	          let fitemIndex = this.saveCheckList.findIndex((item) => {
	            return item.id == row.id;
	          });
	          // 找到了就删除掉
	          if (fitemIndex >= 0) {
	            this.saveCheckList.splice(fitemIndex, 1);
	          }
	        });
	      } else if (val && val.length != 0 && this.saveCheckList.length != 0) {
	        // 如果不为空,且this.saveCheckList也不为空则从val里面找
	        val.forEach((row) => {
	          // 从保存项saveCheckList里面寻找,如果找到了row则删除，如果没找到则添加
	          let fitemIndex = this.saveCheckList.findIndex((item) => {
	            return item.id == row.id;
	          });
	          // 没找到就push进去
	          if (fitemIndex < 0) {
	            this.saveCheckList.push(row);
	          }
	        });
	      } else if (val && val.length != 0 && this.saveCheckList.length == 0) {
	        val.forEach((row) => {
	          this.saveCheckList.push(row);
	        });
	      }
      },
      checkedChange(val){
        // 全选操作
	      if (this.pageChecked) {
	        // 调用接口查询所有的列表数据并且保存起来
          this.baseRequest('listAll', this.search).then(res=>{
            // console.log(res)
            this.saveCheckList=res.data
            this.$nextTick(() => {
	              this.$refs["mListTable"].clearSelection();
	              this.$refs["mListTable"].toggleAllSelection();
	            });
             console.log("this.saveCheckList", this.saveCheckList);
          })
	      } else {
	        // 取消全选，当前所有选择项清空
	        this.saveCheckList = [];
	        // 将当前的页的所有内容取消勾选状态
	        this.$nextTick(() => {
	          this.$refs["mListTable"].clearSelection();
	        });
          console.log("this.saveCheckList", this.saveCheckList);
	      }
        
    },
    checkPageStatus(tableList) {
	      tableList.forEach((row) => {
	        let findex = this.saveCheckList.findIndex((item) => {
	          return item.id == row.id;
	        });
	        // console.log("checkPageStatus", findex);
	        if (findex >= 0) {
	          this.$nextTick(() => {
	            this.$refs["mListTable"].toggleRowSelection(row);
	          });
	        }
	      });
	    },
        getData: function() {
            const _this = this
            _this.loading = true
            _this.AllData = []
            this.search.pageNum = this.currentPage
            this.search.pageSize = this.pageSize
            this.baseRequest('list', this.search)
                .then((res) => {
                    if (res.data.rows) {
                        res.data.rows.forEach(function(item) {
                            const json = _this.getItemJson(item)
                            _this.AllData.push(json)
                        })
                        _this.allpage = res.data.total
                        this.checkPageStatus(this.AllData);
                    }
                    _this.loading = false
                })
                .catch(() => {
                })
        },
        
        getOrgDate: function() {
            const _this = this
            _this.loadingOrg = true
            _this.orgData = []

            this.baseRequest('listAllOrg', this.search)
                .then((res) => {
                    if (res.data) {
                        res.data.forEach(function(item) {
                            _this.orgData.push(
                                {
                                    orgId: item.id,
                                    name: item.name,
                                    label: item.name,
                                    show: false

                                }
                            )
                        })
                    }
                    _this.loadingOrg = false
                })
                .catch(() => {
                })
        },
        handleSearch: function() {
            this.getData()
        },
        handleReset: function() {
            for (const i in this.search) {
                if (i !== 'pageNum' && i !== 'pageSize') {
                    this.search[i] = ''
                }
            }
            this.handleSearch()
        },
        initOutData: function() {
            const _this = this
            this.OutData = []
            const title = [
                ' 序号', ' 组织名称', ' 姓名', ' 部门', ' 岗位', ' 联系方式'
            ]
            this.OutData.push(title)

            return this.baseRequest('getAllPersonnel', {})
                .then((res) => {
                    if (res.data) {
                        res.data.forEach(function(item, index) {
                            const jsonArray = []
                            jsonArray.push(index + 1)
                            jsonArray.push(item.orgname)
                            jsonArray.push(item.name)
                            jsonArray.push(item.department)
                            jsonArray.push(item.post)
                            jsonArray.push(item.phone)
                            _this.OutData.push(jsonArray)
                        })
                    }
                })
                .catch(() => {
                })
        },
        getItemJson: function(item) {
            return item
        },
        initForm: function() {
            return {
                id: '',
                orgId: '',
                orgName: '',
                name: '',
                department: '',
                post: '',
                phone: ''
            }
        },
        initFormOrg: function() {
            return {
                name: ''
            }
        },
        confirmOutput() {
            this.initOutData().then(() => {
                const OutSize = [
                    { wch: 15 },
                    { wch: 15 },
                    { wch: 15 },
                    { wch: 15 },
                    { wch: 15 },
                    { wch: 15 },
                    { wch: 15 }
                ]
                const fileName = '联动通讯录' + new Date().Format('yyyyMMddhhmm')
                this.$outputXlsxFile(this.OutData, OutSize, fileName)
            })
        },
        dlgOpen: function() {
            const _this = this
            if (_this.form.id !== '') {
                const postData = {
                    id: _this.form.id
                }
                this.baseRequest('getById', postData)
                    .then((res) => {
                        if (res.data) {
                            _this.form = Object.assign({}, _this.form, res.data)
                        }
                    })
                    .catch(() => {
                    })
            }
        },
        /* 编辑*/
        handleEdit: function(val) {
            this.isAdd = false
            this.form.id = val.id
            this.dialogVisible = true
            this.dialogTitle = '修改人员'
        },
        /* 新增*/
        handleAdd: function() {
            if (this.orgName === undefined || this.orgName === null || this.orgName === '') {
                this.$message.error('请选择组织')
                return false
            }
            this.form = this.initForm()
            this.form.orgId = this.orgId
            this.form.orgName = this.orgName
            this.isAdd = true
            this.content = ''
            this.dialogVisible = true
            this.dialogTitle = '新增人员'
        },
        confirmSubmit: function() {
            const _this = this
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let soaUrl = 'edit'
                    const extraData = {}
                    const postData = Object.assign({}, _this.form, extraData)

                    if (this.isAdd) {
                        soaUrl = 'add'
                    }
                    this.opRecord(postData, soaUrl)
                } else {
                    // //console.log('error submit!!')
                    return false
                }
            })
        },
        baseRequest(opUrl, postData) {
            // return this.$channel.globeRequest(
            //     'ArchivesPersonnelController',
            //     opUrl,
            //     postData,
            //     'project'
            // )
            return this.$channel.baseRequest('ArchivesPersonnelController', opUrl, postData, 'User')
        },
        // 删除
        handleDel(val) {
            const message = '确认要删除该人员？'
            this.confirm(message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.baseRequest('remove/' + val.id, '')
                    .then((res) => {
                        this.getData()
                    })
                    .catch(() => {
                    })
            })
        },
        addOrg() {
            this.formOrg = this.initForm()
            this.dialogTitleOrg = '新增组织'
            this.isAddOrg = true
            this.dialogVisibleOrg = true
        },
        editOrg(data) {
            this.formOrg.id = data.orgId
            this.formOrg.name = data.name
            this.dialogTitleOrg = '修改组织'
            this.isAddOrg = false
            this.dialogVisibleOrg = true
        },
        removeOrg(data) {
            const message = '确认要删除该组织？'
            this.confirm(message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.baseRequest('removeOrg/' + data.orgId, '')
                    .then((res) => {
                        this.getOrgDate()
                        if (data.orgId === this.orgId) {
                            this.OrgName = ''
                            this.AllData = []
                        }
                    })
                    .catch(() => {
                    })
            })
        },
        setOrgId(node) {
            this.search = {
                orgId: node.orgId
            }
            this.orgName = node.name
            this.orgId = node.orgId
            node.show = true
            this.orgData.forEach((data) => {
                if (data.orgId !== node.orgId) {
                    data.show = false
                }
            })
            this.getData()
        },
        confirmSubmitOrg() {
            const _this = this
            this.$refs.formOrg.validate((valid) => {
                if (valid) {
                    let soaUrl = 'editOrg'
                    const postData = Object.assign({}, _this.formOrg)
                    if (this.isAddOrg) {
                        soaUrl = 'addOrg'
                    }
                    this.opRecord(postData, soaUrl, false).then(() => {
                        this.getOrgDate()
                        this.dialogVisibleOrg = false
                    })
                } else {
                    // //console.log('error submit!!')
                    return false
                }
            })
        }

    }
}
</script>
<style lang="scss" scoped>
  .selectAll{
    position: absolute;
    z-index: 99;
    top: 17px;
    left: 14px;
  }
</style>
<style scoped>
.block-l{
  width: 400px;
}
span.span_red {
  color: red;
}
.left_list {
	height: calc(100vh - 225px);
	width: 100%;
	background: white;
  overflow: auto;
}
.ch-input .el-input__inner {
  border-color: #32323a;
}

.ch-input-size {
  width: 150px;
}

.ch-button {
  border-color: #32323a;
  background-color: #32323a;
  color: #fff;
}

.ch-button-warning {
  margin-left: 10px;
  border-color: #e6a23c;
  background-color: #e6a23c;
  color: #fff;
}

.ch-button-export {
  margin-left: 10px;
  border-color: #98cc1f;
  background-color: #98cc1f;
  color: #fff;
}
/deep/ .el-tree{
  padding-top: 20px;
}

/deep/ .el-tree-node{
  height: 30px;
}

/deep/ .el-dialog__header {
  padding: 20px 30px 0px 30px;
  /* text-align: left; */
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
