<template>
  <div class="app-container">
    <div class="tree-container">
      <div style="padding: 10px; display: flex;">
        <el-button icon="el-icon-refresh-right" size="small" @click="refreshDepartment()" style="padding: 9px 10px; margin-right: 6px"></el-button>
        <el-input
          placeholder="输入关键字进行过滤"
          size="small"
          clearable
          v-model="filterText">
        </el-input>
      </div>
      <el-tree
        :data="departmentList"
        :props="defaultProps"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
        node-key="id"
        ref="tree">
        <div class="custom-tree-node" slot-scope="{ node, data }">
          <i :class="data.children && data.children.length > 0 ? 'el-icon-folder-opened':'el-icon-document-remove'"></i><span>{{ node.label }}</span>
        </div>
      </el-tree>
    </div>
    <div class="mymain-container">
      <div class="screen-container">
        <!-- <div class="top clearfix">
          <div class="title fl">条件筛选</div>
        </div> -->
        <el-form ref="screenForm" :model="screenForm" label-width="70px" size="small" label-position="left">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="12">
              <el-form-item label="成员名称" prop="name">
                <el-input v-model="screenForm.name" placeholder="请输入成员名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="12" class="tr">
              <el-form-item label="">
                <el-button size="small" @click="resetScreenForm">清空</el-button>
                <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="btn-group clearfix" style="margin-top: 20px">
        <div class="fl">
          <el-button size="small" type="primary" @click="openDepartmentForm('add')">添加部门</el-button>
          <el-button size="small" type="primary" @click="openDepartmentForm('edit')">编辑部门</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button size="small" type="primary" @click="openMemberForm('add')">添加成员</el-button>
           
          <el-button size="small" type="danger" @click="batchDeleteMember()">删除成员</el-button>

            <el-button size="small" type="danger" @click="delHandleDownload">下载导入删除模板</el-button>
          <el-upload
            class="import-btn2"
            style="display: inline-block; margin-left: 10px"
            :action="baseURL + 'student/import'"
            :http-request="handleImport2"
            :file-list="importFileList2"
          >
            <el-button size="small" type="danger" :loading="importLoading2">{{ importLoading2 ? '导入中...' : '导入删除成员' }}</el-button>
          </el-upload>
        </div>
        <div class="fr">
          <el-upload
            class="import-btn"
            style="height: 0; width: 0; overflow: hidden;"
            :action="baseURL + 'student/import'"
            :http-request="handleImport"
            :file-list="importFileList"
          >
            <el-button size="small" type="primary" :loading="importLoading">{{ importLoading ? '导入中...' : '导入' }}</el-button>
          </el-upload>

          <el-button size="small" type="primary" @click="handleExport">导出</el-button>

          <el-button size="small" type="primary" :loading="importLoading" @click="clickImport">{{ importLoading ? '导入中...' : '导入' }}</el-button>
          
          <el-button size="small" @click="handleDownload">下载导入模板</el-button>
        </div>
      </div>

      <div class="table">
        <el-table v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe @selection-change="handleTableSelection">
          <el-table-column align="center" type="selection" width="55" fixed></el-table-column>
          <el-table-column align="center" label="操作" min-width="110" fixed>
            <template slot-scope="scope">
              <el-button type="text" @click="openMemberForm('edit', scope.row.id)">编辑</el-button>
              <el-popconfirm style="margin-left: 10px;" title="确定删除吗？" @onConfirm="deleteMember(scope.row.id)">
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column align="center" label="姓名" prop="name" min-width="100" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="性别" prop="gender" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.gender == 1">男</span>
              <span v-else-if="scope.row.gender == 2">女</span>
              <span v-else>未知</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="账号" prop="wechatUserId" min-width="140" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="部门" prop="departmentName" min-width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.departmentName }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="职务" prop="position" min-width="140" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="手机号码" prop="mobile" min-width="140"></el-table-column>
          <el-table-column align="center" label="邮箱" prop="email" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" min-width="160"></el-table-column>
        </el-table>
      </div>
      
      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal">
          </el-pagination>
        </div>
      </div>
    </div>
    
    <!-- 添加编辑部门 -->
    <el-dialog :title="departmentFormType == 'add' ? '添加部门':'编辑部门'" :visible.sync="departmentFormVisible" :show-close="false" width="40%" :close-on-click-modal="false">
      <el-form ref="departmentForm" :model="departmentForm" :rules="departmentFormRules" label-position="right" label-width="110px">
        <el-form-item label="部门名称" prop="name">
          <el-input placeholder="请输入部门名称" v-model="departmentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="code">
          <el-input placeholder="请输入部门编号" v-model="departmentForm.code"></el-input>
        </el-form-item>
        <el-form-item label="选择区域" prop="area">
          <el-select v-model="departmentForm.area" placeholder="请选择区域" style="width: 100%">
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.zoneName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金蝶业务员编号" prop="jindSaleId">
          <el-input placeholder="请输入金蝶业务员编号" v-model="departmentForm.jindSaleId"></el-input>
        </el-form-item>
        <el-form-item label="金蝶业务员名称" prop="jindSaleName">
          <el-input placeholder="请输入金蝶业务员名称" v-model="departmentForm.jindSaleName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDepartmentForm">取 消</el-button>
        <el-button type="primary" @click="submitDepartmentForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加编辑成员 -->
    <el-dialog :title="memberFormType == 'add' ? '添加成员':'编辑成员'" :visible.sync="memberFormVisible" :show-close="false" width="60%" :close-on-click-modal="false">
      <el-form ref="memberForm" :model="memberForm" :rules="memberFormRules" label-position="left" label-width="50px" size="small">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="姓名" prop="name">
              <el-input placeholder="请输入姓名" v-model="memberForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12" style="height: 51px;">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="memberForm.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="账号" prop="account">
              <el-input placeholder="请输入账号" v-model="memberForm.account" :disabled="memberFormType === 'edit'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="部门" prop="department">
              <el-input placeholder="请输入部门" v-model="memberForm.department" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="职务" prop="post">
              <el-input placeholder="请输入职务" v-model="memberForm.post"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="手机" prop="phone">
              <el-input placeholder="请输入手机" v-model="memberForm.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="邮箱" prop="email">
              <el-input placeholder="请输入邮箱" v-model="memberForm.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelMemberForm">取 消</el-button>
        <el-button type="primary" @click="submitMemberForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { 
  getDepartmentList, addDepartment, editDepartment, deleteDepartment, getAreaList,
  getMemberList, addMember, editMember, deleteMember, getMemberDetail
  } from '@/api/wxcustomer'
import { downloadFiles, handleImport } from '@/utils/util'

export default {
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      dataList: null, // 列表数据
      moduleList: null, // 模块列表
      listLoading: true, // 列表加载loading
      screenForm: { // 筛选表单数据
        name: '', // 名称
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数

      departmentFormType: 'add',
      departmentFormVisible: false,
      departmentForm: {
        name: '',
        code: '',
        area: '',
        jindSaleId: '',
        jindSaleName: '',
      },
      departmentFormRules: {
        name: [
          { required: true, message: '请填写部门名称', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请填写部门编号', trigger: 'blur' }
        ]
      },
      selectDepartment: null, // 选中的部门

      memberFormType: 'add',
      memberFormVisible: false,
      memberForm: {
        name: '',
        sex: 1,
        account: '',
        department: '',
        departmentId: '',
        post: '',
        phone: '',
        email: '',
      },
      memberFormRules: {
        name: [
          { required: true, message: '请填写姓名', trigger: 'blur' },
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        account: [
          { required: true, validator: function(rule, value, callback) {
            if (value === '') {
              callback(new Error('请填写账号'));
            } else if (value.length > 0 && value.match(/[\x01-\xFF]*/) == false) {
              callback(new Error('账号不能填写中文'));
            }else {
              callback();
            }
          }, trigger: 'blur' },
        ],
        department: [
          { required: true, message: '请填写部门', trigger: 'blur' },
        ],
        post: [
          { required: true, message: '请填写职务', trigger: 'blur' },
        ],
        phone: [
          { required: true, validator: function(rule, value, callback) {
            if (value === '') {
              callback(new Error('请填写手机号'));
            } else if (value.length > 0 && /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value) == false) {
              callback(new Error('请填写正确的手机号'));
            }else {
              callback();
            }
          }, trigger: 'blur' },
        ],
        email: [
          { validator: function(rule, value, callback) {
            if (value && value.length > 0 && /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value) == false) {
              callback(new Error('请填写正确的邮箱'));
            }else {
              callback();
            }
          }, trigger: 'blur' },
        ],
      },
      editMemberId: null, 

      filterText: '',
      departmentList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },

      areaList: [],
      tableSelection: [],

      importLoading: false, // 导入加载loading
      importFileList: [], // 导入列表

      importLoading2: false, // 导入加载loading
      importFileList2: [], // 导入列表
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getTree();
    this.getList();
    this.getAreaList();
  },
  methods: {
    // 获取部门列表
    getTree() {
      getDepartmentList().then(res => {
        this.departmentList = res.data;
      })
    },

    // 获取成员列表
    getList() {
      this.listLoading = true;

      let params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        adminWebsitId: this.selectDepartment ? this.selectDepartment.id : '',
        websitId: this.selectDepartment ? this.selectDepartment.websitId : '',
        keyword: this.screenForm.name
      };

      getMemberList(params).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })
    },

    // 获取区域列表
    getAreaList() {
      getAreaList().then(res => {
        this.areaList = res.data;
      })
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },

    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1;
      this.getList();
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields();
      this.currentPage = 1;
      this.getList();
    },

    // 筛选部门
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 选择部门
    handleNodeClick(data) {
      console.log(data);
      if(this.selectDepartment && data.websitId === this.selectDepartment.websitId) {
        this.$refs.tree.setCurrentKey(null);
        this.selectDepartment = null;
      }else {
        this.selectDepartment = data;
      }
      this.getList();
    },

    // 刷新部门
    refreshDepartment() {
      this.$refs.tree.setCurrentKey(null);
      this.selectDepartment = null;
      this.getTree();
      this.getList();
    },

    // 打开 新增编辑 部门表单
    openDepartmentForm(type) {
      this.departmentFormType = type;
      if(!this.selectDepartment) {
        return this.$errorMsg('请选择部门');
      }
      if(type == 'edit') {
        this.departmentForm = {
          name: this.selectDepartment.name,
          code: this.selectDepartment.websitNumber,
          area: this.selectDepartment.zoneId,
          jindSaleId: this.selectDepartment.jindSaleId,
          jindSaleName: this.selectDepartment.jindSaleName,
        }
      }
      this.departmentFormVisible = true;
    },

    // 取消 新增编辑 部门表单
    cancelDepartmentForm(){
      this.departmentFormVisible = false;
      this.$refs.departmentForm.resetFields();
      this.departmentForm = {
        name: '',
        code: '',
        area: '',
        jindSaleId: '',
        jindSaleName: '',
      }
    },

    // 提交 部门表单
    submitDepartmentForm() {
      this.$refs.departmentForm.validate((valid) => {
        if (valid) {
          let params = {
            name: this.departmentForm.name,
            websitNumber: this.departmentForm.code,
            jindSaleId: this.departmentForm.jindSaleId,
            jindSaleName: this.departmentForm.jindSaleName,
          }
          if(this.departmentForm.area) {
            params.zoneId = this.departmentForm.area;
            params.areaName = this.areaList[this.$findElem(this.areaList, 'id', this.departmentForm.area)].zoneName;
          }
          if(this.departmentFormType == 'edit') {
            params.id = this.selectDepartment.id;
            params.websitId = this.selectDepartment.websitId;
            params.parentId = this.selectDepartment.parentId;
            editDepartment(params).then(res => {
              this.cancelDepartmentForm();
              this.getTree();
              this.getList();
              this.$successMsg('编辑成功');
            })
          }else {
            params.parentId = this.selectDepartment ? this.selectDepartment.websitId : 0;
            addDepartment(params).then(res => {
              this.cancelDepartmentForm();
              this.getTree();
              this.getList();
              this.$successMsg('添加成功');
            })
          }
        }
      })
    },

    // 打开 新增编辑 成员表单
    openMemberForm(type, id) {
      if(type == 'add') {
        if(!this.selectDepartment) {
          return this.$errorMsg('请选择部门');
        }
        this.memberForm.department = this.selectDepartment.name;
        this.memberForm.departmentId = this.selectDepartment.websitId;
      }
      if(type == 'edit') {
        this.editMemberId = id;
        getMemberDetail({id: id}).then(res => {
          this.memberForm = {
            name: res.data.name,
            sex: res.data.gender,
            account: res.data.wechatUserId,
            department: res.data.departmentName,
            departmentId: res.data.mainDepartment,
            post: res.data.position,
            phone: res.data.mobile,
            email: res.data.email,
          }
        })
      }
      this.memberFormType = type;
      this.memberFormVisible = true;
    },

    // 取消 新增编辑 成员表单
    cancelMemberForm(){
      this.memberFormVisible = false;
      this.$refs.memberForm.resetFields();
    },

    // 提交 成员表单
    submitMemberForm() {
      this.$refs.memberForm.validate((valid) => {
        if (valid) {
          let params = {
            name: this.memberForm.name,
            gender: this.memberForm.sex,
            wechatUserId: this.memberForm.account,
            mainDepartmentId: this.memberForm.departmentId,
            position: this.memberForm.post,
            mobile: this.memberForm.phone,
            email: this.memberForm.email,
          }
          if(this.memberFormType == 'edit') {
            params.id = this.editMemberId;
            editMember(params).then(res => {
              this.cancelMemberForm();
              this.getList();
              this.$successMsg('编辑成功');
            })
          }else {
            addMember(params).then(res => {
              this.cancelMemberForm();
              this.getList();
              this.$successMsg('添加成功');
            })
          }
        }
      })
    },

    // 表格选择列
    handleTableSelection(val) {
      this.tableSelection = val;
    },

    // 批量删除成员
    batchDeleteMember() {
      if(this.tableSelection.length < 1) {
        return this.$errorMsg('至少选择一名成员');
      }
      this.$confirm(`确定删除选中的成员吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let memberIds = [];
        this.tableSelection.forEach(item => {
          memberIds.push(item.id);
        });
        deleteMember({id: memberIds.join(',')}).then(res => {
          this.$successMsg();
          this.getTree();
          this.getList();
        })
      }).catch(() => {});
    },

    // 删除成员
    deleteMember(id) {
      deleteMember({id: id}).then(res => {
        this.$successMsg();
        this.getTree();
        this.getList();
      })
    },

    // 导出
    handleExport() {
      let screenData = {
        adminWebsitId: this.selectDepartment ? this.selectDepartment.websitId : '',
        keyword: this.screenForm.name
      };
      downloadFiles('wechat/enterprise/export', screenData);
    },

    // 下载导入模版
    handleDownload() {
      downloadFiles('wechat/enterprise/download');
    },
    // 下载导入删除模板
    delHandleDownload() {
      downloadFiles('wechat/enterprise/downloadDeleteExcel');
    },

    clickImport() {
      if(!this.selectDepartment) {
        return this.$errorMsg('请选择部门');
      }else {
        document.querySelector('.import-btn input').click();
      }
    },

    // 导入
    async handleImport(param) {
      this.importLoading = true;
      const file = param.file;
      const formData = new FormData();
      formData.append("file", file);
      formData.append("mainDepartmentId", this.selectDepartment.websitId);
      let result = await handleImport('wechat/enterprise/import', formData);
      this.importLoading = false;
      this.importFileList = [];
      if(result.code == 200) {
        this.$alert(result.message, '导入成功', {
          confirmButtonText: '确定'
        });
        this.getList();
      }else {
        this.$alert(result.message, '导入失败', {
          confirmButtonText: '确定'
        });
      }
    },

    // 导入删除成员
    async handleImport2(param) {
      this.importLoading2 = true;
      const file = param.file;
      const formData = new FormData();
      formData.append("file", file);
      let result = await handleImport('wechat/enterprise/excelDelete', formData);
      this.importLoading2 = false;
      this.importFileList2 = [];
      if(result.code == 200) {
        this.$alert(result.message, '导入成功', {
          confirmButtonText: '确定'
        });
        this.getList();
      }else {
        this.$alert(result.message, '导入失败', {
          confirmButtonText: '确定'
        });
      }
    },

  }
}
</script>

<style scoped lang="scss">
  .app-container {
    display: flex;
    .tree-container {
      width: 18%;
      height: calc(100vh - 110px);
      flex-shrink: 0;
      background: #f5f5f5;
      margin-right: 2%;
      display: flex;
      flex-direction: column;
      overflow-y: hidden;
      .el-tree {
        height: 100%;
        background: none;
        width: 100%;
        overflow: scroll;
        // ::v-deep .el-tree-node:focus > .el-tree-node__content {
        //   color: #ffffff;
        //   background-color: #409EFF;
        // }
        ::v-deep >.el-tree-node {
          display: inline-block;
          min-width: 100%;
        }
        ::v-deep .el-tree-node>.el-tree-node__content {
          padding-right: 10px;
          align-self: baseline;
        }
        ::v-deep .el-tree-node.is-current>.el-tree-node__content {
          background-color: #409EFF;
          .custom-tree-node {
            i {
              color: #fff;
            }
            span {
              color: #fff;
            }
          }
        }
        ::v-deep .el-tree-node>.el-tree-node__children {
          overflow: unset;
        }
        .custom-tree-node {
          i {
            font-size: 14px;
            color: #999;
          }
          span {
            font-size: 14px;
            margin-left: 6px;
            color: #666;
          }
        }
      }
    }
    .mymain-container {
      width: 80%;
      margin-top: 0;
    }
  }
  ::v-deep .el-divider--vertical {
    margin: 0 15px;
  }
</style>