<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" class="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="资产编码" prop="assetNumber">
        <el-input
          v-model="queryParams.assetNumber"
          placeholder="请输入资产编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产名称" prop="assetName">
        <el-input
          v-model="queryParams.assetName"
          placeholder="请输入资产名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="借出人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入借出人用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="借出时间" prop="borrowTime">
        <el-date-picker clearable
          v-model="queryParams.borrowTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择借出时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="借出位置" prop="borrowLocationNumber">
        <treeselect v-model="queryParams.borrowLocationNumber" :options="locationList" :normalizer="tenantIdnormalizer" placeholder="请选择借出位置" />
      </el-form-item>
      <el-form-item label="预计归还时间" prop="expectedReturnTime">
        <el-date-picker clearable
          v-model="queryParams.expectedReturnTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择预计归还时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否归还" prop="isReturn">
        <el-select v-model="queryParams.isReturn" placeholder="请选择是否归还" clearable>
          <el-option
            v-for="dict in dict.type.my_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="归还时间" prop="returnTime">
        <el-date-picker clearable
          v-model="queryParams.returnTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择归还时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="归还位置" prop="returnLocationNumber">
        <treeselect v-model="queryParams.returnLocationNumber" :options="locationList" :normalizer="tenantIdnormalizer" placeholder="请选择归还位置" />
      </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="['asset:borrow: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="['asset:borrow: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="['asset:borrow:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['asset:borrow:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="borrowList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="编号" align="center" prop="id" /> -->
      <el-table-column label="资产编码" align="center" prop="assetNumber" />
      <el-table-column label="资产名称" width="200" align="center" prop="assetName" />
      <el-table-column label="借出人" align="center" prop="userName" />
      <el-table-column label="借出时间" align="center" prop="borrowTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.borrowTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借出位置" width="200" align="center" prop="borrowLocationName" />
      <el-table-column label="预计归还时间" align="center" prop="expectedReturnTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedReturnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否归还" align="center" prop="isReturn">
        <template slot-scope="scope">
          <!-- <dict-tag :options="dict.type.my_yes_no" :value="scope.row.isReturn"/> -->
          <el-switch
            v-model="scope.row.isReturn"
            :active-value="1"
            active-color="#13ce66"
            :inactive-value="0"
            @change="onReturn($event, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="归还时间" align="center" prop="returnTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归还位置" width="200" align="center" prop="returnLocationName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['asset:borrow:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['asset:borrow: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="借出资产编码" prop="assetNumber">
          <!-- <el-input v-model="form.assetNumber" placeholder="请输入借出资产编码" :disabled="isUpdate"/> -->
          <el-select v-model="form.assetNumber" :disabled="isUpdate" filterable placeholder="请选择借出资产编码">
            <el-option
              v-for="item in assetSelect"
              :key="item.id"
              :label="item.number"
              :value="item.number">
              <span style="float: left">{{ item.number }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="借出人用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入借出人用户名" @change="onCheckUserName">
            <el-button slot="append" icon="el-icon-search" @click="openUserSearch = true"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="借出位置" prop="borrowLocationNumber" v-if="isUpdate">
          <treeselect v-model="form.borrowLocationNumber" :options="locationList" :normalizer="tenantIdnormalizer" placeholder="请输入借出位置"/>
        </el-form-item>
        <el-form-item label="预计归还时间" prop="expectedReturnTime">
          <el-date-picker clearable
            v-model="form.expectedReturnTime"
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            placeholder="请选择预计归还时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否归还" prop="isReturn" v-if="isUpdate">
          <el-switch
            v-model="form.isReturn"
            active-text="是"
            :active-value="1"
            active-color="#13ce66"
            inactive-text="否"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item label="归还时间" prop="returnTime" v-if="isUpdate && form.isReturn === 1">
          <el-date-picker clearable
            v-model="form.returnTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择归还时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="归还位置" prop="returnLocationNumber" v-if="isUpdate && form.isReturn === 1">
          <treeselect v-model="form.returnLocationNumber" :options="locationList" :normalizer="tenantIdnormalizer" placeholder="请输入归还位置" />
          <el-button type="text" @click="onUseBorrowLocation">归还原位</el-button>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </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>

    <el-dialog :visible.sync="openUserSearch">
      <UserSearch @submit="onSelectUser" @cancel="() => {openUserSearch = false}" v-if="openUserSearch"></UserSearch>
    </el-dialog>
  </div>
</template>

<script>
import { listBorrow, getBorrow, delBorrow, addBorrow, updateBorrow } from "@/api/asset/borrow";
import { select as AssetSelect } from '@/api/asset/information'
import { isExistsUserName } from '@/api/system/user'
import { treeSelect } from '@/api/asset/location'
import UserSearch from '@/components/SysUserSearch/index.vue'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: "Borrow",
  dicts: ['my_yes_no'],
  components: {
    Treeselect,
    UserSearch
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产借用表格数据
      borrowList: [],
      // 所属位置表格数据
      locationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetNumber: null,
        assetName: null,
        userName: null,
        borrowTime: null,
        borrowLocationNumber: null,
        expectedReturnTime: null,
        isReturn: null,
        returnTime: null,
        returnLocationNumber: null,
      },
      // 表单参数
      form: {},
      isUpdate: false,
      openUserSearch: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      // 表单校验
      rules: {
        assetNumber: [
          { required: true, message: "借出资产编码不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "借出人用户名不能为空", trigger: "blur" }
        ],
        borrowTime: [
          { required: true, message: "借出时间不能为空", trigger: "blur" }
        ],
        borrowLocationNumber: [
          { required: true, message: "借出位置不能为空", trigger: "blur" }
        ],
        expectedReturnTime: [
          { required: true, message: "预计归还时间不能为空", trigger: "blur" }
        ],
        returnLocationNumber: [
          { required: true, message: "归还位置不能为空", trigger: "blur" }
        ],
      },
      assetSelect: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    tenantIdnormalizer(node) {
      return {
        id: node.number,
        label: node.label,
        children: node.children,
      }
    },
    /** 查询资产借用列表 */
    getList() {
      this.loading = true;
      listBorrow(this.queryParams).then(response => {
        this.borrowList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      treeSelect().then((response) => {
        this.locationList = response.data
      })
      this.getAssetSelect()
    },
    getAssetSelect() {
      AssetSelect().then((res) => {
        this.assetSelect = res.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        assetNumber: null,
        userName: null,
        borrowTime: null,
        borrowLocationNumber: null,
        expectedReturnTime: null,
        isReturn: null,
        returnTime: null,
        returnLocationNumber: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: 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
    },
    onSelectUser(info) {
      this.openUserSearch = false
      this.form.userName = info.userName
    },
    onCheckUserName(val) {
      isExistsUserName(val).then(res => {
        const isExists = res.data
        if (!isExists) {
          this.$modal.msgWarning('用户不存在')
          this.form.userName = null
        }
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getAssetSelect()
      this.open = true;
      this.isUpdate = false
      this.title = "添加资产借用";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBorrow(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.isUpdate = true
        this.title = "修改资产借用";
      });
    },
    onUseBorrowLocation() {
      this.form.returnLocationNumber = this.form.borrowLocationNumber
    },
    onReturn(e, row) {
      this.$modal.confirm('是否确认更改该数据项？').then(() => {
        this.onSubmitReturn(e, row)
      }).catch(() => {
        this.getList();
      })
    },
    onSubmitReturn(e, row) {
      const form = row
      let message;
      if (e === 1) {
        message = '归还成功'
        form.returnLocationNumber = row.borrowLocationNumber
      } else {
        message = '修改成功'
        form.returnTime = null
        form.returnLocationNumber = null
      }      
      updateBorrow(form).then(response => {
        this.$modal.msgSuccess(message);
        this.getList();
      }).catch((e) => {
        this.getList();
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBorrow(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBorrow(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 delBorrow(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('asset/borrow/export', {
        ...this.queryParams
      }, `borrow_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .vue-treeselect {
  display: inline-block;
}
.queryForm {
  /deep/ .vue-treeselect {
    width: 205px;
    height: 32px;
  }
}
</style>
