<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="部门" prop="deptName" v-if="!data.id">
      <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班组" prop="siteGroupName" v-if="!data.id">
        <el-input
          v-model="queryParams.siteGroupName"
          placeholder="请输入班组名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人员名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入人员名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人员工号" prop="jobNumber">
        <el-input
          v-model="queryParams.jobNumber"
          placeholder="请输入人员工号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="在岗状态" prop="state" v-if="!data.id">
        <el-select v-model="queryParams.state" placeholder="请选择" style="width: 100%;">
          <el-option v-for="item in dict.type.gang_status" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="!data.id">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="[type=='2'?'business:manager:add':'business:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="[type=='2'?'business:manager:export':'business:user:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="[type=='2'?'business:manager:import':'business:user:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="班组" align="center" prop="siteGroupName" />
      <el-table-column label="人员工号" align="center" prop="jobNumber" />
      <el-table-column label="人员名称" align="center" prop="name" />
      <el-table-column label="岗位" align="center" prop="postName" />
      <el-table-column label="在岗状态" align="center" prop="state">
        <template slot-scope="scope">
          {{tableSelect(scope.row.state,dict.type.gang_status)}}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="!data.id">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="[type=='2'?'business:manager:edit':'business:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="[type=='2'?'business:manager:remove':'business:user:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改人员-人员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
<!--        <el-col :span="6" style="overflow-y:auto;height: 420px;">-->
<!--          <div style="padding: 10px 0;color: #999;">{{$store.state.user.completeName}}</div>-->
<!--          <el-tree ref="tree" :data="siteLists" :props="{label:'deptName',value:'deptId',children: 'children'}" :default-expand-all="true" node-key="id" :highlight-current="true" @node-click="siteClick"></el-tree>-->
<!--        </el-col>-->
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <div style="font-weight: bold; font-size: 18px">人员信息</div>
        <el-divider />
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门" prop="deptId">
                <treeselect v-model="form.deptId" :options="siteLists" placeholder="请选择" :show-count="true" @select="siteClick" :normalizer="normalizer" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班组" prop="siteGroupId">
                <el-select v-model="form.siteGroupId" filterable style="width: 100%;" :no-data-text="form.deptId?'该部门下暂无班组':'请先选择部门'" @change="setSiteGroup">
                  <el-option v-for="item in siteGroupList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="人员工号" prop="jobNumber">
                <el-input v-model="form.jobNumber" placeholder="请输入人员工号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入人员名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="岗位" prop="postId">
                <el-select v-model="form.postId" filterable style="width: 100%;" @change="postClick">
                  <el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="在岗状态" prop="state">
                <el-select v-model="form.state" placeholder="请选择" style="width: 100%;">
                  <el-option v-for="item in dict.type.gang_status" :key="item.value" :value="item.value" :label="item.label"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          <div style="font-weight: bold; font-size: 18px">系统信息</div>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="创建人" prop="createBy">
                <el-input v-model="form.createBy" placeholder="请输入创建人" style="width: 100%;" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间" prop="createTime">
                <el-date-picker v-model="form.createTime" type="datetime" style="width: 100%" value-formatter="yyyy-MM-dd HH:mm:ss" placeholder="选择创建时间" disabled>
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 人员导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&type=' + type"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
<!--          <div class="el-upload__tip" slot="tip">-->
<!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
<!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, getUserCode } from "@/api/business/user";
import { getSiteTree } from "@/api/business/unit";
import { listSiteGroup } from "@/api/business/siteGroup";
import { listPost } from "@/api/business/post";
import { formatDate } from "@/utils/index"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from '@/utils/auth'

export default {
  name: "User",
  dicts: ['gang_status'],
  props: {
    type: {
      type: String,
      default: '1', // 1-维修 2-管理
    },
    data: {
      type: Object,
      default: {}
    }
  },
  components: {
    Treeselect
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员-人员表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jobNumber: undefined,
        name: undefined,
        unitId: undefined,
        unitName: undefined,
        workshopId: undefined,
        workshopName: undefined,
        deptName: undefined,
        siteName: undefined,
        siteGroupId: undefined,
        siteGroupName: undefined,
        state: undefined,
        createTime: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "部门不能为空", trigger: "blur" }
        ],
        jobNumber: [
          { required: true, message: "人员工号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "人员名称不能为空", trigger: "blur" }
        ],
        siteGroupId: [
          { required: true, message: "班组不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "在岗状态不能为空", trigger: "blur" }
        ],
        postId: [
          { required: true, message: "岗位不能为空", trigger: "blur" }
        ],
      },
      siteLists: [],
      siteGroupLists: [],
      siteGroupList: [],
      postList: [],
      selectList: [],
    };
  },
  created() {
    this.getList();
    this.getSiteTre()
    this.getPost()
  },
  methods: {
    getSiteTre(){
      getSiteTree().then(response => {
        this.siteLists = this.handleTree(response.data, "deptId")
      });
    },
    getPost(){
      listPost({ pageNum: 1, pageSize: 999, type: this.type }).then(res=>{
        this.postList=res.rows
      })
    },
    /** 查询人员-人员列表 */
    getList() {
      this.loading = true;
      listUser({ ...this.queryParams, type: this.type, siteGroupId: this.data.groupId }).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        jobNumber: undefined,
        name: undefined,
        unitId: undefined,
        unitName: undefined,
        workshopId: undefined,
        workshopName: undefined,
        siteName: undefined,
        siteGroupId: undefined,
        siteGroupName: undefined,
        remark: undefined,
        state: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selectList = selection;
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // console.log(this.$store.state);
      this.form={
        createBy: this.$store.state.user.userInfo.userName,
        createTime: formatDate(new Date().getTime()),
        siteGroupId: '',
        jobNumber: '',
        state: '0'
      }
      this.siteGroupList=[]
      this.open = true;
      this.$nextTick(()=>{
        this.$refs.tree.setCurrentKey(null)
      })
      this.title = "添加人员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      const id = row.id || this.ids
      getUser(id).then(response => {
        if(response.data.state!=null)response.data.state=''+response.data.state;
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改人员";
        this.$nextTick(()=>{
          this.$refs.tree.setCurrentKey(response.data.deptId)
        })
        listSiteGroup({ pageNum: 1, pageSize: 999, deptId: response.data.deptId }).then(res=>{
          this.siteGroupList=res.rows
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateUser({
              ...this.form,
              type: this.type,
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addUser({
              ...this.form,
              type: this.type,
            }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('请确认是否删除'+row.name+'的人员信息，删除后无法恢复！').then(() => {
        this.loading = true;
        return delUser(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "人员导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('business/user/importTemplate', {
        ...this.queryParams,
        ids: this.ids.join(','),
        type: this.type,
      }, `${this.type=='2'?'管理':'维修'}人员`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/user/export', {
        ...this.queryParams,
        ids: this.ids.join(','),
        type: this.type,
      }, `${this.type=='2'?'管理':'维修'}人员`)
    },
    siteClick(e){
      console.log(e);
        this.form.siteGroupId = undefined
        this.form.siteGroupName = undefined
        listSiteGroup({ pageNum: 1, pageSize: 999, deptId: e.deptId }).then(res=>{
          this.siteGroupList=res.rows
        })
      // if(e.ceng==3){
      //   this.form.unitId=e.unitId
      //   this.form.unitName=e.unitName
      //   this.form.workshopId=e.workshopId
      //   this.form.workshopName=e.workshopName
      //   this.form.siteName=e.name;
      // }else{
      //   this.form.siteGroupId=''
      //   this.form.siteGroupName=''
      //   this.siteGroupList=[]
      //   this.$refs.tree.setCurrentKey(null)
      // }
    },
    setSiteGroup(e){
      let item=this.siteGroupList.find(item=>item.id==e)
      if(item){
        this.form.siteGroupName=item.name
      }
    },
    postClick(e){
      let item=this.postList.find(item=>item.id==e)
      if(item){
        this.form.postName=item.name
        getUserCode(e).then(res=>{
          this.form.jobNumber=res.data
        })
      }
    },
    handleChange(e){
      console.log(e);
      this.queryParams.siteGroupId=''
        listSiteGroup({
          pageNum: 1,
          pageSize: 999,
          deptId: e.deptId
        }).then(res=>{
          this.siteGroupLists=res.rows
        })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
        // isDisabled: node.level<4&&!node.children
      };
    },
  }
};
</script>
<style scoped>
.app-title{
  font-size: 16px;
  font-weight: 600;
  padding: 10px 0;
}
</style>
