<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="用户名称" prop="userId">
        <el-input
          v-model="queryParams.cardUsername"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="IC卡号" prop="cardCode">
        <el-input
          v-model="queryParams.cardCode"
          placeholder="请输入IC卡号"
          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="['system:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:info:edit']"
        >修改</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="['system:info: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="['system:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户名称" align="center" prop="cardUsername"/>
      <el-table-column label="卡片手机号码" align="center" prop="cardPhonenumber"  v-if="false"/>
      <el-table-column label="卡片编码" align="center" prop="cardCode" />
      <el-table-column label="用户编码" align="center" prop="userId" />
      <el-table-column label="所属机构" align="center" prop="organizationCode" >
        <template slot-scope="scope">
          {{ orgFormatter(scope.row.organizationCode) }}
        </template>
      </el-table-column>
      <el-table-column label="是否删除" align="center" prop="isDelete" v-if="false">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_or_no" :value="scope.row.isDelete"/>
        </template>
      </el-table-column>
      <el-table-column label="卡片状态" align="center" prop="cardState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_job_status" :value="scope.row.cardState"/>
        </template>
      </el-table-column>
      <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="['system:info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:info: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="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="卡片用户名称" prop="cardUsername">-->
<!--              <el-input v-model="form.cardUsername" placeholder="请输入卡片用户名称" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="卡片手机号码" prop="cardPhonenumber">-->
<!--              <el-input v-model="form.cardPhonenumber" placeholder="请输入卡片手机号码" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="IC卡号" prop="cardCode">
              <el-input v-model="form.cardCode" placeholder="请输入IC卡号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="卡片密码" prop="cardPassword">-->
<!--              <el-input v-model="form.cardPassword" placeholder="请输入卡片密码" :show-password="true"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userId">
              <el-autocomplete
                v-model="form.userId"
                :fetch-suggestions="queryNickName"
                placeholder="请输入内容"
                :trigger-on-focus="false"
                @select="handleSelect"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="机构代码" prop="organizationCode" v-if="false">
          <el-input v-model="form.organizationCode" placeholder="请输入IC卡号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo, exportInfo } from "@/api/system/cardinfo";
import user from "@/store/modules/user";
import {queryUserInfoByUserName} from "@/api/system/user";

export default {
  name: "Card",
  dicts: ['yes_or_no', 'sys_job_status'],
  data() {
    const validatorPhone = function (rule, value, callback) {
      if (!/^1\d{10}$/.test(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }

    const validatorPassword = function (rule, value, callback) {
      if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(value)) {
        callback(new Error('密码必须同时含有数字和字母,且长度要在8-16位之间'))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 卡片用户信息表格数据
      infoList: [],
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // jurisdiction: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cardUsername: '',
        cardCode: '',
        organizationCode: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // cardUsername: [
        //   { required: true, message : "卡片名称不能为空", trigger: "blur" }
        // ],
        // cardPhonenumber: [
        //   { required: true, message : "卡片手机号码不能为空", trigger: "blur" },
        //   { required: true, validator: validatorPhone, trigger: "blur" }
        // ],
        // cardPassword:[
        //   { required: true, message : "卡片密码不能为空", trigger: "blur" },
        //   { required: true, validator : validatorPassword, trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    // const roleTypes = Array.from(user.state.roleTypes);
    // this.jurisdiction = roleTypes.indexOf(2) > -1 && !roleTypes.indexOf(3) > -1;
    this.getList();
  },
  methods: {
    /** 查询卡片用户信息列表 */
    getList() {
      this.queryParams.organizationCode =  user.state.organ;
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cardUsername: null,
        cardPhonenumber: null,
        cardPassword: null,
        userId: null,
        organizationCode: null,
        isDelete: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        cardCode: null,
        cardState:null
      };
      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 = "添加卡片用户信息";
      this.form.organizationCode = user.state.organ;
      this.form.cardState = 0;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改卡片用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除卡片用户信息编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有卡片用户信息数据项？').then(() => {
        this.exportLoading = true;
        return exportInfo(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },

    orgFormatter(val) {
      let name = '';
      user.state.organDicts.forEach(item => {
        if(item.deptCode == val) {
          name = item.deptName;
        }
      })
      return name;
    },

    queryNickName(queryString, cb) {
      if(this.form.userId) {
        queryUserInfoByUserName({userName:this.form.userId}).then((response) => {
          if(response.code === 200){
            this.userList = response.data;
            this.userList.forEach(item=> {
              item.value = item.userName + ' ' + item.nickName;
            });
            cb(this.userList)
          }
        }).catch((e) => {
        });
      }
    },

    handleSelect(item) {
      this.form.userId = item.userName;
      this.form.cardUsername = item.nickName;
    }
  }
};
</script>
