<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb
        v-if="this.$route.query.type == 1"
        :crumbs="crumbs"
      ></bread-crumb>
      <bread-crumb
        v-if="this.$route.query.type == 2"
        :crumbs="crumbs2"
      ></bread-crumb>

      <div style="float:right;">
        <el-button size="small" @click="back()" class="filter-item"
          >取 消</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="submit()"
          class="filter-item"
          >保 存</el-button
        >
      </div>
    </div>

    <div class="app-container">
  

      <!-- <drugs-stock-dialog
        ref="dialog" :propForm="propForm"
        :visibility="isVisibility"
        v-on:dialog-comfirm="comfirm"
        v-on:dialog-cancle="cancle"
      ></drugs-stock-dialog> -->


      <div class="cell clearfix">
        <label class="title"><span class="name">出库时间</span> : </label>
        <el-date-picker
          size="small"
          v-model="warehouse_out_time"
          prefix-icon="el-icon-date"
          :editable="false"
          style="width: 200px;"
          type="date"
          placeholder="选择日期时间"
          align="right"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </div>

    
      <el-form :rules="tableRules" :model="recordInfo" ref="tableForm">
        <el-table
          :data="recordInfo.recordData"
          :class="signAndWeighBoxPatients"
          style="width: 100%"
          border
          max-height="450"
          :header-cell-style="{ backgroundColor: 'rgb(245, 247, 250)' }"
        >
          <el-table-column align="center" width="200" fixed="left">
            <template slot="header" slot-scope="scope">
              <span>药品名称<span style="color: red">*</span></span>
            </template>

            <template slot-scope="scope">
              <el-form-item style="padding-top: 20px">
                <el-autocomplete
                    class="checkSearch"
                    popper-class="my-autocomplete"
                    v-model="scope.row.drug_name"
                    :fetch-suggestions="querySearchAsync"
                    :trigger-on-focus="true"
                    placeholder="请输入药品名称"
                    @select="handleSelect"
                    @input="changeGoodName(scope.$index)"
                    style="width:160px;"
                  >
                    <i class="el-icon-search el-input__icon" slot="suffix"></i>
                  <template slot-scope="{ item }">
                    <div class="name">{{ item.drug_name + item.dose + item.dose_unit + "*" +item.min_number + item.min_unit +"/" + item.max_unit + " " + item.manufacturer}}</div>
                  </template>
                 </el-autocomplete>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" width="140">
            <template slot="header" slot-scope="scope">
              <span>药品类型</span>
            </template>
             <template slot-scope="scope">
               <el-select v-model="scope.row.drug_type" filterable placeholder="请选择厂商">
                <el-option
                  v-for="(option, index) in drugTypeList"
                  :key="index"
                  :label="option.name"
                  :value="option.id">
                </el-option>
               </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" width="140">
            <template slot="header" slot-scope="scope">
              <span>规格&单位<span style="color: red">*</span></span>
            </template>
            <template slot-scope="scope">
              <el-form-item style="padding-top: 20px">
                <el-input
                  :disabled="true"
                  placeholder="请输入规格&单位"
                  v-model="scope.row.name"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" width="150">
            <template slot="header" slot-scope="scope" >
                  <span>批号</span>
              </template>
                <template slot-scope="scope">
                  <el-form-item style="padding-top: 20px">
                    <!-- <el-input
                      placeholder="请输入批号"
                      v-model="scope.row.batch_number"
                    ></el-input> -->
                    <el-select v-model="scope.row.batch_number" filterable placeholder="请选择">
                      <el-option
                        v-for="(item,index) in numberList"
                        :key="index"
                        :label="item.batch_number"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
              </template>
          </el-table-column>
          <el-table-column width="200" align="center">
            <template slot="header" slot-scope="scope">
              <span>出库数量<span style="color: red">*</span></span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordData.' + scope.$index + '.count'"
                :rules="tableRules.count"
                style="padding-top: 20px"
              >
                <div style="display:flex;">
                  <el-input
                     oninput="value=value.replace(/\D|^0/g,'')"
                    style="width:80px"
                    placeholder="请输入出库数量"
                    type="number"
                    v-model="scope.row.count"
                  ></el-input>
                  <el-select v-model="scope.row.max_unit" filterable placeholder="请选择单位" style="width:80px">
                    <el-option
                      v-for="(option, index) in unitList"
                      :key="index"
                      :label="option.name"
                      :value="option.name">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
              
            </template>

          </el-table-column>
          <el-table-column width="120" align="center">
            <template slot="header" slot-scope="scope">
              <span>出货价<span style="color: red">*</span></span>
            </template>
            <template slot-scope="scope">
            
              <el-form-item
                :prop="'recordData.' + scope.$index + '.price'"
                :rules="tableRules.price"
                style="padding-top: 20px"
              >
                <el-input
                  placeholder="请输入出货价"
                  type="number"
                  v-model="scope.row.price"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="总价" width="80" align="center">
            <template slot-scope="scope">
              {{ calculate(scope.row.price * scope.row.count) }}
            </template>
          </el-table-column>
   
          <el-table-column label="生产厂家" width="140" align="center">
            <template slot-scope="scope">
               <el-select v-model="scope.row.manufacturer" filterable placeholder="请选择厂商">
                <el-option
                  v-for="(option, index) in manufacturerList"
                  :key="index"
                  :label="option.manufacturer_name"
                  :value="option.id">
                </el-option>
               </el-select>
            </template>
          </el-table-column>
 

          <el-table-column label="生产日期" width="180" align="center">
            <template slot-scope="scope">
              <el-date-picker
                prefix-icon="el-icon-date"
                style="width: 145px"
                v-model="scope.row.product_date"
                type="date"
                placeholder="选择日期时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="有效日期" width="180" align="center">
            <template slot-scope="scope">
              <el-date-picker
                prefix-icon="el-icon-date"
                style="width: 145px"
                v-model="scope.row.expiry_date"
                type="date"
                placeholder="选择日期时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </template>
          </el-table-column>
        
        <el-table-column align="center" width="150" label="批准文号">
            <template slot-scope="scope">
              <el-form-item style="padding-top: 20px" :disabled="true">
                <el-input
                  placeholder="请输入批准文号"
                  v-model="scope.row.number"
                ></el-input>
              </el-form-item>
            </template>
        </el-table-column>

         <el-table-column label="经销商" width="140" align="center">
            <template slot-scope="scope">
               <el-select v-model="scope.row.dealer" filterable placeholder="请选择厂商">
                <el-option
                  v-for="(option, index) in dealerList"
                  :key="index"
                  :label="option.dealer_name"
                  :value="option.id">
                </el-option>
               </el-select>
            </template>
          </el-table-column>

          <el-table-column label="备注" width="120" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="150" fixed="right">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="新增"
                placement="top"
              >
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-circle-plus-outline"
                  @click="handleEdit(scope.$index, scope.row)"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top"
              >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.$index, scope.row)"
                >
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
  </div>
</template>

<script>
import { uParseTime } from "@/utils/tools";
import {  postDrugWarehouseOut,GetAllConfig,GetAllDrugInfoByID,getDrugBatchNumber } from "@/api/drug/drug_stock";

import BreadCrumb from "../../components/bread-crumb";
import DrugsStockDialog from './drugsStockDialog/index'
import { getDataConfig,getDictionaryDataConfig } from "@/utils/data";
import {postSearchDrugList} from "@/api/data"
export default {
  components: { DrugsStockDialog,   BreadCrumb },
  name: "salesReturnOrderAdd",

  data() {
    return {
      crumbs: [
        { path: false, name: "库存管理" },
        { path: false, name: "药品出库单" },
        { path: false, name: "新增出库单" }
      ],
      crumbs2: [
        { path: false, name: "库存管理" },
        { path: false, name: "其他出库单" },
        { path: false, name: "新增出库单" }
      ],
      type: this.$route.query.type,
      signAndWeighBoxPatients: "sign-and-weigh-box-patients",
      warehouse_out_time: "",
      currentIndex: 0,
      recordInfo: {
        recordData: []
      },
      tableRules: {
        price: [{ required: true, message: "单价不能为空", trigger: "blur" }],
        count: [{ required: true, message: "数量不能为空", trigge: "blur" }],
        min_unit:[{required:true,message:"单位不能为空",trigge:"blur"}]
      },
      ruleForm: {
        manufacturer: [
          { required: true, message: "请选择厂商", trigger: "change" }
        ]
      },
      // prop
      isVisibility: false,
      propForm: {
        goods: [],
        goodType: [],
        goodInfo: [],
        goodUnit: [],
        manufacturer: 0,
        dealer: 0
      },
      form: {
        manufacturer: 0,
        dealer: 0
      },
      warehouseInfoList: [],
      manufacturer: [],
      dealer: [],
      goodType: [],
      goodInfo:[],
      drugList:[],
      manufacturerList:[],
      dealerList:[],
      showOne:true,
      showTwo:false,
      drugTypeList:[],
      totalPrice:0,
      unitList:[],
      numberList:[]
    };
  },
  methods: {
    
    cancle: function() {
      this.$refs.dialog.hide();
    },
    GetConfigInfo: function() {

      GetAllConfig().then(response => {
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });

        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.manufacturer = response.data.data.manufacturer;
          this.dealer = response.data.data.dealer;
          for(let i = 0; i<  response.data.data.drugs.length;i++){
            this.goodType.push(response.data.data.drugs[i])
            if(response.data.data.drugs[i].drug_specs != null) {
              for (let b = 0; b < response.data.data.drugs[i].drug_specs.length; b++) {
                this.goodInfo.push(response.data.data.drugs[i].drug_specs[b])
              }
            }
          }
          this.manufacturer.splice(0, 0, { id: 0, manufacturer_name: "全部" });
          this.dealer.splice(0, 0, { id: 0, dealer_name: "全部" });

          this.form.manufacturer = 0
          this.form.dealer = 0
        }
        loading.close()

      });
    },
    typeName: function(drug_id) {
    
      let name = "";
      for (let i = 0; i < this.goodInfo.length; i++) {
        if (this.goodInfo[i].id == drug_id) {
          name = this.goodInfo[i].drug_name;

        }
      }
      return name;
    },
     specificationName: function(drug_id) {
      let name = "";
      for (let i = 0; i < this.goodInfo.length; i++) {
        if (this.goodInfo[i].id == drug_id) {
          name = this.goodInfo[i].drug_spec;
        }
      }
      return name;
    },
    handleEdit: function(index, row) {
      const tempObj = {};
      tempObj["drug_id"] = 0;
      tempObj["count"] = "";
      tempObj["price"] = "";
      tempObj["retail_price"] = "";
      tempObj["remark"] = "";
      tempObj["min_unit"] = "";
      tempObj['dose'] = ""
      tempObj['dose_unit'] = ""
      tempObj["min_number"] = ""
      tempObj["number"] = ""
      tempObj["batch_number"] = ""
      tempObj["max_unit"] = ""
      tempObj["warehouse_info_id"] = 0
      this.recordInfo.recordData.push(tempObj);
    },
    handleDelete: function(index, row) {
      if (this.recordInfo.recordData.length <= 1) {
        this.$message.error("只有一条记录的时候无法删除");
        return;
      } else {
        this.recordInfo.recordData.splice(index, 1);
      }
    },
    calculate: function(val) {
      if (isNaN(val)) {
        return "";
      }
      if (val == 0) {
        return "";
      }
      return Math.round(parseFloat(val) * 100) / 100;
    },
    getTime(val, temp) {
      if (val != 0) {
        return uParseTime(val, temp);
      } else {
        return "";
      }
    },
    showDialog(index, row) {
      
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.currentIndex = index
      const params = {
        manufacturer_id: this.form.manufacturer,
        dealer_id: this.form.dealer
      }
      GetAllDrugInfoByID(params).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
            loading.close()

          } else {
            loading.close()

            if (response.data.data.drugs.length <= 0) {
              this.$message.error('该厂商或经销商没有物品信息')
              return
            }


            this.$refs.dialog.show()
            for (let i = 0; i < response.data.data.drugs.length; i++) {
              this.propForm.goods.push(
                response.data.data.drugs[i]
              );
            }
            const obj = {};
            this.propForm.goods = this.propForm.goods.reduce(
              (cur, next) => {
                obj[next.id] ? "" : (obj[next.id] = true && cur.push(next));
                return cur;
              },
              []
            ); // 设置cur默认类型为数组，并且初始值为空的数组


          }

        for (let i = 0; i < this.propForm.goods.length; i++) {
          for (let a = 0; a < this.propForm.goods[i].drug_specs.length; a++) {
            var respObj = this.propForm.goods[i].drug_specs[a];
            respObj["isSelected"] = false;
          }
        }
        }
      )

    },
    back() {
      this.$router.go(-1);
    },
    submit() {
      this.$refs["tableForm"].validate(valid => {
        if (valid) {
          const array = this.recordInfo.recordData;
          let total = 0;
          for (let i = 0; i < array.length; i++) {
            if (array[i].drug_id == 0) {
              this.$message.error("药品名称或者药品规格名称不能为空");
              return;
            }
            total = total + array[i].price * array[i].return_count;
          }
          if (this.recordInfo.recordData.length <= 0) {
            this.$message.success("请添加出库商品");
            return;
          }
          for(let i=0;i<this.recordInfo.recordData.length;i++){
            this.recordInfo.recordData[i].price = this.recordInfo.recordData[i].price.toString()

            for(let j=0;j<this.manufacturerList.length;j++){
              if(this.recordInfo.recordData[i].manufacturer == this.manufacturerList[j].manufacturer_name){
                  this.recordInfo.recordData[i].manufacturer =  this.manufacturerList[j].id
              }
              
            }
             if(this.recordInfo.recordData[i].dealer == ""){
                this.recordInfo.recordData[i].dealer = 0
             }
            for(let z=0;z<this.dealerList.length;z++){
              if(this.recordInfo.recordData[i].dealer == this.dealerList[z].dealer_name){
                  this.recordInfo.recordData[i].dealer = this.dealerList[z].id
              }
            }

            for(let y=0;y<this.numberList.length;y++){
              if(this.recordInfo.recordData[i].batch_number == this.numberList[y].id){
                this.recordInfo.recordData[i].batch_number = this.numberList[y].batch_number
                this.recordInfo.recordData[i].warehouse_info_id = this.numberList[y].id
              }
            }
          }
          const params = {
            stockOut: this.recordInfo.recordData
          };
          console.log("params222222",params)
        
          postDrugWarehouseOut(
            params,
            this.warehouse_out_time,
            this.form.dealer,
            this.form.manufacturer,
            this.type
          ).then(response => {
            if (response.data.state == 0) {
              this.$message.error("库存不足");
              return false;
            } else {
              var msg = response.data.data.msg
              var drug_name =  response.data.data.drug_name
              console.log("drug_name",drug_name)
              var dose = response.data.data.dose
              console.log("dose",dose)
              var dose_unit = response.data.data.dose_unit
              console.log("dose_unit",dose_unit)
              var min_number = response.data.data.min_number
              console.log("min_number",min_number)
              var min_unit =  response.data.data.min_unit
              console.log("min_unit",min_unit)
              var max_unit =  response.data.data.max_unit
              console.log("max_unit",max_unit)
              var str = drug_name + " " + dose + dose_unit + "*" + min_number + min_unit+"/"+max_unit
              console.log("str22222222",str)
              if(msg == 1){
                this.$message.error(str + "库存不足,请入库")
              }else{
                this.$message.success("出库成功");
                this.recordInfo.recordData = [];
                this.$router.back(-1);
              }
              
            }
          });
        } else {
          return false;
        }
      });
    },
    changeManufacturer(val) {
      this.propForm.manufacturer = val;
    },
    changeDealer(val) {
      this.propForm.goods = []
      this.propForm.dealer = val;
      this.form.dealer = val
     
    },
    getDataConfig(module, filed_name){
     return getDataConfig(module, filed_name)
    },
    querySearchAsync(keyword, cb) {
        let key = '';
        if (keyword != undefined) {
          key = keyword
        }
        let searchArray = [];
        postSearchDrugList(key).then(response => {
          if (response.data.state == 1) {
            searchArray = response.data.data.list;
             var list = response.data.data.list
             console.log("list99999999",list)
             this.drugList = list
             var manufacturerList = response.data.data.manufacturerList
             this.manufacturerList = manufacturerList
             var dealerList = response.data.data.dealerList
             this.dealerList = dealerList
             console.log("经销商",this.dealerList)
             for(let i=0;i<this.drugList.length;i++){
                for(let j=0;j<this.manufacturerList.length;j++){
                  if(this.drugList[i].manufacturer == this.manufacturerList[j].id){
                     this.drugList[i].manufacturer = this.manufacturerList[j].manufacturer_name
                  }
                }
               for(let z=0;z<dealerList.length;z++){
                  if(this.drugList[i].dealer == this.dealerList[z].id){
                      this.drugList[i].dealer = this.dealerList[z].dealer_name
                  }
               
                }
             }

             cb(this.drugList)
          } else {
            cb([])
          }
        })
      },
      changeGoodName(val){
        this.currentIndex = val
      },
      handleSelect(val){
        console.log("val2222222",val)
         this.getDrugBatchNumber(val.id)
        for(let i=0;i<this.recordInfo.recordData.length;i++){
          if(this.currentIndex == i){
            this.recordInfo.recordData[i].drug_id = val.id
            this.recordInfo.recordData[i].drug_name = val.drug_name
            this.recordInfo.recordData[i].drug_type = val.drug_type
            this.recordInfo.recordData[i].dose = val.dose
            this.recordInfo.recordData[i].dose_unit = val.dose_unit
            this.recordInfo.recordData[i].max_unit = val.max_unit
            this.recordInfo.recordData[i].min_number = val.min_number
            this.recordInfo.recordData[i].min_unit = val.min_unit
         
            this.recordInfo.recordData[i].number = val.number
            if(val.retail_price == 0){
              this.recordInfo.recordData[i].price = ""
            }else{
              this.recordInfo.recordData[i].price = val.retail_price
            }
           
            this.recordInfo.recordData[i].manufacturer = val.manufacturer
            this.recordInfo.recordData[i].name = this.recordInfo.recordData[i].dose + this.recordInfo.recordData[i].dose_unit + "*" + this.recordInfo.recordData[i].min_number + this.recordInfo.recordData[i].min_unit + "/"+this.recordInfo.recordData[i].max_unit
          
            if(val.dealer == 0){
               this.recordInfo.recordData[i].dealer = ""
            }else{
               this.recordInfo.recordData[i].dealer = val.dealer
            }
          }
        }
      }, 
      getDictionaryDataConfig(module, filed_name) {
        return getDictionaryDataConfig(module, filed_name)
      },
      getDrugBatchNumber(id){
          var params = {
            id:id
          }
        getDrugBatchNumber(params).then(response=>{
           if(response.data.state == 1){
             var list = response.data.data.list
             console.log("list2222",list)
             this.numberList = list
           }
        })
      }
  },
  created() {
    this.drugTypeList = getDictionaryDataConfig('system','drug_type') 
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth() + 1;
    var nowDay = nowDate.getDate();
    this.warehouse_out_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    const tempObj = {};
    tempObj["drug_id"] = 0;
    tempObj['max_unit'] = ''
    tempObj['min_unit'] = '',
    tempObj["return_count"] = 0;
    tempObj["price"] = "";
    tempObj["remark"] = "";
    tempObj['manufacturer'] = ''
    tempObj['batch_number'] = ''
    tempObj['drug_type'] = ''
    tempObj['dose'] = ""
    tempObj['dose_unit'] = ""
    tempObj["min_number"] = ""
    tempObj["dealer"] = ""
    tempObj["number"] = ""
    tempObj["warehouse_info_id"] = 0
    this.recordInfo.recordData.push(tempObj);
    this.GetConfigInfo();
    this.propForm.goodUnit = this.$store.getters.good_unit;
    this.unitList =  getDataConfig('hemodialysis','units')
    console.log("单位",this.unitList)
  }
};
</script>

<style rel="stylesheet/css" lang="scss" scoped>
.information {
  border: 1px #dcdfe6 solid;
  padding: 30px 20px 30px 20px;

  .border {
    border-bottom: 1px #dcdfe6 solid;
    margin: 0px 0 20px 0;
  }
}

.edit_separater {
  border-top: 1px solid rgb(233, 233, 233);
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>

<style>
.sign-and-weigh-box .sign-and-weigh-box-patients .cell {
  font-size: 12px;
}

.sign-and-weigh-box .sign-and-weigh-box-patients .current-row > td {
  background: #6fb5fa;
}
.el-autocomplete-suggestion{
  width: 400px !important;
}
</style>
