<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
      <el-button
        size="small"
        @click="AddNewOrder"
        class="filter-item"
        style="float:right;"
        type="primary"
        icon="el-icon-circle-plus-outline"
        >新增</el-button
      >
    </div>
    <div class="app-container">
      <div class="cell clearfix">
        <el-input
          size="small"
          style="width: 400px;"
          class="filter-item"
          v-model.trim="searchKey"
          placeholder="单据编码/制单人/耗材名称"
        />
        <el-button
          size="small"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
      </div>

      <div class="cell clearfix">
        <label class="title"><span class="name">出库时间</span> : </label>
        <el-date-picker
          size="small"
          v-model="start_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"
          @change="startTimeChange"
        ></el-date-picker>
        <span class="cellLine"> - </span>
        <el-date-picker
          size="small"
          v-model="end_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"
          @change="endTimeChange"
        ></el-date-picker>
      </div>

      <div class="cell clearfix">
        <el-checkbox
          style="width: 70px"
          v-model="checked"
          @change="changeAllSelected"
          >全选</el-checkbox
        >
        <el-button size="small" icon="el-icon-delete" @click="batchDelete">删除</el-button>
        <el-button size="small" type="primary" @click="toPrint">打印</el-button>
        <el-button size="small" type="primary" @click="toExport">导出</el-button>
      </div>

      <el-table
        :data="warehouseOutDate"
        :class="signAndWeighBoxPatients"
        style="width: 100%"
        border
        highlight-current-row
        ref="multipleTable"
        @selection-change="select"
        :row-style="{ color: '#303133' }"
        :header-cell-style="{
          backgroundColor: 'rgb(245, 247, 250)',
          color: '#606266'
        }"
       @current-change="handleSearch"
      >
        <el-table-column type="selection" width="55" align="center"> </el-table-column>

        <el-table-column label="单据日期" align="center">
          <template slot-scope="scope">
            {{ scope.row.warehouse_out_time | parseTime("{y}-{m}-{d}") }}
          </template>
        </el-table-column>

        <el-table-column label="单据编号" align="center">
          <template slot-scope="scope">
            {{ scope.row.warehouse_out_order_number }}
          </template>
        </el-table-column>

        <el-table-column label="制单人" align="center">
          <template slot-scope="scope">
            {{ getXuserName(scope.row.creater) }}
          </template>
        </el-table-column>

       <el-table-column label="出库方式" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_sys == 1">自动出库</span>
            <span v-if="scope.row.is_sys == 0">手动出库</span>
          </template>
        </el-table-column>
       

        <el-table-column label="操作" align="center" width="300px">
          <template slot-scope="scope">
           
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit-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"
                :disabled="scope.row.is_sys == 1"
                icon="el-icon-delete"
                @click="handleDelete(scope.$index, scope.row)"
              >
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5, 10, 50, 100]"
        :page-size="5"
        background
        style="margin-top:20px;text-align: right"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!--  详情 -->
      <div v-show="tableShow" style="margin-top:10px;">
        <el-table
            :data="tableList"
            :class="signAndWeighBoxPatients"
            style="width: 100%"
            border
            highlight-current-row
            ref="multipleTableOne"
            @selection-change="select"
            :row-style="{ color: '#303133' }"
            :header-cell-style="{
              backgroundColor: 'rgb(245, 247, 250)',
              color: '#606266'
            }"
          >
          <el-table-column label="耗材名称" align="center">
            <template slot-scope="scope">
              {{ scope.row.good_name }}
            </template>
          </el-table-column>
          <el-table-column label="耗材类型" align="center">
            <template slot-scope="scope">
              {{  getTypeName(scope.row.good_type_id)}}
            </template>
          </el-table-column>
          <el-table-column label="规格&单位" align="center">
            <template slot-scope="scope">
              {{ scope.row.specification_name}} / {{scope.row.packing_unit}}
            </template>
          </el-table-column>
          <!-- <el-table-column label="批号" align="center">
            <template slot-scope="scope">
              {{ scope.row.number}}
            </template>
          </el-table-column> -->
          <el-table-column label="出库数量" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.is_sys == 0">{{ scope.row.count}}{{scope.row.packing_unit}}</span> 
              <span v-if="scope.row.is_sys == 1">{{getOutStockCount(scope.row.good_id)}}{{scope.row.packing_unit}}</span> 
            </template>
          </el-table-column>
          <el-table-column label="出货价" align="center">
            <template slot-scope="scope">
              {{ scope.row.price}}
            </template>
          </el-table-column>
          <el-table-column label="总价" align="center">
            <template slot-scope="scope">
             <span v-if="scope.row.is_sys == 0">{{ (scope.row.count * scope.row.price).toFixed(2)}}</span> 
             <span v-if="scope.row.is_sys == 1">{{(getOutStockCount(scope.row.good_id)*scope.row.price).toFixed(2)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产厂家" align="center">
            <template slot-scope="scope">
              {{ getManufactuerName(scope.row.manufacturer)}}
            </template>
          </el-table-column>
          <el-table-column label="经销商" align="center">
            <template slot-scope="scope">
              {{getDealerName(scope.row.dealer) }}
            </template>
          </el-table-column>
          <el-table-column label="生产日期" align="center">
            <template slot-scope="scope">
              {{ getTime(scope.row.product_date,"{y}-{m}-{d}")}}
            </template>
          </el-table-column>
          <el-table-column label="有效期" align="center">
            <template slot-scope="scope">
              {{ getTime(scope.row.expiry_date,"{y}-{m}-{d}")}}
            </template>
          </el-table-column>
          <!-- <el-table-column label="批准文号" align="center">
            <template slot-scope="scope">
              {{ scope.row.license_number}}
            </template>
          </el-table-column> -->
          <el-table-column label="备注" align="center">
            <template slot-scope="scope">
              {{ scope.row.remark }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <span style="color: #589ff8" @click="GetOrderDetailById(scope.row)">使用明细</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>



  


    <!-- 新增弹窗 -->

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="80%"
     >
      <span>
        <div class="filter-container">
          <span style="font-size: 18px;color: #606266">出库单详情</span>
          <el-row style="float:right;">
            <span style="color: #606266">{{warehousingOutInfo.info.warehouse_out_order_number}}</span>
          </el-row>
        </div>

        <div class="cell clearfix">
          <span style="width: 300px;color: #606266">单据日期:  {{warehousingOutInfo.info.warehouse_out_time | parseTime('{y}-{m}-{d}')}} </span>
          <span style="width: 300px;color: #606266">厂商 {{getManufactuerName(warehousingOutInfo.info.manufacturer)}}</span>
          <span style="width: 300px;color: #606266">经销商 {{getDealerName(warehousingOutInfo.info.dealer)}}</span>
        </div>

        <div class="filter-container" style="margin-top: 10px">
         <el-button size="small" icon="el-icon-edit" @click="editRecord(warehousingOutInfo.info.id)" v-if="warehousingOutInfo.info.is_sys != 1">编辑</el-button>
         <el-button size="small" icon="el-icon-delete" @click="deleteRecord" v-if="warehousingOutInfo.info.is_sys != 1">删除</el-button>
        </div>


         <el-row :gutter="12" style="margin-top: 10px">
          <el-table :data="warehousingOutInfo.warehousingOutData" :class="signAndWeighBoxPatients" style="width: 100%"
                    border :header-cell-style="{ backgroundColor: 'rgb(245, 247, 250)'}"
                  
          >
            <el-table-column min-width="35" align="center">
              <template slot="header" slot-scope="scope">
                <span>耗材类型</span>
              </template>

              <template slot-scope="scope">
                <span v-if="scope.row.good_type_id != 0">{{getTypeName(scope.row.good_type_id)}}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="35" align="center">
              <template slot="header" slot-scope="scope">
                <span>耗材名称</span>
              </template>

              <template slot-scope="scope">
                <span v-if="scope.row.good_id != 0">{{getTypeNameOne(scope.row.good_id)}}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="35" align="center">
              <template slot="header" slot-scope="scope">
                <span>规格型号</span>
              </template>
              <template slot-scope="scope">
                <span v-if="scope.row.good_id != 0">{{getSpecificationName(scope.row.good_id)}}</span>
              </template>
            </el-table-column>


            <el-table-column min-width="23" align="center">
              <template slot="header" slot-scope="scope">
                <span>出货价</span>
              </template>
              <template slot-scope="scope">
                <span>{{scope.row.price}}</span>
              </template>
            </el-table-column>

            <el-table-column min-width="23" align="center">
              <template slot="header" slot-scope="scope">
                <span>出库数量</span>
              </template>
              <template slot-scope="scope">
               <span v-if="scope.row.is_sys == 0">{{scope.row.count}}</span>
               <span v-if="scope.row.is_sys == 1">{{getOutStockCount(scope.row.good_id)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="总价" min-width="20" align="center">
              <template slot-scope="scope">
                {{calculate(scope.row.price*scope.row.count)}}
              </template>
            </el-table-column>

            <el-table-column label="备注" min-width="20" align="center">
              <template slot-scope="scope">
                <el-popover placement="top-start" width="250" trigger="hover">
                  <div>{{scope.row.remark}}</div>
                  <span slot="reference"
                        v-if="scope.row.remark.length > 20">{{ scope.row.remark.substr(0,20)+'...' }}</span>
                  <span slot="reference" v-else>{{ scope.row.remark}}</span>
                </el-popover>

              </template>
            </el-table-column>

            <el-table-column label="" align="center"  >
              <template slot-scope="scope" v-if="scope.row.is_sys == 1">
              <div style="color: #589ff8" @click="GetOrderDetailThree(scope.row.id)">使用明细</div>
              </template>
            </el-table-column>
             


          </el-table>
      </el-row>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
   </el-dialog>


  <!-- 使用明细查询 -->
   <el-dialog
    title="出库单详情"
    :visible.sync="editdialogVisibleTwo"
    width="80%">
    <span>
      <div class="filter-container">
        <span style="font-size: 18px;color: #606266">商品使用明细</span>
      </div>
     
       <el-row :gutter="12" style="margin-top: 10px">
        <el-table :data="infoList" :class="signAndWeighBoxPatients" style="width: 80%"
                  border :header-cell-style="{ backgroundColor: 'rgb(245, 247, 250)'}"
        >
          <el-table-column min-width="35" align="center">
            <template slot="header" slot-scope="scope">
              <span>序号</span>
            </template>
            <template slot-scope="scope">
              {{scope.$index+1}}
            </template>
          </el-table-column>

          <el-table-column min-width="35" align="center">
            <template slot="header" slot-scope="scope">
              <span>使用人</span>
            </template>
            <template slot-scope="scope">
              系统
            </template>
          </el-table-column>
          <el-table-column min-width="35" align="center">
            <template slot="header" slot-scope="scope">
              <span>使用数量</span>
            </template>
            <template slot-scope="scope">
             {{scope.row.count}}
            </template>
          </el-table-column>
          <el-table-column min-width="35" align="center">
            <template slot="header" slot-scope="scope">
              <span>批次号</span>
            </template>
            <template slot-scope="scope">
               {{scope.row.number}}
            </template>
          </el-table-column>
          <el-table-column min-width="35" align="center">
            <template slot="header" slot-scope="scope">
              <span>使用时间</span>
            </template>
            <template slot-scope="scope">
              <span>{{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}} </span>
            </template>
          </el-table-column>

        </el-table>
      </el-row>
    </span>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editdialogVisibleTwo = false">取 消</el-button>
      <el-button type="primary" @click="editdialogVisibleTwo = false">确 定</el-button>
    </span>
  </el-dialog>
  


  <!-- 编辑 -->
   <el-dialog
      title="编辑出库单"
      :visible.sync="editDialogVisible"
      width="80%">
      <span>

        <div style="margin-bottom:10px">
          <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: 196px;" type="date" placeholder="选择日期时间" align="right" format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"></el-date-picker>
          <label class="title" style="margin-left:10px;"><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>
          <label class="title" style="margin-left:10px;"><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 min-width="35" align="center">

            <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.good_type_id"
                          :value="typeName(scope.row.good_type_id)"
                          @focus="showDialog(scope.$index, scope.row)"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          
          <el-table-column min-width="35" align="center">
            <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.good_id"
                          :value="specificationName(scope.row.good_id)"
                          @focus="showDialog(scope.$index, scope.row)"></el-input>
              </el-form-item>

            </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 + '.price'" :rules='tableRules.price'
                            style="padding-top: 17px">
                <el-input type="number" v-model="scope.row.price"></el-input>
              </el-form-item>
            </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 type="number" v-model="scope.row.count"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="总价" min-width="20" align="center">
            <template slot-scope="scope">
              {{calculate(scope.row.price*scope.row.count)}}
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="20" 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" min-width="30">
            <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="handleEditOne(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="handleDeleteOne(scope.$index, scope.row)">
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
  </el-dialog>
   
  
    <el-dialog
      title="出库明细"
      :visible.sync="editdialogVisibleThree"
      width="70%">
      <span>
         <div class="app-container">

      <div class="filter-container">
        <span style="font-size: 18px;color: #606266">商品使用明细</span>
      </div>

      <el-row :gutter="12" style="margin-top: 10px">
      <el-table :data="userList" :class="signAndWeighBoxPatients" style="width: 50%"
              border :header-cell-style="{ backgroundColor: 'rgb(245, 247, 250)'}">
          <el-table-column min-width="35" align="center">
            <template slot="header" slot-scope="scope">
              <span>序号</span>
            </template>
            <template slot-scope="scope">
              <span v-if="scope.row.is_total == 0">{{scope.$index+1}}</span>
              <span v-if="scope.row.is_total == 1">{{'合计'}}</span>
            </template>
          </el-table-column>

          <el-table-column min-width="35" align="center">
            <template slot="header" slot-scope="scope">
              <span>使用人</span>
            </template>
            <template slot-scope="scope">
              <span v-if="scope.row.is_total == 0">{{scope.row.user.name}}</span>
              <span v-if="scope.row.is_total == 1"></span>
            </template>
          </el-table-column>
          <el-table-column min-width="35" align="center">
            <template slot="header" slot-scope="scope">
              <span>使用数量</span>
            </template>
            <template slot-scope="scope">
              <span v-if="scope.row.is_total == 0">{{scope.row.count}}{{scope.row.info.packing_unit}}</span>
              <span  v-if="scope.row.is_total == 1">{{scope.row.total}} </span>

            </template>
          </el-table-column>
          <el-table-column min-width="60" align="center">
            <template slot="header" slot-scope="scope">
              <span>使用时间</span>
            </template>
            <template slot-scope="scope">
              <span>{{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}} </span>

            </template>
          </el-table-column>
         <el-table-column min-width="70" align="center">
            <template slot="header" slot-scope="scope">
              <span>批次号</span>
            </template>
            <template slot-scope="scope">
              <span v-if="scope.row.is_total == 0">{{getNumber(scope.row.id)}}</span>
            </template>
          </el-table-column>
<!-- 
          <el-table-column min-width="70" align="center">
            <template slot="header" slot-scope="scope">
              <span>批次详情</span>
            </template>
            <template slot-scope="scope">
              <span v-if="scope.row.is_total == 0">批次详情</span>
            </template>
          </el-table-column> -->
        </el-table>
      </el-row>
    </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisibleThree = false">取 消</el-button>
        <el-button type="primary" @click="editdialogVisibleThree = false">确 定</el-button>
      </span>
    </el-dialog>

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

  
  </div>
</template>

<script>
import { uParseTime } from "@/utils/tools";
import { fetchAllAdminUsers, fetchAllDoctorAndNurse } from "@/api/doctor";

import {
  deleteWarehouseOut,
  GetAllConfig,
  getWarehouseOutList,
  getWarehouseOutInfo,
  getWarehouseOutUser,
  GetOutStockTotalCount,
  deleteWarehouseOutInfo,
  GetAllGoodInfoByID,
  editWarehouseoutInfo,
  getOrderDetailByOrderId,
  getOrderDetailById,
  getOutExportList
} from "@/api/stock";
import BreadCrumb from "../components/bread-crumb";
import StockInDialog from './Dialog/stockInDialog'

export default {
  name: "salesReturnOrder",
  components: { StockInDialog, BreadCrumb},
  created() {
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth() + 1;
    var nowDay = nowDate.getDate();
    this.end_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    nowDate.setMonth(nowDate.getMonth() - 1);
    nowYear = nowDate.getFullYear();
    nowMonth = nowDate.getMonth() + 1;
    nowDay = nowDate.getDate();

    this.start_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    this.GetConfigInfo();
    this.GetWarehouseOut();
    this.fetchAllAdminUsers();
    
    
  },
  data() {
     var checkGoodId = (rule, value, callback) => {
      setTimeout(() => {
        if (value == "" || value == 0) {
          return callback(new Error("规格名称不能为空"));
        }
      }, 2000);
    };
    return {
      searchKey: "",
      crumbs: [
        { path: false, name: "库存管理" },
        { path: false, name: "出库单" }
      ],
      page: 1,
      limit: 5,
      checked: false,
      total: 0,
      pageTotal: 0,
      pageSelect: 0,
      adminUserOptions: [],
      multipleSelection: [],
      signAndWeighBoxPatients: "sign-and-weigh-box-patients",
      start_time: "",
      warehouseOutDate: [],
      end_time: "",
      goodType: [],
      goodInfo: [],
      manufacturer: [],
      selectedTableData: [],
      dealer: [],
      type: 1,
      drug_id:0,
      dialogVisible:false,
      editdialogVisible:false,
      warehousingOutInfo: {
        loading: false,
        warehousingOutData: [],
        info: {}
      },
      userList:[],
      type_name:'',
      specification_name:"",
      stockCount:[],
      editDialogVisible:false,
      warehouse_out_time: '',
      form: {
          manufacturer: 0,
          dealer: 0
        },
       warehouseInfoList: [],
       tableRules: {
        price: [{ required: true, message: "单价不能为空", trigger: "blur" }],
        warehousing_count: [
          { required: true, message: "数量不能为空", trigge: "blur" }
        ],

        good_id: [{ validator: checkGoodId, trigger: "blur" }]
      },

      recordInfo: {
        recordData: [],
        stock_in_code: "",
        current_index: ""
      },
      propForm: {
        goods:[],
        goodType: [],
        goodInfo: [],
        goodUnit: [],
        title: '入库',
        manufacturer: 0,
        dealer: 0
      },
      isVisibility: false,
      good_type_id:"",
      tableShow:false,
      tableList:[],
      dialogVisibleTwo:false,
      userList:[],
      editdialogVisibleTwo:false,
      editdialogVisibleThree:false,
      order_id:"",
      warehouse_out_time:"",
      exportList:[],
      is_sys:0,
      infoList:[]
    };
  },
  methods: {
    search: function() {
      const Params = {
        page: this.page,
        limit: this.limit,
        start_time: this.start_time,
        end_time: this.end_time,
        type: this.type,
        keywords: this.searchKey
      };
      this.warehouseOutDate = [];
      getWarehouseOutList(Params).then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.total = response.data.data.total;
          for (let i = 0; i < response.data.data.list.length; i++) {
            this.warehouseOutDate.push(response.data.data.list[i]);
          }
        }
      });
    },
    AddNewOrder: function() {
      this.$router.push({
        name: "stockOutOrderAdd",
        query: { type: this.type }
      });
    },
    GetWarehouseOut: function() {
      const Params = {
        page: this.page,
        limit: this.limit,
        start_time: this.start_time,
        end_time: this.end_time,
        type: this.type
      };
      this.warehouseOutDate = [];
      getWarehouseOutList(Params).then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          console.log("parsm",response.data.data)
          
          this.total = response.data.data.total;
          for (let i = 0; i < response.data.data.list.length; i++) {
            
            this.warehouseOutDate.push(response.data.data.list[i]);
          }
          console.log("2222222",this.warehouseOutDate)
        }
      });
    },
    getXuserName(id) {
      if (id <= 0) {
        return "";
      }
      var name = "";
      if (
        this.adminUserOptions == null ||
        typeof this.adminUserOptions.length === "undefined"
      ) {
        return name;
      }
      var leng = this.adminUserOptions.length;
      if (leng == 0) {
        return name;
      }
      for (let index = 0; index < leng; index++) {
        if (this.adminUserOptions[index].id == id) {
          name = this.adminUserOptions[index].name;
          break;
        }
      }
      return name;
    },
    fetchAllAdminUsers() {
      fetchAllAdminUsers().then(response => {
        console.log(response);
        if (response.data.state == 1) {
          this.adminUserOptions = response.data.data.users;
          var alen = this.adminUserOptions.length;
          for (let index = 0; index < alen; index++) {
            if (this.adminUserOptions[index].user_type == 2) {
              // this.doctorOptions.push(this.adminUserOptions[index]);
            }
          }
        }
      });
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.limit = val;
      this.GetWarehouseOut();
      
    },
    handleCurrentChange(val) {
      this.page = val;
      this.GetWarehouseOut();
     
    },
    startTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.start_time = "";
      } else {
        this.GetWarehouseOut();
        this.getlist()
      }
     
    },
    endTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.end_time = "";
      } else {
        this.GetWarehouseOut();
        this.getlist()
      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    calculate: function(val) {
      return Math.round(parseFloat(val) * 100) / 100;
    },
    GetConfigInfo: function() {
      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;
          this.goodInfo = response.data.data.goodInfo
          this.goodType = response.data.data.goodType
          // this.manufacturer.splice(0, 0, { id: 0, manufacturer_name: "全部" });
          // this.dealer.splice(0, 0, { id: 0, dealer_name: "全部" });
          this.getlist()
        }
      });
    },
    getManufactuerName: function(manufacturer_id) {
      for (let i = 0; i < this.manufacturer.length; i++) {
        if (this.manufacturer[i].id == manufacturer_id) {
          return this.manufacturer[i].manufacturer_name;
        }
      }
    },
    getDealerName: function(dealer_id) {
      for (let i = 0; i < this.dealer.length; i++) {
        if (this.dealer[i].id == dealer_id) {
          return this.dealer[i].dealer_name;
        }
      }
    },
    handleEdit: function(index, row) {
      
      this.$router.push({path:'/stock/stockoutorderedit?id='+row.id+"&is_sys="+row.is_sys})
       
    },
    handleDelete: function(index, row) {
      const ids = [];
      ids.push(row.id);
      const idStr = ids.join(",");

      const params = {
        ids: idStr
      };

      this.$confirm("确认删除出库单记录?", "删除出库单记录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteWarehouseOut(params).then(response => {
            if (response.data.state == 0) {
              this.$message.error(response.data.msg);
              return false;
            } else {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                duration: 2000
              });
              for (let i = 0; i < ids.length; i++) {
                for (let y = 0; y < this.warehouseOutDate.length; y++) {
                  if (ids[i] == this.warehouseOutDate[y].id) {
                    this.warehouseOutDate.splice(y, 1);
                  }
                }
              }
            }
          });
        })
        .catch(() => {});
    },
    changeAllSelected: function(val) {
      if (val) {
        this.$refs.multipleTable.toggleAllSelection();
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    select(selection) {
      
      var ids = []
      for(let i=0;i<selection.length;i++){
        ids.push(selection[i].id)
      }
      console.log("ids",ids)
      this.exportList = []
      this.order_id = ids.join(",")
      this.warehouse_out_time = selection[0].warehouse_out_time
      this.selectedTableData = selection;
      this.getlist()

    },
    batchDelete() {
    
      if (this.selectedTableData.length <= 0) {
        this.$message.error("请选择要删除的记录");
        return;
      }
      const ids = [];
      for (let i = 0; i < this.selectedTableData.length; i++) {
         if(this.selectedTableData[i].is_sys == 0){
           ids.push(this.selectedTableData[i].id);
         }
      }
      const idStr = ids.join(",");
      const params = {
        ids: idStr
      };
      this.$confirm("确认删除出库单记录?", "删除出库单记录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteWarehouseOut(params).then(response => {
            if (response.data.state == 0) {
              this.$message.error(response.data.msg);
              return false;
            } else {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                duration: 2000
              });

              for (let i = 0; i < ids.length; i++) {
                for (let y = 0; y < this.warehouseOutDate.length; y++) {
                  if (ids[i] == this.warehouseOutDate[y].id) {
                    this.warehouseOutDate.splice(y, 1);
                  }
                }
              }
            }
          });
        })
        .catch(() => {});
    },


    handleSearch(val){
      this.tableList = []
    
      this.editdialogVisibleThree = false
      this.GetOrderDetailOne(val.id)
      this.GetTotalCount(val.warehouse_out_time)
    },
  
      GetOrderDetailOne(id){
        const params = {
          'id': id
        }
        getOrderDetailByOrderId(params).then(response=>{
            if(response.data.state == 1){
              this.tableShow = true
              var list = response.data.data.list
              console.log("list22222222",list)
              for(let i=0;i<list.length;i++){
                if(list[i].dealer == 0){
                  list[i].dealer = ""
                }
                if(list[i].manufacturer == 0){
                  list[i].manufacturer = ""
                }
                this.tableList.push(list[i])
              }
            }
        })
      },

      getTypeName: function(id) {
        let name = ''
        for (let i = 0; i < this.goodType.length; i++) {
          if (this.goodType[i].id == id) {
            name = this.goodType[i].type_name
          }
        }
        return name
      },

      getTypeNameOne: function(id) {
       let name = ''
        for (let i = 0; i < this.goodInfo.length; i++) {
          if (this.goodInfo[i].id == id) {
            name = this.goodInfo[i].good_name
          }
        }
        return name
      },

     getSpecificationName: function(id) {
        let name = ''
        for (let i = 0; i < this.goodInfo.length; i++) {
          if (this.goodInfo[i].id == id) {
            name = this.goodInfo[i].specification_name
          }
        }
        return name
      },
     getManufactuerName: function(manufacturer_id) {
        for (let i = 0; i < this.manufacturer.length; i++) {
          if (this.manufacturer[i].id == manufacturer_id) {
            return this.manufacturer[i].manufacturer_name
          }
        }
      }, 

    jump(id){
      this.userList = []
      this.GetOrderDetail(id)
     
    },

     GetOrderDetail: function(order_id) {
       this.userList = []
        const params = {
          'id': order_id
        }
        getWarehouseOutUser(params).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            var total = 0
            var list = response.data.data.list
            var arrList =  this.unique(list)
            for (let i = 0; i < arrList.length; i++) {
              var obj = arrList[i]
              obj['is_total'] = 0
              this.userList.push(obj)
              total = total + arrList[i].count
            }
            this.userList.push({
              is_total: 1,
              total: total,
            })
            // this.type_name = this.userList[0].type.type_name
            // this.specification_name = this.userList[0].info.specification_name
            console.log("详情数据区",this.userList)
            this.editdialogVisibleThree = true
          }
        })
      },

     
     deleteRecord: function() {
        const ids = []
        ids.push(this.warehousingOutInfo.info.id)
        const idStr = ids.join(',')

        const params = {
          ids: idStr
        }

        this.$confirm('确认删除出库单?', '删除出库单记录', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteWarehouseOut(params).then(response => {
            if (response.data.state == 0) {
              this.$message.error(response.data.msg)
              return false
            } else {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })

              this.$router.back(-1)
            }
          })
        }).catch(() => {
        })
      },

      GetTotalCount(time){
          var params = {
           warehouse_out_time:time
          }
        GetOutStockTotalCount(params).then(response=>{
           if(response.data.state == 1){
              var stockCount = response.data.data.stockCount
              console.log("出库数量2323",stockCount)
              this.stockCount = stockCount
              // this.dialogVisible = true
           }
        })
      },

     getOutStockCount(id){
         var count = 0 
         for(let i=0;i<this.stockCount.length;i++){
            if(id == this.stockCount[i].good_id){
              count = this.stockCount[i].count
            }
         }
         return count
     },

     unique(arr) {
        const res = new Map();
        return arr.filter((arr) => !res.has(arr.patient_id) && res.set(arr.patient_id, 1));
     },

    editRecord(id){
      this.warehouseOut= []
      this.recordInfo.recordData = []
      this.GetConfigInfo()
      this.GetOrderDetailTwo(id)
      this.good_type_id = id
    },

     GetOrderDetailTwo(order_id) {
        const params = {
          'id': order_id
        }
        console.log("触发了222222",order_id)
        getWarehouseOutInfo(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].price = response.data.data.list[i].price.toString()
              response.data.data.list[i].count = response.data.data.list[i].count.toString()
              this.recordInfo.recordData.push(response.data.data.list[i])
            }
            this.warehouseOut = response.data.data.info
            this.warehouse_out_time = this.getTime(this.warehouseOut.warehouse_out_time, '{y}-{m}-{d}')
            // this.form.manufacturer = this.warehouseOut.manufacturer
            // this.form.dealer = this.warehouseOut.dealer
            this.editDialogVisible = true
          }

          if (this.recordInfo.recordData.length == 0) {
            const tempObj = {}
            tempObj['id'] = 0
            tempObj['good_type_id'] = 0
            tempObj['good_id'] = 0
            tempObj['count'] = ''
            tempObj['price'] = ''
            tempObj['remark'] = ''
            this.recordInfo.recordData.push(tempObj)
            this.editDialogVisible = true
          }
        })
      },
     getTime(val, temp) {
        if (val != 0) {
          return uParseTime(val, temp)
        } else {
          return ''
        }
     },
     changeManufacturer(val) {
        this.propForm.manufacturer = val
      },
       changeDealer(val) {
        this.propForm.dealer = val
     },
      typeName: function(good_type_id) {
        let name = "";
        for (let i = 0; i < this.goodType.length; i++) {
          if (this.goodType[i].id == good_type_id) {
            name = this.goodType[i].type_name;
          }
        }
        return name;
      },
     specificationName: function(good_info_id) {
        let name = "";
        for (let i = 0; i < this.goodInfo.length; i++) {
          if (this.goodInfo[i].id == good_info_id) {
            name = this.goodInfo[i].specification_name;
          }
        }
        return name;
     }, 
     handleEditOne(){
        const tempObj = {}
        tempObj['id'] = 0
        tempObj['good_type_id'] = 0
        tempObj['good_id'] = 0
        tempObj['count'] = ''
        tempObj['price'] = ''
        tempObj['remark'] = ''
        this.recordInfo.recordData.push(tempObj)
     },
     handleDeleteOne: function(index, row) {
        if (row.id == 0) {
          this.recordInfo.recordData.splice(index, 1)
        } else {
          const params = {
            id: row.id
          }
          this.$confirm('确认删除该出库耗材信息记录?', '删除出库耗材信息记录', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteWarehouseOutInfo(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(() => {
          })
        }
      },
      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
        };
        this.propForm.goods = []

        GetAllGoodInfoByID(params).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg);
            return false;
          } else {
            if (response.data.data.goodInfo.length <= 0) {
              this.$message.error("该厂商或经销商没有物品信息");
              return;
            }
            this.$refs.dialog.show();
            for (let i = 0; i < response.data.data.goodInfo.length; i++) {
              this.propForm.goodType.push(
                response.data.data.goodInfo[i].type
              );
            }
            const obj = {};
            this.propForm.goodType = this.propForm.goodType.reduce(
              (cur, next) => {
                obj[next.id] ? "" : (obj[next.id] = true && cur.push(next));
                return cur;
              },
              []
            ); // 设置cur默认类型为数组，并且初始值为空的数组
          }

          for (let i = 0; i < this.propForm.goodType.length; i++) {
            let goodInfo = [];
            let goodObj = {};

            for (let a = 0; a < response.data.data.goodInfo.length; a++) {
              var respObj = response.data.data.goodInfo[a];
              respObj["isSelected"] = false;
              if (respObj.type.id == this.propForm.goodType[i].id) {
                goodInfo.push(respObj);
              }
            }
            const obj = {};
            goodInfo = goodInfo.reduce((cur, next) => {
              obj[next.id] ? "" : (obj[next.id] = true && cur.push(next));
              return cur;
            }, []); // 设置cur默认类型为数组，并且初始值为空的数组

            this.$set(goodObj, this.propForm.goodType[i].id, goodInfo);
            this.propForm.goods.push(goodObj);
          }
          loading.close();
        });
      },
     
      comfirm: function(val) {
        this.$refs.dialog.hide();
        this.propForm.goodType = [];
        this.propForm.goods = [];

        if (val.selectedGoodInfo.length > 0) {
          for (let i = val.selectedGoodInfo.length - 1; ; i--) {
            if (i == 0) {
              this.recordInfo.recordData[this.currentIndex].good_type_id =
                val.selectedGoodInfo[i].good_type_id;
              this.recordInfo.recordData[this.currentIndex].good_id =
                val.selectedGoodInfo[i].id;
              this.recordInfo.recordData[
                this.currentIndex
                ].price = val.selectedGoodInfo[i].buy_price.toString();
            } else {
              const tempForm = {};
              tempForm["id"] = 0;
              tempForm["good_type_id"] = val.selectedGoodInfo[i].good_type_id;
              tempForm["good_id"] = val.selectedGoodInfo[i].id;
              tempForm["count"] = "";
              tempForm["price"] = val.selectedGoodInfo[i].buy_price.toString();
              tempForm["remark"] = "";
              this.recordInfo.recordData.splice(
                this.currentIndex + 1,
                0,
                tempForm
              );
            }
          }
        }
        this.currentIndex = -1;
      },
      cancle: function() {
        this.$refs.dialog.hide()
        this.propForm.goods = [];

        this.propForm.goodType = [];
      },

      submit() {
        this.$refs['tableForm'].validate((valid) => {
          if (valid) {
            const array = this.recordInfo.recordData
            console.log("$arr3333333333",array)
            for (let i = 0; i < array.length; i++) {
              if (array[i].good_type_id == 0) {
                this.$message.error('商品类型不能为空')
                return
              }
              if (array[i].good_id == 0) {
                this.$message.error('规格名称不能为空')
                return
              }
            }

            const params = {
              'stockOut': this.recordInfo.recordData
            }
            editWarehouseoutInfo(params, this.warehouse_out_time,this.good_type_id, 1, 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.editDialogVisible = false
                this.warehousingOutInfo.info = []
                this.warehousingOutInfo.warehousingOutData = []
                this.GetOrderDetailOne(this.good_type_id)
              }
            })
          } else {
            return false
          }
        })
      }, 
     
      GetOrderDetailById(val){
        console.log("val",val)
         this.userList =[]
         var params = {
           id:val.warehouse_out_id,
           good_id:val.good_id,
           record_time:val.sys_record_time,
          }
         getOrderDetailById(params).then(response=>{
            if(response.data.state == 1){
              var total = 0
              var list = response.data.data.list
              var arrList =  this.unique(list)
              var info = response.data.data.info
              this.infoList = info
              console.log("info列表22222222",info)
              for (let i = 0; i < arrList.length; i++) {
                var obj = arrList[i]
                obj['is_total'] = 0
                this.userList.push(obj)
                total = total + arrList[i].count
              }
              this.userList.push({
                is_total: 1,
                total: total,
              })

              console.log("详情数据区",this.userList)
              if(val.is_sys == 1){
                this.editdialogVisibleThree = true
              }
              if(val.is_sys == 0){
                this.editdialogVisibleTwo = true
              }  
            }
         })
      },
      getNumber(id){
        var str = ""
        var arr = []
        var ids = []
        for(let i=0;i<this.userList.length;i++){
          if(id == this.userList[i].id){
            arr.push(...this.userList[i].warehouseOutInfo)
          }
        }
        console.log("arr",arr)
        if(arr.length > 0){
          for(let i=0;i<arr.length;i++){
              ids.push(arr[i].number)
          }
        }
        str = ids.join(",")
        return str
      },
      toPrint(){
        if(this.order_id == ""){
          this.$message.error("请选择出库单")
        }else{
            this.$router.push({path:"/stock/out/detail/print?id="+this.order_id+"&warehouse_out_time="+this.warehouse_out_time+"&keyword="+this.searchKey+"&start_time="+this.start_time+"&end_time="+this.end_time})
        }
      },
      getlist(){
         var params = {
           'id': this.order_id,
           "start_time":this.start_time,
           "end_time":this.end_time,
         }
        console.log('parasm22',params)
       getOutExportList(params).then(response=>{
          if(response.data.state == 1){
            var list = response.data.data.list
            var outCount = response.data.data.outCount
            console.log("outCount",outCount)
            for(let i=0;i<list.length;i++){
               list[i].unit = list[i].specification_name + list[i].packing_unit
               list[i].total_price = (list[i].total_count * list[i].price).toFixed(2)
               list[i].expiry_date = this.getTime(list[i].expiry_date,"{y}-{m}-{d}")
               list[i].product_date = this.getTime(list[i].product_date,"{y}-{m}-{d}") 
              for(let j=0;j<this.manufacturer.length;j++){
                if(list[i].manufacturer == this.manufacturer[j].id){
                  list[i].manufacturer = this.manufacturer[j].manufacturer_name
                }
              }
              for(let z=0;z<this.dealer.length;z++){
                 if(list[i].dealer == this.dealer[z].id){
                   list[i].dealer = this.dealer[z].dealer_name
                 }
              }
              for(let a=0;a<this.goodType.length;a++){
                 if(list[i].good_type_id == this.goodType[a].id){
                    list[i].good_type_id = this.goodType[a].type_name
                 }
              } 
            }
            console.log("导出list222222",list)
            this.exportList = list
          }
        })
      },
      toExport(){
        if(this.order_id == ""){
         this.$message.error("请勾选出库单")
         return
        }
        import('@/vendor/Export2Excel').then(excel => {
        for(let i=0;i<this.exportList.length;i++){
          this.exportList[i].total_price = this.exportList[i].count * this.exportList[i].price
        }
        const tHeader = ['耗材名称', '规格型号', '单位','出库数量','出库价格','总价','批号','生产日期','有效日期']
        const filterVal = ['good_name', 'specification_name', 'packing_unit','count','price','total_price','number','product_date','expiry_date']
        console.log("table",this.exportList)
        const data = this.formatJson(filterVal, this.exportList)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '耗材出库单详情'
        })
        this.downloadLoading = false
     })
    },
    formatJson(filterVal, jsonData) {
    return jsonData.map(v => filterVal.map(j => v[j]));
   },
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.app-container {
  // margin: 20px;
  font-size: 15px;
  .filter-container {
    padding-bottom: 5px;
  }
  .search-component {
    width: 500px;
    .searchBox {
      width: 300px;
      height: 36px;
      line-height: 36px;
      padding-left: 15px;
      border: 1px #dcdfe6 solid;
      border-right: none;
      outline: none;
      float: left;
      border-radius: 6px 0 0 6px;
      font-size: 14px;
      color: #333;
      background: #fff;
      box-shadow: 3px 3px 4px rgba(135, 135, 135, 0.05);
    }
    .searchBtn {
      background-color: #409eff;
      color: #fff;
      font-size: 15px;
      text-align: center;
      height: 36px;
      line-height: 36px;
      float: left;
      outline: none;
      width: 70px;
      border: none;
      border-radius: 0 6px 6px 0;
      font-family: "Microsoft Yahei";
      cursor: pointer;
    }
  }

  .amount {
    font-weight: normal;
    padding: 10px 0 0 0;
    color: #606266;
    font-size: 14px;
    span {
      color: #ef2525;
      font-family: "Arial";
      padding: 0 2px;
    }
  }
}
.el-table td,
.el-table th.is-leaf,
.el-table--border,
.el-table--group {
  border-color: #d0d3da;
}
.el-table--border::after,
.el-table--group::after,
.el-table::before {
  background-color: #d0d3da;
}
</style>
