<template>
  <div class="app-container row-container">
    <!--工具栏-->
    <div class="head-container">
      <div class="head-search">
        <!-- 搜索 -->
        <el-input v-model="query.search" clearable size="small" placeholder="输入借阅者名称搜索" prefix-icon="el-icon-search" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation />
      </div>
      <div style="display: flex; justify-content: space-between;">
        <crudOperation :permission="permission">
          <!-- <template v-slot:middle>
            <el-button size="mini" :disabled="crud.selections.length !== 1" @click="toEdit(crud.selections[0])">
              <i class="iconfont icon-bianji" />
              编辑
            </el-button>
          </template> -->
          <template v-slot:right>
            <el-button :loading="crud.downloadLoading" size="mini" :disabled="crud.selections.length === 0" @click="doExport(crud.selections)">
              <i class="iconfont icon-daochu" />
              导出
            </el-button>
            <el-button icon="el-icon-refresh-left" size="mini" :disabled="crud.selections.length !== 1" @click="handlePwdReset(crud.selections)">密码重置</el-button>
          </template>
        </crudOperation>
        <div>
          <el-button size="mini" :loading="bindLoading" :disabled="crud.selections.length !== 1" @click="bindingTag(crud.selections)">
            <i class="iconfont icon-bendiguajie" />
            绑定借阅证
          </el-button>
          <el-button :loading="unbindBtnLoading" class="unbind-btn" size="mini" :disabled="crud.selections.length !== 1" @click="handleUnbind(crud.selections)">
            <i class="iconfont icon-jiebang" />
            解绑借阅证
          </el-button>
        </div>
      </div>
    </div>
    <!--表格渲染-->
    <div class="container-wrap">
      <span class="right-top-line" />
      <span class="left-bottom-line" />
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        row-key="id"
        @select="crud.selectChange"
        @select-all="crud.selectAllChange"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="borrowName" label="借阅者名称" />
        <el-table-column prop="borrowType" label="借阅者类型">
          <template slot-scope="scope">
            <div>
              <span v-if="scope.row.borrowType === 1">部门</span>
              <span v-if="scope.row.borrowType === 2">个人</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="borrowNo" label="借阅证绑定">
          <template slot-scope="scope">
            <div>
              <span v-if="scope.row.borrowNo === null || scope.row.borrowNo === ''" class="row-state cancel-state">未绑定</span>
              <span v-else class="row-state end-state">已绑定</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="borrowNo" label="借阅证号" />
        <el-table-column prop="create_time" label="创建日期" width="200px">
          <template slot-scope="scope">
            <div>{{ scope.row.create_time | parseTime }}</div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-if="crud.data.length !== 0" />
    </div>

    <!--表单渲染-->
    <el-dialog class="borrower-dialog" append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title">
      <div class="setting-dialog">
        <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="100px">
          <el-form-item label="借阅者类型" prop="borrowType">
            <el-radio-group v-model="form.borrowType">
              <el-radio :label="1">部门</el-radio>
              <el-radio :label="2">个人</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="借阅者名称" prop="borrowName">
            <el-input v-model="form.borrowName" style="width:380px;" />
          </el-form-item>
          <el-form-item label="借阅证号" prop="borrowNo">
            <el-input v-model="form.borrowNo" disabled style="width:380px;" />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="4" style="width:380px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 密码重置dialog -->
    <el-dialog class="tip-dialog" :visible.sync="resetVisible" :modal-append-to-body="false" append-to-body :close-on-click-modal="false" title="提示">
      <div class="setting-dialog">
        <div class="tip-content">
          <p class="tipMsg">此操作将重置所选借阅者密码为"123456"</p>
          <span>你是否还要继续?</span>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="resetVisible = false">取消</el-button>
          <el-button v-loading="btnLoading" type="primary" @click="pwdReset(crud.selections)">继续</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import crudBorrower from '@/api/system/borrower'
import { FetchReadPatron, FetchBindReadNo, FetchUnbindReadNo } from '@/api/system/documentArchives'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import { exportFile } from '@/utils/index'
import qs from 'qs'
import { mapGetters } from 'vuex'

// crud交由presenter持有
const defaultForm = { id: null, borrowType: 1, borrowName: null, remarks: null }
export default {
  name: 'BorrowerManage',
  components: { crudOperation, rrOperation, pagination },
  cruds() {
    return CRUD({
      title: '借阅者',
      url: 'api/documentArchives/initBorrowerList',
      crudMethod: { ...crudBorrower },
      optShow: {
        add: true,
        edit: true,
        del: true,
        reset: true,
        download: false,
        group: false
      }
    })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      permission: {
        add: ['admin', 'borrower:add'],
        edit: ['admin', 'borrower:edit'],
        del: ['admin', 'borrower:del']
      },
      rules: {
        borrowType: [
          { required: true, message: '请选择借阅者类型', trigger: 'change' }
        ],
        borrowName: [
          { required: true, message: '借阅者名称不可为空', trigger: 'blur' }
        ]
      },
      bindLoading: false,
      unbindBtnLoading: false,
      resetVisible: false,
      btnLoading: false
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  created() {

  },
  mounted() {

  },
  methods: {
    [CRUD.HOOK.afterRefresh](crud) {
    },
    bindingTag(selection) {
      this.bindLoading = true
      console.log('selection', selection)
      if (selection[0].borrowNo && (selection[0].borrowNo !== '' || selection[0].borrowNo !== null)) {
        console.log('当前用户已绑定')
        this.$confirm('当前所选用户已有借阅证' + '<span>你是否还要继续？</span>', '提示', {
          confirmButtonText: '重新绑定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }).then(() => {
          this.handlBind(selection)
        }).catch(() => {
          this.bindLoading = false
        })
      } else {
        this.handlBind(selection)
      }
    },
    handlBind(selection) {
      const sDevID = process.env.NODE_ENV === 'production' ? window.g.sDevID : process.env.VUE_APP_SDEVID
      const param = {
        'sDevID': sDevID
      }
      FetchReadPatron(param).then((res) => {
        console.log('res', res)
        if (!res) {
          this.$message({ message: '绑定失败', type: 'error', offset: 8 })
          this.bindLoading = false
        } else {
          const result = JSON.parse(res)
          console.log('result', result)
          if (result.code === '0') {
            const readParam = {
              'id': selection[0].id,
              'borrowNo': result.data[0].barcode
            }
            FetchBindReadNo(readParam).then((res) => {
              console.log('FetchBindReadNo', res)
              this.crud.refresh()
              this.bindLoading = false
              this.$message({ message: '绑定成功', type: 'success', offset: 8 })
            }).catch(error => {
              console.error(error)
              this.bindLoading = false
            })
          } else if (result.code === '-1') {
            this.$message({ message: result.message, type: 'error', offset: 8 })
            this.bindLoading = false
          } else if (result.code === '-1000') {
          // 读写器超时未响应
            this.$message({ message: result.message, type: 'error', offset: 8 })
            this.bindLoading = false
          }
        }
      }).catch(error => {
        console.error(error)
        this.bindLoading = false
      })
    },
    handleUnbind(selection) {
      if (selection[0].borrowNo && (selection[0].borrowNo !== '' || selection[0].borrowNo !== null)) {
        this.$confirm('此操作将解除所选借阅证的绑定关系' + '<span>你是否还要继续？</span>', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }).then(() => {
          this.unbindBtnLoading = true
          const unbindData = {
            'id': selection[0].id,
            'borrowNo': selection[0].borrowNo
          }
          FetchUnbindReadNo(unbindData).then((res) => {
            this.unbindBtnLoading = false
            this.$message({ message: '解除绑定成功', type: 'success', offset: 8 })
            this.crud.refresh()
          })
        }).catch(() => {
        })
      } else {
        this.$message({ message: '当前所选用户借阅者未绑定', type: 'error', offset: 8 })
      }
    },
    doExport(data) {
      console.log(data)
      crud.downloadLoading = true
      this.$confirm('此操作将导出所选数据' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const ids = []
        data.forEach(val => {
          ids.push(val.id)
        })
        const params = {
          'ids': ids
        }
        console.log('params', params)
        exportFile(this.baseApi + '/api/documentArchives/downloadBorrower?' + qs.stringify(params, { indices: false }))
      }).catch(() => {
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.cnName,
        children: node.children,
        isDisabled: node.isType !== 2
      }
    },
    // 重置密码
    handlePwdReset() {
      this.resetVisible = true
    },
    // 重置密码
    pwdReset(data) {
      const params = data.map(item => { return item.borrowName })
      console.log('params', params)
      // this.btnLoading = true
      // resetpassword(params).then(res => {
      //   if (res === 'SUCCESS') {
      //     this.$message({ message: '重置密码成功', type: 'success', offset: 8 })
      //     this.resetVisible = false
      //     this.btnLoading = false
      //     this.crud.refresh()
      //   } else {
      //     this.$message({ message: '重置密码失败', type: 'error', offset: 8 })
      //     this.btnLoading = false
      //   }
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
[data-theme=light] .el-button.unbind-btn,
[data-theme=light] .el-button.unbind-btn:hover,
[data-theme=light] .el-button.unbind-btn:focus{
  color: #ED4A41;
  border-color: #ED4A41;
  background: transparent;
}

[data-theme=light] .el-button.unbind-btn.is-disabled,
[data-theme=light] .el-button.unbind-btn.is-disabled:hover,
[data-theme=light] .el-button.unbind-btn.is-disabled:focus{
  color:#F6A5A0;
  border-color:#F6A5A0;
  background: rgba(252,49,49,0.2);
}
.borrower-dialog{
  ::v-deep .el-dialog{
    width: 550px !important;
  }
}
</style>
