<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="队伍" prop="ranks">
        <el-select v-model="queryParams.ranks" clearable placeholder="请选择队伍">
          <el-option
            v-for="item in postOptions"
            :key="item.postId"
            :label="item.postName"
            :value="item.postId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工号" prop="jobNum">
        <el-input
          v-model="queryParams.jobNum"
          placeholder="请输入工号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gas:user:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gas:user:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          :loading="exportLoading"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['gas:user:export']"-->
      <!--        >导出</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="主键id" align="center" prop="id" v-if="false"/>
      <el-table-column label="序号" width="70">
        <template slot-scope="scope">
          {{(queryParams.pageNum-1)*queryParams.pageSize+scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="队伍" align="center" prop="ranks">
        <template slot-scope="scope">
          <dict-post :options="postOptions" :value="scope.row.ranks"/>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name"/>
      <el-table-column label="工号" align="center" prop="jobNum"/>
<!--      <el-table-column label="手机号" align="center" prop="phone"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gas:user:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="selectYaBox(scope.row,1)"
          >增减调压箱
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="selectYaBox(scope.row,2)"
          >增减庭院管网
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="selectYaBox(scope.row,3)"
          >增减阀井
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gas:user:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <tyx ref="tyx" v-if="tyxShow" @closeE="closeE"></tyx>
    <areas ref="areas" v-if="areaShow" @closeF="closeF"></areas>
    <vw ref="vw" v-if="vwShow" @closeF="closeG"></vw>
    <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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="队伍" prop="ranks">
          <el-select v-model="form.ranks" clearable placeholder="请选择">
            <el-option
              v-for="item in postOptions"
              :key="item.postId"
              :label="item.postName"
              :value="item.postId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="工号" prop="jobNum">
          <el-input v-model="form.jobNum" placeholder="请输入工号"/>
        </el-form-item>
<!--        <el-form-item label="手机号" prop="phone">-->
<!--          <el-input v-model="form.phone" placeholder="请输入手机号"/>-->
<!--        </el-form-item>-->
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" autocomplete="new-password"/>
        </el-form-item>
        <el-form-item label="工程权限" prop="power">
          <el-select
            v-model="form.power"
            placeholder="请选择工程权限"
            clearable
            multiple
            size="small"
            style="width:100%"
          >
            <el-option
              v-for="dict in dict.type.engine_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="管理所" prop="power">
          <el-select
            v-model="form.administrativeOffice"
            placeholder="请选择管理所"
            clearable
            multiple
            size="small"
            style="width:100%"
          >
            <el-option
              v-for="dict in dict.type.administrative_office"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </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>
  </div>
</template>


<script>
import {listUser, getForPhone, getForJobnum, getUser, delUser, addUser, updateUser} from "@/api/gas/user";
import {listPostAll} from "@/api/system/post";
import Cookies from "js-cookie";
import tyx from "@/views/gas/user/springIoc/tyx.vue";
import areas from "@/views/gas/user/springIoc/area.vue";
import vw from "@/views/gas/user/springIoc/vw.vue";
export default {
  components:{tyx,areas,vw},
  name: "User",
  dicts: ['user_type', 'engine_type', 'administrative_office'],
  data() {
    // 手机号唯一性验证
    let validateAnotherPhone = (rule, value, callback) => {
      console.log(value)
      console.log(rule)
      console.log(this.form)
      let PHONE_REG = /^((0\d{2,3}-{0,1}\d{7,8})|(1[3-9]\d{9}))$/;
      if (value) {
        if (!PHONE_REG.test(value)) {
          callback(new Error('请输入有效的手机号'));
          return;
        }
        getForPhone(value, this.form.id).then(res => {
          if (res.data === false) {
            callback('该手机号已存在');
          } else {
            callback();
          }
        }).catch(err => {
          callback(new Error(err.data.msg));
        });
      } else {
        callback();
      }
    };
    // 工号唯一性验证
    let validateAnother = (rule, value, callback) => {
      if (value) {
        getForJobnum(value, this.form.id).then(res => {
          if (res.data === false) {
            callback('该工号已存在');
          } else {
            callback();
          }
        }).catch(err => {
          callback(new Error(err.data.msg));
        });
      } else {
        callback();
      }
    };
    return {
      tyxShow:false,
      areaShow:false,
      vwShow:false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        jobNum: undefined,
        ranks: (Cookies.get("postName").indexOf('xx') > -1 ? parseInt(Cookies.get("postId")) : undefined),
      },
      postName:Cookies.get("postName"),
      // 岗位选项
      postOptions: [],
      selectIds:[],
      foremanList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "姓名不能为空", trigger: "blur"}
        ],
        ranks: [
          {required: true, message: "队伍不能为空", trigger: "blur"}
        ],
        jobNum: [
          {required: true, message: "工号不能为空", trigger: "blur"},
          {required: true, trigger: 'blur', validator: validateAnother}
        ],
        // phone: [
        //   {
        //     validator: validateAnotherPhone,
        //     message: "请输入正确的手机号码",
        //     trigger: "blur"
        //   }
        // ]
      }
    };
  },
  created() {
    this.getPostList();
    this.getList();
  },
  methods: {
    selectYaBox(row, index) {
        if (index === 1) {
          this.tyxShow = true;
          this.$nextTick(() => {
            this.$refs.tyx.init(row)
          })
        }
        if (index === 2) {
          this.areaShow = true;
          this.$nextTick(() => {
            this.$refs.areas.init(row)
          })
        }
        if (index === 3) {
          this.vwShow = true;
          this.$nextTick(() => {
            this.$refs.vw.init(row)
          })
        }
    },
    closeE(){
      this.tyxShow = false;
    },
    closeF(){
      this.areaShow = false;
    },
    closeG(){
      this.vwShow = false;
    },
    //获取岗位列
    getPostList(){
      listPostAll({remark:'ranks'}).then(response => {
        this.postOptions = response.data;
      });
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    foreman(role) {
      if (role === "002") {
        this.foremanForm = true;
      } else {
        this.foremanForm = false;
        this.form.parentId = undefined;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        ranks: (Cookies.get("postName").indexOf('xx') > -1 ? parseInt(Cookies.get("postId")) : undefined),
        name: undefined,
        jobNum: undefined,
        phone: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        power: "",
      };
      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.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
        this.form.power = response.data.power == null || response.data.power == '' ? [] : response.data.power.split(",");
        this.form.administrativeOffice = response.data.administrativeOffice == null || response.data.administrativeOffice == '' ? [] : response.data.administrativeOffice.split(",");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.power = this.form.power.toString();
          this.buttonLoading = true;
          if (this.form.id != null) {
            this.form.administrativeOffice = this.form.administrativeOffice == null ? "" : this.form.administrativeOffice.join()
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            }).catch(() => this.buttonLoading = false);
          } else {
            this.form.administrativeOffice = this.form.administrativeOffice == null ? "" : this.form.administrativeOffice.join()
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            }).catch(() => this.buttonLoading = false);
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delUser(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$download.excel('/gas/user/export', this.queryParams);
    },
  }
};
</script>
