<template>
  <div class="main-container-text">
    <div class="title">试剂管理</div>
    <div class="header">
      <el-select v-model="client_id" clearable placeholder="请选择柜体">
        <el-option
          v-for="item in $store.getters.clientOptions"
          :key="item.id"
          :label="item.client_name"
          :value="item.client_id"
        />
      </el-select>
      <el-input v-model="name" clearable placeholder="请输入试剂名称" />
      <el-button type="primary" icon="el-icon-search" @click="getList">搜索</el-button>
      <el-button type="primary" plain @click="handleSetEmpty"><svg-icon icon-class="cup" /> 设为空瓶</el-button>
      <el-button icon="el-icon-edit" @click="handleEdit">编辑试剂</el-button>
      <el-button @click="showHistory"><svg-icon icon-class="流转" /> 查看流转记录</el-button>
      <el-button icon="el-icon-user" @click="handleDisable">分配禁用用户</el-button>
      <div class="header-right">
        <el-button icon="el-icon-delete" circle @click="handleDel" />
        <el-button icon="el-icon-refresh" circle @click="handleRefresh" />
      </div>
    </div>
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      stripe
      element-loading-text="拼命加载中"
      :header-cell-style="headerStyle"
      height="69vh"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        align="center"
        type="index"
        width="50"
        label="序号"
      />
      <el-table-column
        prop="name"
        show-overflow-tooltip
        label="试剂名称"
        align="center"
        width="100"
      />
      <el-table-column
        prop="english_name"
        show-overflow-tooltip
        label="英文名称"
        align="center"
        width="100"
      />
      <el-table-column
        prop="bar_code"
        label="试剂编码"
        align="center"
      />
      <el-table-column
        show-overflow-tooltip
        prop="cas_number"
        label="CAS码"
        align="center"
      />
      <el-table-column
        prop="speci"
        label="规格"
        align="center"
      />
      <el-table-column
        prop="remain"
        label="余量(g)"
        align="center"
      />
      <el-table-column
        prop="purity"
        label="纯度"
        align="center"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        prop="production_date"
        label="生产日期"
        align="center"
        width="150"
      />
      <el-table-column
        prop="put_in_date"
        label="入库时间"
        align="center"
        width="150"
      />
      <!--      <el-table-column-->
      <!--        prop="is_supervise"-->
      <!--        label="是否监管"-->
      <!--        align="center"-->
      <!--      />-->
      <el-table-column
        prop="status"
        label="状态"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag :type="statusColorMap[scope.row.status-1]">{{ statusMap[scope.row.status-1] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="client_id"
        label="所属终端"
        align="center"
      >
        <template slot-scope="scope">
          <div v-if="$store.getters.clientOptions.find(item => item.client_id === scope.row.client_id)">
            {{ $store.getters.clientOptions.find(item => item.client_id === scope.row.client_id).client_name }}
          </div>
          <div v-else>
            {{ scope.row.client_id }}
          </div>
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--        prop="inventory_warning_value"-->
      <!--        label="预警量(瓶)"-->
      <!--        align="center"-->
      <!--      />-->
      <!--      <el-table-column-->
      <!--        prop="use_days_warning_value"-->
      <!--        label="提前预警(天)"-->
      <!--        align="center"-->
      <!--      />-->
      <el-table-column
        prop="by_user_name"
        label="最后使用人"
        align="center"
      />
      <el-table-column
        v-for="item in extra_form"
        :key="item.id"
        align="center"
        :prop="item.name"
        :label="item.name"
        width="100"
        show-overflow-tooltip
      />
    </el-table>
    <div class="my-pagination" style="text-align: center">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page.sync="page"
        :total="total"
        :page-size.sync="page_size"
        :disabled="loading"
        @current-change="pageChange"
      />
    </div>
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogHistoryVisible" width="60%" title="查看流转记录" @close="handleHistoryClose">
      <el-table
        v-loading="loadingHistory"
        element-loading-text="拼命加载中"
        :header-cell-style="headerStyle"
        :data="historyData"
        height="420"
      >
        <el-table-column align="center" type="index" width="50" label="序号" />
        <el-table-column align="center" property="name" label="试剂名称" />
        <el-table-column align="center" property="bar_code" label="试剂编码" width="100" show-overflow-tooltip />
        <el-table-column align="center" property="cas_number" label="CAS码" />
        <el-table-column align="center" property="purity" label="纯度" width="100" show-overflow-tooltip />
        <el-table-column align="center" property="client_id" label="所属终端">
          <template slot-scope="scope">
            <div v-if="$store.getters.clientOptions.find(item => item.client_id === scope.row.client_id)">
              {{ $store.getters.clientOptions.find(item => item.client_id === scope.row.client_id).client_name }}
            </div>
            <div v-else>
              {{ scope.row.client_id }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" property="status" label="操作类型">
          <template slot-scope="scope">
            <el-tag :type="statusColorMap[scope.row.status-1]">{{ recodeStatusMap[scope.row.status-1] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" property="create_date" label="操作时间" width="150" />
        <el-table-column align="center" property="create_user_name" label="操作人员" />
      </el-table>
      <div class="my-pagination" style="text-align: center">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="history_page"
          :total="history_total"
          :page-size.sync="history_page_size"
          :disabled="loadingHistory"
          @current-change="HistoryPageChange"
        />
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogUserVisible" width="60%" title="分配禁用用户">
      <div class="user-header">
        <el-input v-model="seach_user" clearable placeholder="请输入内容" />
        <el-button type="primary" icon="el-icon-search" @click="getUserList">搜索</el-button>
        <el-button plain type="danger" @click="handleDisUser"><svg-icon icon-class="确认禁用" /> 确认禁用</el-button>
        <el-button plain type="success" @click="handleEnUser"><svg-icon icon-class="解除禁用" /> 解除禁用</el-button>
      </div>
      <el-table
        v-loading="loadingUser"
        element-loading-text="拼命加载中"
        :header-cell-style="headerStyle"
        :data="userData"
        height="420"
        stripe
        @selection-change="handleUserSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" width="50" />
        <el-table-column align="center" property="name" label="用户头像">
          <template slot-scope="scope">
            <el-avatar :size="20" :src="scope.row.circleUrl" />
          </template>
        </el-table-column>
        <el-table-column align="center" property="real_name" label="用户名称" />
        <el-table-column align="center" property="role_name" label="用户身份" />
        <el-table-column align="center" label="禁用状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status_type === 1?'danger':'success'">{{ scope.row.status_type === 1? '已禁用':'未禁用' }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="my-pagination" style="text-align: center">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="user_page"
          :total="user_total"
          :page-size.sync="user_page_size"
          :disabled="loadingUser"
          @current-change="userPageChange"
        />
      </div>

    </el-dialog>
    <el-dialog :visible.sync="dialogEditVisible" :close-on-click-modal="false" width="60%" title="编辑试剂" @close="onClose">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="110px">
          <el-col :span="24">
            <el-form-item label="试剂名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入试剂名称" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="英文名称" prop="english_name">
              <el-input v-model="formData.english_name" placeholder="请输入英文名称" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="条码编号" prop="bar_code">
              <el-input v-model="formData.bar_code" placeholder="请输入条码编号" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="CAS码" prop="cas_number">
              <el-input v-model="formData.cas_number" placeholder="请输入CAS码" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试剂纯度" prop="purity">
              <el-input v-model="formData.purity" placeholder="请输入试剂纯度" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保质期" prop="shelf_life">
              <el-input v-model="formData.shelf_life" placeholder="请输入保质期" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产日期" prop="production_date">
              <el-date-picker
                v-model="formData.production_date"
                style="width: 100%"
                type="datetime"
                placeholder="选择过期日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过期日期" prop="expiration_date">
              <el-date-picker
                v-model="formData.expiration_date"
                style="width: 100%"
                type="datetime"
                placeholder="选择过期日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="出库预警天数" prop="use_days_warning_value">-->
          <!--              <el-input-->
          <!--                v-model="formData.use_days_warning_value"-->
          <!--                placeholder="请输入出库预警天数"-->
          <!--                clearable-->
          <!--                :style="{width: '100%'}"-->
          <!--              />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="保质期预警天数" prop="shelf_life_warning_value">-->
          <!--              <el-input-->
          <!--                v-model="formData.shelf_life_warning_value"-->
          <!--                placeholder="请输入保质期预警天数"-->
          <!--                clearable-->
          <!--                :style="{width: '100%'}"-->
          <!--              />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="预警量" prop="inventory_warning_value">-->
          <!--              <el-input v-model="formData.inventory_warning_value" placeholder="请输入预警量" clearable :style="{width: '100%'}" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="规格" prop="speci">
              <el-input v-model="formData.speci" placeholder="请输入规格" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="net_weight_unit">
              <el-input v-model="formData.net_weight_unit" placeholder="请输入单位" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预估质量" prop="net_weight">
              <el-input v-model="formData.net_weight" placeholder="请输入预估质量" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="说明" prop="field115">-->
          <!--              <el-input v-model="formData.field115" placeholder="请输入说明" clearable :style="{width: '100%'}" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="6">-->
          <!--            <el-form-item label="是否监管" prop="is_supervise">-->
          <!--              <el-switch v-model="formData.is_supervise" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="4">-->
          <!--            <el-form-item label="是否称重" prop="is_weigh">-->
          <!--              <el-switch v-model="formData.is_weigh" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col v-for="item in extra_form" :key="item.id" :span="12">
            <el-form-item :label="item.name" :prop="item.name">
              <el-input v-model="formData[item.name]" :placeholder="'请输入' + item.name " clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div style="text-align: center">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="handelConfirm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  del,
  drug_list,
  get_durg_record,
  update,
  user_ban_confirm,
  user_ban_list,
  user_ban_relieve,
  set_drug_empty_bottle
} from '@/api/reagent/management'
import stringify from '@/utils/stringify'
import { get_use } from '@/api/reagent/customform'
export default {
  name: 'Management',
  data() {
    return {
      page: 1,
      page_size: 15,
      total: 0,
      recodeStatusMap: ['入库', '领用', '归还'],
      statusMap: ['在库', '出库', '空瓶'],
      statusColorMap: ['success', '', 'warning'],
      headerStyle: { 'background': '#E6E6E6' },
      client_id: null,
      name: null,
      multipleSelection: [],
      tableData: [],
      loading: true,
      //  查看流转记录
      dialogHistoryVisible: false,
      loadingHistory: false,
      historyData: [],
      history_page: 1,
      history_page_size: 15,
      history_total: 0,
      // 分配禁用用户
      dialogUserVisible: false,
      loadingUser: false,
      seach_user: '',
      userData: [],
      user_page: 1,
      user_page_size: 15,
      user_total: 0,
      multipleUserSelection: [],
      // 编辑试剂
      formData: {
        medicament_id: undefined,
        name: undefined,
        english_name: undefined,
        bar_code: undefined,
        cas_number: undefined,
        purity: undefined,
        shelf_life: undefined,
        production_date: '14:09:53',
        expiration_date: null,
        // use_days_warning_value: undefined,
        // shelf_life_warning_value: undefined,
        // inventory_warning_value: undefined,
        speci: undefined,
        net_weight_unit: undefined,
        net_weight: undefined
        // field115: undefined,
        // is_supervise: undefined,
        // is_weigh: undefined
      },
      rules: {
        name: [{
          required: true,
          message: '请输入试剂名称',
          trigger: 'blur'
        }],
        english_name: [],
        bar_code: [],
        cas_number: [{
          required: true,
          message: '请输入CAS码',
          trigger: 'blur'
        }],
        purity: [{
          required: true,
          message: '请输入试剂纯度',
          trigger: 'blur'
        }],
        shelf_life: [{
          required: true,
          message: '请输入保质期',
          trigger: 'blur'
        }],
        production_date: [{
          required: true,
          message: '请选择生产日期',
          trigger: 'change'
        }],
        expiration_date: [{
          required: true,
          message: '请选择过期日期',
          trigger: 'change'
        }],
        // use_days_warning_value: [{
        //   required: true,
        //   message: '请输入出库预警天数',
        //   trigger: 'blur'
        // }],
        // shelf_life_warning_value: [{
        //   required: true,
        //   message: '请输入保质期预警天数',
        //   trigger: 'blur'
        // }],
        // inventory_warning_value: [{
        //   required: true,
        //   message: '请输入预警量',
        //   trigger: 'blur'
        // }],
        speci: [],
        net_weight_unit: [],
        net_weight: []
        // field115: [],
        // is_supervise: [],
        // is_weigh: []
      },
      dialogEditVisible: false,
      extra_form: []
    }
  },
  created() {
    get_use().then(res => {
      this.extra_form = res.data
      this.getList()
    })
  },
  methods: {
    // 获取试剂列表
    getList() {
      this.loading = true
      const data = {
        page: this.page,
        page_size: this.page_size,
        client_id: this.client_id,
        seach_word: this.name
      }
      drug_list(stringify(data)).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total_count
      }).finally(() => { this.$refs['table'].doLayout(); this.loading = false })
    },

    // 获取流转记录列表
    getHistoryList() {
      this.loadingHistory = true
      const data = {
        page: this.history_page,
        page_size: this.history_page_size,
        medicament_id: this.multipleSelection[0].medicament_id
      }
      get_durg_record(stringify(data)).then(res => {
        this.historyData = res.data.data_list
        this.history_total = res.data.total_count
      }).finally(() => { this.loadingHistory = false })
    },
    // 查看流转记录按钮click事件处理
    showHistory() {
      if (this.multipleSelection.length !== 1) {
        this.$message.warning('请选择一个试剂！')
        return
      }
      this.dialogHistoryVisible = true
      this.getHistoryList()
    },
    // 流转记录翻页
    HistoryPageChange(page) {
      this.history_page = page
      this.getHistoryList()
    },
    handleHistoryClose() {
      this.historyData = []
      this.history_page = 1
      this.history_total = 0
    },
    handleDel() {
      if (this.multipleSelection.length !== 1) {
        this.$message.warning('请选择一个试剂！')
        return
      }
      this.$confirm('此操作将永久删除该试剂, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          medicament_id: this.multipleSelection[0].medicament_id
        }
        del(stringify(data)).then(res => {
          this.$message.success(res.msg)
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 设置空瓶
    handleSetEmpty() {
      if (this.multipleSelection.length !== 1) {
        this.$message.warning('请选择一个试剂！')
        return
      }
      const data = {
        medicament_id: this.multipleSelection[0].medicament_id
      }
      set_drug_empty_bottle(stringify(data)).then(res => {
        this.$message.success(res.msg)
        this.getList()
      })
    },
    // 刷新按钮
    handleRefresh() {
      this.getList()
    },
    // 选择试剂
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 试剂展示翻页
    pageChange(page) {
      this.page = page
      this.getList()
    },
    // 分配禁用用户 翻页
    userPageChange(page) {
      this.getUserList()
    },
    // 用户多选
    handleUserSelectionChange(val) {
      this.multipleUserSelection = val
    },
    // 分配禁用用户按钮点击事件处理
    handleDisable() {
      if (this.multipleSelection.length !== 1) {
        this.$message.warning('请选择一个试剂！')
        return
      }
      this.getUserList()
      this.dialogUserVisible = true
    },
    getUserList() {
      const data = {
        drug_id: this.multipleSelection[0].variety_id,
        page: this.user_page,
        page_size: this.user_page_size,
        seach_user: this.seach_user
      }
      this.loadingUser = true
      user_ban_list(stringify(data)).then(res => {
        this.userData = res.data.data
        this.user_total = res.data.total_count
      }).finally(() => { this.loadingUser = false })
    },
    handleDisUser() {
      if (this.multipleUserSelection.length !== 1) {
        this.$message.warning('请选择一个用户！')
        return
      }
      const data = {
        user_id: this.multipleUserSelection[0].user_id,
        drug_id: this.multipleSelection[0].variety_id
      }
      user_ban_confirm(stringify(data)).then(res => {
        if (res.status === 0) {
          this.$message.success(res.msg)
          this.getUserList()
        }
      })
    },

    handleEnUser() {
      if (this.multipleUserSelection.length !== 1) {
        this.$message.warning('请选择一个用户！')
        return
      }
      const data = {
        user_id: this.multipleUserSelection[0].user_id,
        drug_id: this.multipleSelection[0].variety_id
      }
      user_ban_relieve(stringify(data)).then(res => {
        if (res.status === 0) {
          this.$message.success(res.msg)
          this.getUserList()
        }
      })
    },

    // 编辑
    handleEdit() {
      if (this.multipleSelection.length !== 1) {
        this.$message.warning('请选择一个需要编辑的试剂！')
        return
      }
      // 给form赋值
      const row = this.multipleSelection[0]
      Object.keys(this.formData).forEach(item => {
        this.formData[item] = row[item]
      })
      this.formData.is_supervise = this.formData.is_supervise === 1
      this.formData.is_weigh = this.formData.is_weigh === 1
      this.dialogEditVisible = true
    },
    onClose() {
      this.dialogEditVisible = false
      this.$refs['elForm'].resetFields()
    },
    handelConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        const data = JSON.parse(JSON.stringify(this.formData))
        data.is_supervise = data.is_supervise ? 1 : 0
        data.is_weigh = data.is_weigh ? 1 : 0
        update(stringify(data)).then(res => {
          this.$message.success(res.msg)
          this.getList()
        })
        this.onClose()
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.main-container-text{
  min-height:calc(100vh - 110px) ;
  padding: 1rem;
  margin: 1rem;
  background: white;
  .title{
    font-size: 20px;
    font-weight: bold;
    color: #000000;
  }
  .header{
    margin: 1rem 0 1rem 0;
    .el-input{
      width: 12.5rem;
      margin-right: 1rem;
    }
    .el-select {
      margin-right: 1rem;
    }
    .header-right{
      float: right;
    }
  }
}

.user-header {
  margin-bottom: 1rem;
  .el-input{
    width: 150px;
    margin-right: 1rem;
  }
}

</style>
