<template>
  <div class="main-content-container">
    <div class="header">
      <div class="title">试剂入库</div>
      <div class="header-select">
        <!--        <el-button>返回上一级</el-button>-->
        <el-select v-model="client_id" clearable placeholder="请选择柜体" @change="getTmpList">
          <el-option
            v-for="item in $store.getters.clientOptions"
            :key="item.id"
            :label="item.client_name"
            :value="item.client_id"
          />
        </el-select>
        <el-button type="primary" @click="handleReagentToDatabase">选择试剂入库</el-button>
        <el-button type="primary" @click="handleBindToDB">绑定入库</el-button>
        <el-button type="primary" plain @click="handleAddTmp('add')">+ 新增试剂模板</el-button>
        <el-button @click="handleAddTmp('modify')"><i class="el-icon-edit" />编辑试剂模板</el-button>
        <el-button><i class="el-icon-printer" /> 打印模板条码</el-button>
        <el-button><i class="el-icon-folder-add" /> 导入入库模板</el-button>
        <div class="right">
          <el-button icon="el-icon-delete" circle @click="handleDelTem" />
          <el-button icon="el-icon-refresh" circle @click="handleRefresh" />
        </div>
      </div>
    </div>
    <div class="content">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        element-loading-text="拼命加载中"
        :header-cell-style="headerStyle"
        :data="tableData"
        style="width: 100%"
        size="medium"
        stripe
        @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="template_name"
          label="模板名称"
          sortable
          align="center"
        />
        <el-table-column
          prop="client_name"
          label="所处位置"
          sortable
          align="center"
        />
        <el-table-column
          align="center"
          prop="all_export_count"
          label="入库数量"
        />
        <el-table-column
          align="center"
          prop="create_date"
          label="创建时间"
        />
        <el-table-column
          align="center"
          prop="create_user_name"
          label="创建人"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          align="center"
          width="180"
          prop="template_content"
          label="详情信息"
        />
      </el-table>
    </div>
    <div class="page my-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page.sync="page"
        :total="total"
        :page-size.sync="page_size"
        @current-change="tmpPageChange"
      />
    </div>
    <!--    选择试剂入库 弹框 -->
    <el-dialog title="选择试剂入库" width="70%" :close-on-click-modal="false" :visible.sync="dialogTableVisible" @close="handleSelectClose">
      <div class="search-header">
        <el-input v-model="selectReagentValue" clearable placeholder="请输入搜索试剂名称" />
        <el-button type="primary" icon="el-icon-search" @click="searchReagent">搜索</el-button>
      </div>
      <el-table
        v-loading="loadingReagent"
        element-loading-text="拼命加载中"
        :header-cell-style="headerStyle"
        :data="reagentData"
        stripe
        height="400"
      >
        <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="试剂编码" />
        <el-table-column align="center" property="manufacturer" label="生产厂家" />
        <el-table-column align="center" property="purity" label="纯度" />
        <el-table-column align="center" property="cas_number" label="CAS码" />
        <el-table-column align="center" property="production_date" label="生产日期" />
        <el-table-column align="center" property="shelf_life" label="保质期(天)" />
        <el-table-column
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button type="primary" @click="handleReagentClick(scope.row)">操作</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="my-pagination" style="text-align: right">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page.sync="reagent_page"
          :total="reagent_total"
          :page-size.sync="reagent_page_size"
          @current-change="reagentPageChange"
        />
      </div>
      <el-dialog
        width="53%"
        title="编辑试剂信息"
        :close-on-click-modal="false"
        :visible.sync="formVisible"
        append-to-body
        @close="formClose"
      >
        <ReagentForm :propsformdata="propsformdata" @handlefunc="handleReagentForm" />
      </el-dialog>
    </el-dialog>
    <!-- 新增试剂模板弹框   -->
    <el-dialog :title="opTitle" width="70%" :close-on-click-modal="false" :visible.sync="reagentAddVisible" @close="handleAddClose">
      <div class="header-select">
        <el-input v-model="reagentAddTmpName" placeholder="请输入模板名称" />
        <el-select v-model="reagentAddClient" placeholder="请选择柜体">
          <el-option
            v-for="item in $store.getters.clientOptions"
            :key="item.id"
            :label="item.client_name"
            :value="item.client_id"
          />
        </el-select>
        <el-button v-if="opType === 'add'" type="primary" plain @click="handleADDOpen('add')">+ 新增试剂条目</el-button>
        <el-button @click="handleADDOpen('modify')"><i class="el-icon-edit" />编辑试剂条目</el-button>
        <el-button v-if="opType === 'add'" @click="handleADDDEL"><i class="el-icon-delete" /> 删除试剂条目</el-button>
      </div>
      <div class="content">
        <el-table
          ref="multipleTable"
          :header-cell-style="headerStyle"
          :data="reagentAddTmpData"
          style="width: 100%"
          size="medium"
          height="400"
          @selection-change="handleAddSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" property="name" label="试剂名称" />
          <el-table-column align="center" property="english_name" label="英文名称" />
          <el-table-column align="center" property="purity" label="纯度" />
          <el-table-column align="center" property="cas_number" label="CAS码" />
          <el-table-column align="center" property="manufacturer" label="生产厂家" />
          <el-table-column align="center" property="speci" label="规格" />
          <el-table-column align="center" property="net_weight_unit" label="单位" />
          <el-table-column align="center" property="total" label="预估质量" />
          <el-table-column align="center" property="production_date" label="生产日期" />
          <el-table-column align="center" property="shelf_life" label="保质期(天)" />
        </el-table>
        <div class="reagent-add">
          <el-button @click="() => {reagentAddVisible= false;handleAddClose()}">取消</el-button>
          <el-button type="primary" @click="handleAddSave">保存</el-button>
        </div>
      </div>
      <el-dialog
        width="53%"
        :close-on-click-modal="false"
        :title="reagentAddFormTitle"
        :visible.sync="reagentAddFormVisible"
        append-to-body
        @close="reagentAddFormClose"
      >
        <ReagentForm :propsformdata="reagentAddFormdata" @handlefunc="handleReagentAddForm" />
      </el-dialog>
    </el-dialog>
    <!--    绑定入库-->
    <el-dialog title="绑定入库" width="70%" :close-on-click-modal="false" :visible.sync="bindToDBVisible" @close="handleCloseToDB">
      <div class="to-database">
        <div class="bind-to-db-title">请扫描试剂条码</div>
        <div>
          <el-select v-model="client_id_input" placeholder="请选择柜体">
            <el-option
              v-for="item in $store.getters.clientOptions"
              :key="item.id"
              :label="item.client_name"
              :value="item.client_id"
            />
          </el-select>
        </div>
      </div>
      <el-table
        ref="singleTable"
        :header-cell-style="headerStyle"
        :data="bindToDBData"
        height="400"
        highlight-current-row
        @current-change="handleCurrentSelectChange"
      >
        <el-table-column align="center" property="name" label="试剂名称" />
        <el-table-column align="center" property="bar_code" label="试剂编码" />
        <el-table-column align="center" property="manufacturer" label="生产厂家" />
        <el-table-column align="center" property="purity" label="纯度" />
        <el-table-column align="center" property="cas_number" label="CAS码" />
        <el-table-column align="center" property="production_date" label="生产日期" />
        <el-table-column align="center" property="shelf_life" label="保质期(天)" />
        <el-table-column align="center" property="status" label="状态">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status ? 'success' : 'danger' "
              disable-transitions
            >{{ scope.row.status ? "已入库" :"未入库" }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <Scanner @getcode="getCode" />
  </div>
</template>

<script>
import ReagentForm from '@/components/ReagentForm/index'
import Scanner from '@/components/Scannner/index'
import { show_tmp, select_drug, bind_tmp_enter_warehouse, add_tmp, del_tmp } from '@/api/reagent/warehousing'
import stringify from '@/utils/stringify'
import { throttle } from '@/utils'
export default {
  name: 'Warehousing',
  components: { ReagentForm, Scanner },
  data() {
    return {
      dialogTableVisible: false,
      headerStyle: { 'background': '#E6E6E6' },
      tableData: [],
      client_id: '',
      selectReagentValue: '',
      multipleSelection: [],
      loading: true,
      // 模板翻页信息
      page: 1,
      page_size: 15,
      total: 0,
      // 试剂翻页信息
      loadingReagent: true,
      reagentData: [],
      reagent_page: 1,
      reagent_page_size: 15,
      reagent_total: 0,
      // dialog form相关
      formVisible: false,
      propsformdata: {},

      // 新增 编辑 试剂模板
      opType: null,
      opTitle: '',
      reagentAddVisible: false,
      reagentAddTmpName: '',
      reagentAddClient: null,
      reagentAddTmpData: [],
      reagentAddSelection: [],
      reagentAddFormdata: {},
      reagentAddModifyIndex: null, // 确定第几个修改了
      reagentAddFormVisible: false,
      reagentAddFormTitle: '',

      // 绑定入库
      bindToDBVisible: false,
      bindToDBData: [],
      barCode: '',
      currentRow: null,
      client_id_input: ''
    }
  },
  watch: {
    // 如果 `barCode` 发生改变，这个函数就会运行
    // 扫码后提交后台并自动选择下一行
    barCode: function(newCode, oldCode) {
      if (newCode) {
        if (!this.client_id_input) {
          this.$message.warning('请选择存储柜体！')
          return
        }
        const data = JSON.parse(JSON.stringify(this.currentRow))
        const id = data.index
        delete data.status
        delete data.index
        bind_tmp_enter_warehouse(stringify({
          'tmplate_content': JSON.stringify(data),
          'bar_code': newCode,
          'client_id': this.client_id_input
        })).then(res => {
          if (res.status === 0) {
            this.bindToDBData[id].status = true
            this.$message.success('入库成功！')
            // 判断是否是最后一行，不是最后一行自动选择下一行
            if (id < this.bindToDBData.length - 1) {
              // 将下一行自动选中
              this.$refs.singleTable.setCurrentRow(this.bindToDBData[id + 1])
            }
          } else {
            this.$message.error('入库失败，请重试！')
          }
        })
      }
    }
  },
  created() {
    this.client_id = this.$store.getters.clientOptions[0].client_id
    this.getTmpList()
  },
  methods: {
    handleCloseToDB() {
      this.client_id_input = ''
    },
    formClose() {
      this.propsformdata = {}
    },
    handleCurrentSelectChange(row) {
      this.currentRow = row
    },
    // getCode
    getCode(code) {
      this.barCode = code
    },
    // 选择模板
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 处理删除模板
    handleDelTem() {
      if (this.multipleSelection.length > 0) {
        this.$msgbox.confirm(`确定要删除模板${this.multipleSelection.map(item => item.template_name).join('、')}吗？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del_tmp(stringify({ 'template_id_list': JSON.stringify(this.multipleSelection.map(item => item.template_id)) })).then(
            res => {
              if (res.status === 0) {
                this.$message.success('删除成功！')
                this.getTmpList()
              }
            }
          )
        })
      } else {
        this.$message.warning('请先选择模板')
      }
    },
    // 处理刷新
    handleRefresh() {
      this.getTmpList()
    },
    // 选择试剂入库搜索药物
    searchReagent() {
      this.reagentPageChange(1)
    },
    getTmpList() {
      this.loading = true
      show_tmp({
        page: this.page,
        page_size: this.page_size,
        client_id: this.client_id
      }).then(res => {
        this.tableData = res.data.data_list
        this.total = res.data.total_count
      }).finally(() => { this.loading = false })
    },
    // 模板页翻页
    tmpPageChange(page) {
      this.page = page
      this.getTmpList()
    },
    // 试剂入库信息翻页
    reagentPageChange(page) {
      this.reagent_page = page
      const data = { seach_word: this.selectReagentValue, page: this.reagent_page, page_size: this.reagent_page_size }
      this.getSelectDrug(stringify(data))
    },
    // 选择试剂
    handleReagentClick(row) {
      this.propsformdata = row
      this.formVisible = true
    },
    // 处理ReagentForm 转绑定入库
    handleReagentForm(obj) {
      this.formVisible = false
      this.bindToDBData = []
      for (let i = 0; i < obj.num; i++) {
        this.bindToDBData.push({ ...this.propsformdata, ...obj, 'status': false, 'index': i })
      }
      this.client_id_input = obj.client_id
      // 自动选择第一行数据
      this.$nextTick(() => {
        this.$refs.singleTable.setCurrentRow(this.bindToDBData[0])
      })
      this.bindToDBVisible = true
    },
    // 处理选择试剂入库弹框关闭后数据留存问题
    handleSelectClose() {
      this.bindToDBData = []
      this.selectReagentValue = ''
    },
    // 请求select_drug
    getSelectDrug(data) {
      this.loadingReagent = true
      this.reagentData = []
      select_drug(data).then(res => {
        this.reagentData = res.data.data_list
        this.reagent_total = res.data.total_count
      }).finally(() => { this.loadingReagent = false })
    },
    handleReagentToDatabase() {
      this.dialogTableVisible = true
      this.getSelectDrug({ page: this.reagent_page, page_size: this.reagent_page_size })
    },
    // 新增试剂模板
    handleAddTmp(t) {
      // / 新增 编辑 试剂模板
      // opType: null,
      //   opTitle: '',
      this.opType = t
      if (t === 'add') {
        this.opTitle = '新增试剂模板'
        if (this.multipleSelection.length === 0) {
          this.reagentAddVisible = true
        } else if (this.multipleSelection.length === 1) {
          const data = this.multipleSelection[0]
          this.reagentAddTmpName = data.template_name
          this.reagentAddClient = data.client_id
          this.reagentAddTmpData = JSON.parse(data.template_content)
          this.reagentAddVisible = true
        } else {
          this.$message.warning('请选择一个模板！')
        }
      } else {
        this.opTitle = '编辑试剂模板'
        if (this.multipleSelection.length === 1) {
          const data = this.multipleSelection[0]
          this.reagentAddTmpName = data.template_name
          this.reagentAddClient = data.client_id
          this.reagentAddTmpData = JSON.parse(data.template_content)
          this.reagentAddVisible = true
        } else {
          this.$message.warning('请选择一个模板！')
        }
      }
    },
    // 处理新增试剂模板 弹框关闭清理工作
    handleAddClose() {
      this.reagentAddTmpName = ''
      this.reagentAddClient = null
      this.reagentAddTmpData = []
      this.client_id_input = ''
    },
    handleAddSave: throttle(function() {
      if (!this.reagentAddTmpName) {
        this.$message.warning('请输入模板名称！')
        return
      }
      if (!this.reagentAddClient) {
        this.$message.warning('请选择存储柜体！')
        return
      }
      const data = stringify({ 'template_name': this.reagentAddTmpName, 'template_content': JSON.stringify(this.reagentAddTmpData), 'client_id': this.reagentAddClient })
      add_tmp(data).then(
        res => {
          if (res.status === 0) {
            this.$message.success('操作成功')
            this.handleAddClose()
            this.reagentAddVisible = false
          } else {
            this.$message.success('操作失败，请重试！')
          }
        }
      )
    }, 2000),
    // 处理新增 新增试剂条目 弹框打开
    handleADDOpen(t) {
      if (t === 'add') {
        this.reagentAddFormTitle = '新增模板条目'
      } else {
        if (this.reagentAddSelection.length !== 1) {
          this.$message.warning('请选择需要编辑的模板条目！')
          return
        }
        // 查找修改第几个
        this.reagentAddModifyIndex = this.reagentAddTmpData.find(item => this.reagentAddSelection[0] === item)
        this.reagentAddFormdata = this.reagentAddSelection[0]
        this.reagentAddFormTitle = '编辑模板条目'
      }
      this.reagentAddFormVisible = true
    },
    handleADDDEL() {
      this.reagentAddTmpData = this.reagentAddTmpData.filter(item => !this.reagentAddSelection.includes(item))
    },
    // 处理新增 条目form
    handleReagentAddForm(obj) {
      if (this.reagentAddFormTitle === '新增模板条目') {
        this.reagentAddTmpData.push(obj)
      } else {
        // 修改
        this.reagentAddTmpData[this.reagentAddModifyIndex] = { ...this.reagentAddTmpData[this.reagentAddModifyIndex], ...obj }
      }
      this.reagentAddFormVisible = false
    },
    reagentAddFormClose() {
      this.reagentAddFormdata = {}
    },
    // handleAddSelectionChange
    handleAddSelectionChange(val) {
      this.reagentAddSelection = val
    },
    // 绑定入库
    handleBindToDB() {
      if (this.bindToDBData.length === 0 && this.multipleSelection.length === 0) {
        this.$message.warning('请选择入库试剂或模板！')
        return
      }
      this.bindToDBData = []
      this.multipleSelection.forEach(item => {
        this.bindToDBData.push(...JSON.parse(item.template_content).map((item, index) => {
          item.status = false
          item.index = index
          return item
        }))
      })
      if (this.multipleSelection.length === 1) {
        this.client_id_input = this.multipleSelection[0].client_id
      }
      // 自动选择第一行数据
      this.$nextTick(() => {
        this.$refs.singleTable.setCurrentRow(this.bindToDBData[0])
      })
      this.bindToDBVisible = true
    }

  }
}
</script>

<style lang="scss" scoped>
.main-content-container{
  margin: 1rem;
  background: white;
  min-height: calc(100vh - 110px);
  .header{
    margin: 1rem;
    .title{
      font-size: 20px;
      font-weight: bold;
      color: #000000;
      padding-top: 1rem ;
    }
    .header-select{
      margin-top: 1rem;
      .el-select{
        margin-left: 0;
      }
      .right{
        float: right;
      }
    }
  }
  .content{
    margin: 1rem;
  }
  .page{
    position: absolute;
    bottom: 2rem;
    text-align: center;
    left: 50%;    //起始是在body中，横向距左50%的位置
    transform:translate(-50%);
  }
}
.el-select{
  margin: 0rem 1rem 0rem 1rem;
}
.el-input{
  width: 14.9375rem;
  margin-right: 1rem;
}
.search-header{
  margin-bottom: 1rem;
}
.bind-to-db-title{
  font-size: 1rem;
  font-weight: 400;
  color: #FF9B02;
  margin-bottom: 1rem;
}

.reagent-add{
  text-align: center;
  margin-top: 1rem;
}
.to-database{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}
</style>
