<template>
  <div class="main-container-text">
    <div class="title">采购申请</div>
    <div class="header">
      <el-button type="primary" plain @click="openDialogTableVisible"><i class="el-icon-edit" />新建采购申请单</el-button>

      <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="adddialogVisible">
        <el-row :gutter="15">
          <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="110px">
          <el-col :span="12">
            <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="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="export_count">
              <el-input v-model="formData.export_count" 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-form>
      </el-row>
      <div style="text-align: center">
        <el-button type="primary" @click="handelConfirm">保存</el-button>
      </div>



        <el-table :data="checkList" max-height="250" style="height:250px;padding-bottom: 50px;">
          <el-table-column type="index" align="center"  width="50" label="序号" />
          <el-table-column prop="name" show-overflow-tooltip label="试剂名称" align="center" />
          <el-table-column prop="cas_number" show-overflow-tooltip label="CAS码" align="center" />
          <el-table-column prop="speci" show-overflow-tooltip label="规格" align="center" />
          <el-table-column prop="purity" show-overflow-tooltip label="纯度" align="center" />
          <el-table-column prop="net_weight_unit" show-overflow-tooltip label="单位" align="center" />
          <el-table-column prop="export_count" show-overflow-tooltip label="数量" align="center" />
          <el-table-column prop="net_weight" show-overflow-tooltip label="预估质量" align="center" />
          <el-table-column
            fixed="right"
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button @click="cancelClick(scope.row)" type="text" size="small">取消申请</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div slot="footer" style="text-align: center">
          <el-button @click="dialogTableClose">取消</el-button>
          <el-button type="primary" @click="create_apply">提交申请</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="撤销采购单申请"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
        <span>是否确认撤销</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="backcheck()">确 定</el-button>
        </span>
      </el-dialog>

      <div class="header-right">
        <el-button icon="el-icon-refresh" circle @click="handleRefresh" />
      </div>
    </div>
    <el-table
      stripe
      ref="multipleTable"
      :data="tableData"
      :header-cell-style="headerStyle"
      @select="handleSelection"
      row-key="medicament_id"
      height="69vh"
      class="table-style"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" type="index" width="50" label="序号" />
      <el-table-column prop="user_name" show-overflow-tooltip label="采购申请人" align="center" />
      <el-table-column prop="create_date" show-overflow-tooltip label="申请时间" align="center" />
      <el-table-column prop="is_solve" show-overflow-tooltip label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="statusColorMap[scope.row.is_solve]">{{ statusMap[scope.row.is_solve] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="solve_user_name" show-overflow-tooltip label="审批人1" align="center" />
      <el-table-column prop="solve_user_pt_name" show-overflow-tooltip label="审批人2" align="center" />
      <el-table-column prop="solve_date" show-overflow-tooltip label="审批时间" align="center" />
      <el-table-column prop="information" show-overflow-tooltip label="备注" align="center" />
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        width="250">
        <template slot-scope="scope">
          <el-button @click="handleCheck(scope.row)" type="text" size="small">修改申请单</el-button>
          <el-button @click="handback(scope.row)" type="text" size="small">撤销申请单</el-button>
          <el-button @click="handleExport(scope.row)" type="text" size="small">导出申请单</el-button>
        </template>
      </el-table-column>
    </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"
        @current-change="pageChange"
      />
    </div>
  </div>
</template>

<script>
import { throttle } from '@/utils'
import stringify from '@/utils/stringify'
import {
  get_list,
  add,
  update,
  solve,
  del
} from '@/api/reagent/purchase'
import { dowload,click_dowload } from '@/api/reagent/dowload_file'

export default {
  name: 'Buy',
  data() {
    return {
      page: 1,
      page_size: 10,
      total: 0,
      tableData: [],
      centerDialogVisible: false,
      adddialogVisible:false,
      row_id:'',
      formData: {
        name: '',
        cas_number: '',
        purity: '',
        export_count:'',
        speci: '',
        net_weight_unit: '',
        net_weight: ''
      },
      statusColorMap: ['warning','success','danger'],
      statusMap: ['未处理', '已处理','已驳回','已完成'],
      title:'',

      seach_word:'',
      client_id: '',
      dialogVisible: false,
      headerStyle: { 'background': '#E6E6E6' },
      multipleSelection: [],
      handleSelectionSelection: [],
      dialogHistoryVisible: false,
      loadingHistory: false,
      historyData: [],
      name: '',
      history_client_id: '',
      value1: '',
      value2: ['', ''],
      dialogTableVisible: false,
      checkList: [],
      rules: {
        name: [
          { required: true, message: '请输入试剂名称', trigger: 'change' }
        ],
        purity: [
          { required: true, message: '请输入试剂纯度', trigger: 'change' }
        ],
        export_count:[
          { required: true, message: '请输入数量', trigger: 'blur' },
          { 
            validator (rule, value, callback) {
              if (/(^[1-9]\d*$)/.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正整数'))
              }
            },
            trigger: 'blur'
          }
        ],
        speci: [
          { required: true, message: '请输入试剂规格', trigger: 'change' },
          { 
            validator (rule, value, callback) {
              if (/(^[1-9]\d*$)/.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正整数'))
              }
            },
            trigger: 'blur'
          }
        ],
        net_weight_unit: [
          { required: true, message: '请输入单位', trigger: 'change' }

        ],
        net_weight: [
          { required: true, message: '请输入预估质量', trigger: 'change' },
          { 
            validator (rule, value, callback) {
              if (/(^[1-9]\d*$)/.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正整数'))
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.get_drug_group()
  },
  methods: {
    //添加
    handelConfirm:function() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          this.checkList.push(this.formData)
          console.log(this.formData, '-----------------------')
        }
        if (!valid) return
      })
    }, 

    //获取采购单
    get_drug_group: function() {
      var that =this
      const data = {
        page:that.page,
        page_size: 10
      }
      get_list(stringify(data)).then(rsp => {
        console.log("rsp.data.data_list>>", rsp.data.data_list)
        this.tableData = this.addDataIndex(rsp.data.data_list)
        this.total = rsp.data.total_count
      })
    },
    //导出
    handleExport(row){
      const data = {
        id: row.id,
        file_name: '请购单'
      }
      this.recordLoading = true
      // 导出
      dowload(data).then(
        res => {
          this.$message.success(res.statusText)
          click_dowload(data, res)
        }
      ).finally(() => { this.recordLoading = false })
    },
    //撤销弹窗
    handback(row){
      this.row_id =row.id
      this.centerDialogVisible =true
    },
    //撤销
    backcheck(){
      this.recordLoading = true
      const data = {
        id: this.row_id,
      }
      // 撤销
      del(stringify(data)).then(
        res => {
          if (res.status ==0){
            this.centerDialogVisible =false
            this.$message.success(res.msg)
            this.get_drug_group()
          }else{
            this.$message.error(res.msg)
          }    
        }
      ).finally(() => { this.recordLoading = false })
    },
    //勾选
    handleSelection(selection){
      var that =this 
      that.handleSelectionSelection =selection
    },
    // 查看详情
    handleCheck(row) {
      this.title='编辑采购试剂'
      this.row_id =row.id
      if(row.is_solve==1 || row.is_solve==3){
        this.$message.error('已处理无法修改')
      }else{
        this.adddialogVisible = true
        this.checkList = JSON.parse(row.use_content) 
      }
      // if (this.handleSelectionSelection.length === 1) {
      //   this.dialogHistoryVisible = true
      //   this.historyData = JSON.parse(this.handleSelectionSelection[0].use_content) 
      // } else {
      //   this.$message.warning("选择一条记录操作！")
      // }
    },
    //取消试剂申请
    cancelClick(row){
      var that =this
      let getLocation = that.checkList.indexOf(row);
      that.checkList.splice(getLocation, 1)
    },
    //申请页翻页
    pageChange(page) {
      this.page = page
      this.get_drug_group()
    },
    addDataIndex(initData){
      for (let i = 0; i < initData.length; i++) {
        initData[i]["index"] = i
      }
      return initData
    },
    //申请
    handleRefresh() {
      this.page =1
      this.get_drug_group()
    },
    //打开申请列表
    openDialogTableVisible(){
      this.title='新增采购试剂'
      this.checkList=[]
      this.formData = {
        name: '',
        cas_number: '',
        purity: '',
        export_count:'',
        speci: '',
        net_weight_unit: '',
        net_weight: ''
      }
      this.adddialogVisible = true
    },
    //关闭申请列表
    dialogTableClose() {
      this.adddialogVisible = false
      this.checkList=[]
      this.formData = {
        name: '',
        cas_number: '',
        purity: '',
        export_count:'',
        speci: '',
        net_weight_unit: '',
        net_weight: ''
      }
    },
    //提交申请
    create_apply(){
      var that =this 
      let datalist = that.checkList.map((item) => {
        return Object.assign({}, {net_weight_unit: item.net_weight_unit, total: item.net_weight, name: item.name,value:item.name, cas_number: item.cas_number,purity: item.purity, remark6:'瓶',
          export_count: item.export_count, speci: item.speci,distributor:'',english_name:'',expiration_date:'',manufacturer:'',medicament_id:'',production_date:'',net_weight:'',shelf_life:''})
      })
      console.log(datalist,'5')
      if(datalist.length==0){
        this.$message.error('没有数据')
      }else{
        if(this.title=='编辑采购试剂'){
          const data = {
            id: this.row_id,
            use_content: JSON.stringify(datalist),
          }
          update(stringify(data)).then(rsp => {
            console.log("rsp>>", rsp)
            if (rsp.status==0){
              this.dialogTableClose()
              //清空表格多选框
              this.$refs.multipleTable.clearSelection();
              that.checkList=[]
              this.page =1
              this.get_drug_group()
            }
          })
        }else{
          const data = {
            use_doc: '',
            use_content: JSON.stringify(datalist),
          }
          add(stringify(data)).then(rsp => {
            console.log("rsp>>", rsp)
            if (rsp.status==0){
              this.dialogTableClose()
              //清空表格多选框
              this.$refs.multipleTable.clearSelection();
              that.checkList=[]
              this.page =1
              this.get_drug_group()
            }
          }) 
        }
      }
    },
  }
}
</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: 9.375rem;
      margin-right: 1rem;
    }

    .el-select {
      margin-right: 1rem;
    }

    .header-right {
      float: right;
    }
  }
}

.add-item {
  margin-bottom: 1rem;
}
</style>

<style>
/* 1,必须去掉scoped，否则overflow-x: hidden失效 */
.box {
  margin: 0 auto;
  width: 95%;
  height: 95%;
}

/* 2，外包一个div,来减少对其他页面会有冲突（此时缺少scoped） */
.box .el-scrollbar__wrap {
  overflow-x: hidden;
}
/* .el-dialog__body {
  height: 600px !important;
} */
</style>
