<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs='crumbs'></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">

    <!--<sales-return-dialog ref="dialog" :propForm="propForm"-->
                     <!--:visibility="isVisibility"-->
                     <!--v-on:dialog-comfirm="comfirm"-->
                     <!--v-on:dialog-cancle="cancle"></sales-return-dialog>-->
    <!--<stock-in-dialog-->
      <!--ref="dialog"-->
      <!--:propForm="propForm"-->
      <!--:visibility="isVisibility"-->
      <!--v-on:dialog-comfirm="comfirm"-->
      <!--v-on:dialog-cancle="cancle"-->
    <!--&gt;</stock-in-dialog>-->

    <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="return_time" prefix-icon="el-icon-date" :editable="false" style="width: 196px;"
                            type="date" placeholder="选择日期时间" align="right" format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"></el-date-picker>
    </div>


    <div class="cell clearfix">
      <label class="title"><span class="name">经销商</span> : </label>
      <el-select size="small" v-model="form.dealer" clearable placeholder="请选择经销商" @change="changeDealer">
        <el-option
          v-for="(option, index) in dealer"
          :key="index"
          :label="option.dealer_name"
          :value="option.id">
        </el-option>
      </el-select>
    </div>


    <div class="cell clearfix">
      <label class="title"><span class="name">厂商</span> : </label>

      <el-select size="small" v-model="form.manufacturer" clearable placeholder="请选择厂商" @change="changeManufacturer">
        <el-option
          v-for="(option, index) in manufacturer"
          :key="index"
          :label="option.manufacturer_name"
          :value="option.id">
        </el-option>
      </el-select>
    </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">
              <template slot="header" slot-scope="scope">
                <span>药品名称<span style="color: red">*</span></span>
              </template>

              <template slot-scope="scope">
                <el-form-item style="padding-top: 15px">
                  <el-input
                    placeholder="请输入药品名称"
                    v-model="scope.row.drug_id"
                    :value="typeName(scope.row.drug_id)"
                    @focus="showDialog(scope.$index, scope.row)"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" width="200">
              <template slot="header" slot-scope="scope">
                <span>规格名称<span style="color: red">*</span></span>
              </template>
              <template slot-scope="scope">
                <el-form-item style="padding-top: 15px">
                  <el-input
                    placeholder="请输入规格名称"
                    v-model="scope.row.drug_id"
                    :value="specificationName(scope.row.drug_id)"
                    @focus="showDialog(scope.$index, scope.row)"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" width="150">
              <template slot="header" slot-scope="scope">
                <span>进价<span style="color: red">*</span></span>
              </template>
              <template slot-scope="scope">
                <!--<el-input type="number" v-model="scope.row.price"  @blur="handleBlur(scope.$index, scope.row)"></el-input>-->
                <el-form-item
                  :prop="'recordData.' + scope.$index + '.price'"
                  :rules="tableRules.price"
                  style="padding-top: 17px"
                >
                  <el-input
                    placeholder="请输入进价"
                    type="number"
                    v-model="scope.row.price"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="进货总价" align="center" width="80">
              <template slot-scope="scope">
                {{ calculate(scope.row.price * scope.row.count) }}
              </template>
            </el-table-column>



            <el-table-column min-width="23" 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: 17px">
                  <el-input  placeholder="请输入退货数量" type="number" v-model="scope.row.count"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="零价" align="center" width="80">
              <template slot-scope="scope">
                {{ scope.row.retail_price }}
              </template>
            </el-table-column>

            <el-table-column label="零价总价" align="center" width="80">
              <template slot-scope="scope">
                {{ calculate(scope.row.retail_price * scope.row.count) }}
              </template>
            </el-table-column>


            <el-table-column label="操作" align="center" min-width="20">
              <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 {
    GetAllConfig,
    deleteDrugSalesReturnInfo,
    getDrugReturnList,
    getDrugSalesReturnConfig,
    editDrugSalesReturnInfo,
    GetAllDrugInfoByID
  } from '@/api/drug/drug_stock'
  import BreadCrumb from '../../components/bread-crumb'
  // import StockInDialog from './Dialog/stockInDialog'
  import DrugsStockDialog from './drugsStockDialog/index'

  export default {
    components: { DrugsStockDialog, BreadCrumb },
    name: 'salesReturnEdit',

    data() {
      return {
        crumbs: [
          { path: false, name: '库存管理' },
          { path: '/stock/return', name: '退货单' },
          { path: '/stock/in/detail', name: '编辑退货单' }
        ],
        signAndWeighBoxPatients: 'sign-and-weigh-box-patients',
        warehousing_time: '',
        adminUserOptions: null,
        currentIndex: 0,
        return_time: '',
        recordInfo: {
          recordData: [],
          stock_in_code: '',
          current_index: ''

        },
        tableRules: {
          count: [
            { required: true, message: '数量不能为空', trigge: 'blur' }
          ]

        },


        // prop
        isVisibility: false,
        propForm: {
          goods:[],
          goodType: [],
          goodInfo: [],
          goodUnit: [],
          title: '入库',
          manufacturer:0,
          dealer:0,
        },

        form: {
          manufacturer: 0,
          dealer: 0,
        },
        warehouseInfoList:[],
        salesReturn: {},
        manufacturer: [],
        dealer: [],
        goodType: [],
        goodInfo:[]
      }
    },
    methods: {
      comfirm: function(val) {
        this.$refs.dialog.hide()
        if (val.selectedGoodInfo.length > 0) {
          for (let i = val.selectedGoodInfo.length -1; i >= 0 ; i--) {
            if (i == 0) {
              this.recordInfo.recordData[this.currentIndex].drug_id = val.selectedGoodInfo[i].id
              this.recordInfo.recordData[this.currentIndex].price = val.selectedGoodInfo[i].last_price.toString()
              this.recordInfo.recordData[this.currentIndex].retail_price = val.selectedGoodInfo[i].retail_price.toString()

            } else {
              const tempForm = {}
              tempForm['id'] = 0
              tempForm['drug_id'] = val.selectedGoodInfo[i].id
              tempForm['count'] = ''
              tempForm['price'] = val.selectedGoodInfo[i].last_price.toString()
              tempForm['retail_price'] = val.selectedGoodInfo[i].retail_price.toString()
              this.recordInfo.recordData.splice(this.currentIndex + 1, 0, tempForm)
            }
          }
        }
        this.propForm.goodType = []
        this.currentIndex = -1
      }, cancle: function() {
        this.$refs.dialog.hide()

      },
      GetConfigInfo: function() {
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        GetAllConfig().then(response => {
          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: "全部" });
          }
          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) {
        console.log(this.goodInfo)
        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['id'] = 0
        tempObj['drug_id'] = 0
        tempObj['count'] = ''
        tempObj['price'] = ''
        tempObj['retail_price'] = ''
        this.recordInfo.recordData.push(tempObj)
      }, handleDelete: function(index, row) {
        console.log(row.id)
        if (row.id == undefined || row.id == 0) {
          this.recordInfo.recordData.splice(index, 1)
        } else {
          const params = {
            id: row.id
          }
          this.$confirm('确认删除该退货商品信息记录?', '删除退货商品信息记录', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteDrugSalesReturnInfo(params).then(response => {
              if (response.data.state == 0) {
                this.$message.error(response.data.msg)
                return false
              } else {
                this.$message.success('删除成功')
                this.recordInfo.recordData.splice(index, 1)
              }
            })
          }).catch(() => {
          })
        }
      }, getTime(val, temp) {
        if (val != 0) {
          return uParseTime(val, temp)
        } else {
          return ''
        }
      },calculate: function(val) {
        if (val == 0) {
          return ''
        }

        return Math.round(parseFloat(val) * 100) / 100
      },
      showDialog(index, row) {
        this.currentIndex = index;
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });

        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;
          } else {
            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;
            }
          }
          loading.close();
        });
      },
      back() {
        this.$router.go(-1)
      }, submit() {
        this.$refs['tableForm'].validate((valid) => {
          if (valid) {
            const array = this.recordInfo.recordData
            for (let i = 0; i < array.length; i++) {

              if (array[i].drug_id == 0) {
                this.$message.error('药品名称或者药品规格名称不能为空')
                return
              }
            }

            const params = {
              'salesReturn': this.recordInfo.recordData
            }
            editDrugSalesReturnInfo(params, this.return_time, this.$route.query.id, this.$route.query.type,this.form.manufacturer,this.form.dealer).then(response => {
              if (response.data.state == 0) {
                this.$message.error(response.data.msg)
                return false
              } else {
                this.$message.success('退货成功')

                this.$router.back(-1)
              }
            })
          } else {
            return false
          }
        })
      }, GetOrderDetail: function(order_id) {
        const params = {
          'id': order_id
        }
        getDrugReturnList(params).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            for (let i = 0; i < response.data.data.list.length; i++) {
              response.data.data.list[i].count = response.data.data.list[i].count.toString()
              response.data.data.list[i].price = response.data.data.list[i].price.toString()
              response.data.data.list[i].retail_price = response.data.data.list[i].retail_price.toString()

              this.recordInfo.recordData.push(response.data.data.list[i])
            }
            this.salesReturn = response.data.data.salesReturn
            this.return_time = this.getTime(this.salesReturn.return_time, '{y}-{m}-{d}')
            this.form.manufacturer = this.salesReturn.manufacturer
            this.form.dealer = this.salesReturn.dealer
          }

          if (this.recordInfo.recordData.length == 0) {
            const tempObj = {}
            tempObj['id'] = 0
            tempObj['drug_id'] = 0
            tempObj['count'] = ''
            tempObj['price'] = ''
            tempObj['retail_price'] = ''


            this.recordInfo.recordData.push(tempObj)
          }
        })
      },changeManufacturer(val) {
        this.propForm.manufacturer = val
        console.log(val)
      },changeDealer(val){
        this.propForm.dealer = val
        console.log(val)
      }
    },
    created() {
      this.GetConfigInfo()
      this.propForm.goodUnit = this.$store.getters.good_unit
      const order_id = this.$route.query.id
      this.GetOrderDetail(order_id)
    }

  }
</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;
  }

</style>
