<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
      <div>
        <el-button type="warning" @click="approval">反审核</el-button>
        <el-button type="warning" @click="examine">审核</el-button>
        <el-button type="primary" @click="Add">新增</el-button>
      </div>
    </div>
    <div class="app-container">
      <div
        style="
          justify-content: flex-start;
          margin: 0px 0 12px 0;
          display: flex;
          align-items: center;
        "
      >
        <div>
          <!-- <el-button
            size="small"
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="search"
            >查看</el-button
          > -->
        </div>
        <div>
          单据日期：
          <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
          >-
          <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>
          <el-input
            size="small"
            style="width: 200px; margin-left: 10px"
            class="filter-item"
            placeholder="请输入单据编号,仓库名称"
            v-model.trim="keywords"
          />
          <el-button
            size="small"
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="search"
            >查看</el-button
          >
        </div>
      </div>
      <el-table
        :header-cell-style="{
          backgroundColor: 'rgb(245, 247, 250)',
          color: '#606266',
        }"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="单据编号" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.second_order_number}}</span>
          </template>
        </el-table-column>
        <el-table-column label="单据日期" align="center">
          <template slot-scope="scope">
             {{getTime(scope.row.record_date)}}
          </template>
        </el-table-column>
      
        <el-table-column label="调出仓库" align="center">
          <template slot-scope="scope">
             {{getHouseName(scope.row.storehouse_out_id)}}
          </template>
        </el-table-column>
        <el-table-column label="调入仓库" align="center">
          <template slot-scope="scope">
            {{getHouseName(scope.row.storehouse_in_id)}}
          </template>
        </el-table-column>
        <el-table-column label="制单人" align="center">
          <template slot-scope="scope">
            {{getDocName(scope.row.creater)}}
          </template>
        </el-table-column>
        <el-table-column label="审核人" align="center">
          <template slot-scope="scope">
           {{getDocName(scope.row.checker)}}
          </template>
        </el-table-column>
        <el-table-column label="审核时间" align="center">
          <template slot-scope="scope">
            {{getTime(scope.row.check_time)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="260px">
          <template slot-scope="scope">
            <el-tooltip class="item" content="编辑" placement="top-start">
              <el-button
                icon="el-icon-edit-outline"
                size="small"
                type="primary"
                @click="toEdit(scope.row)"
              >
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" content="删除" placement="top-start">
              <el-button
                icon="el-icon-delete"
                size="small"
                type="danger"
                @click="toDelete(scope.row, scope.$index)"
              >
              </el-button>
            </el-tooltip>

            <el-tooltip class="item" content="详情" placement="top-start">
              <el-button
                icon="el-icon-view"
                size="small"
                type="primary"
                @click="toDetails(scope.row, scope.row.$index)"
              >
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 50, 100, 200, 500, 1000]"
        :page-size="10"
        background
        align="right"
        style="margin-top: 20px"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import BreadCrumb from "@/xt_pages/components/bread-crumb";
import {getAllSecondOrderList,checkSecondOrder,deleteStoreHouseList,returnCheckSecondOrder} from "@/api/seconde";
import { uParseTime } from "@/utils/tools";
export default {
  components: {
    BreadCrumb,
  },
  data() {
    return {
      crumbs: [
        { path: false, name: "库房管理" },
        { path: "/stock/warehousequery", name: "库存调拨" },
      ],
      value1: "",
      total: 0,
      page: 1,
      limit: 10,
      tableData: [],
      keywords:"",
      start_time:"",
      end_time:"",
      supplyList: [],
      check_id: 0,
      doctorList: [],
      houseList:[],
      check_id:0,
      ids:"",
      array:[],
      checkArray:[],
      returnArray:[],
    };
  },

  methods: {
   
    // 反审核
    approval() {
      if(this.array.length<=0){
       this.$message.error("请勾选需要反审核的订单!")
       return
      }
      if(this.returnArray.length >0){
        this.$message.error("不能勾选未审核的单据!")
        return
      }
      var ids = this.array.join(",")
      returnCheckSecondOrder(ids).then(response=>{
         if(response.data.state == 1){
          var msg = response.data.data.msg
          if(msg == 0){
            this.$message.success("反审核失败!")
            this.getlist()
          }
          if(msg == 1){
            this.$message.success("反审核成功!")
            this.getlist()
          }
          if(msg == 2){
            var good_name = response.data.data.good_name
            var specification_name = response.data.data.specification_name
            var storehose_name = response.data.data.storehose_name

            this.$message.error(storehose_name + " "+good_name+"*"+specification_name+"已有出库数据不能反审核")
          }
          if(msg == 3){
            var drug_name =  response.data.data.drug_name
            var dose = response.data.data.dose
            var dose_unit = response.data.data.dose_unit
            var min_number = response.data.data.min_number
            var min_unit =  response.data.data.min_unit
            var max_unit =  response.data.data.max_unit
            var str = drug_name + " " + dose + dose_unit + "*" + min_number + min_unit+"/"+max_unit
            var storehose_name = response.data.data.storehose_name
            this.$message.error(storehose_name +" "+str +"已有出库数据不能反审核!")

          }
         }
      })

    },

    // 审核
    examine() {
      if(this.checkArray.length >0){
       this.$message.error("不能勾选已审核的单据!")
       return
      }

      if(this.array.length <=0){
       this.$message.error("请勾选需要审核的订单!")
       return
      }
      var ids = this.array.join(",")
      checkSecondOrder(ids).then(response=>{
        if(response.data.state == 1){
          var msg = response.data.data.msg
         
          if(msg == 1){
            this.$message.success("审核成功!")
            this.getlist()
          }
          if(msg == 2){
            var good_name = response.data.data.good_name
            var specification_name = response.data.data.specification_name
            var storehose_name = response.data.data.storehose_name

            this.$message.error("审核失败" + " "+storehose_name + " "+good_name+"*"+specification_name+"库存不足,无法调拨,请修改调拨数量!")
          }
          if(msg == 3){
            var drug_name =  response.data.data.drug_name
            var dose = response.data.data.dose
            var dose_unit = response.data.data.dose_unit
            var min_number = response.data.data.min_number
            var min_unit =  response.data.data.min_unit
            var max_unit =  response.data.data.max_unit
            var str = drug_name + " " + dose + dose_unit + "*" + min_number + min_unit+"/"+max_unit
            var storehose_name = response.data.data.storehose_name
            this.$message.error("审核失败" + " " + storehose_name +" "+str +"库存不足,无法调拨,请修改调拨数量!")

          }

        }
      })
    },

    // 添加
    Add() {
      this.$router.push({path:"/stock/inventoryTransfer/Addtrans"})
    },

    // 删除
    toDelete(row,index) {
      if(row.is_check == 1){
        this.$message.error("已审核数据不能删除!")
        return 
      }
      this.$confirm("确认删除库存调拨单记录?", "删除库存调拨单记录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消", 
        type: "warning"
      }).then(() => {
          deleteStoreHouseList(row.id).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.tableData.splice(index,1)
            }
          });
        }).catch(() => {});
    },

    // 详情查看
    toDetails(row) {
        this.$router.push({path:"/stock/inventoryTransfer/transDetails?id="+row.id})
    },
    changeTypeName() {
      this.getlist();
    },
    startTimeChange() {
      
      this.getlist();
    },
    endTimeChange() {
     
      this.getlist();
    },
    search() {
      this.getlist();
    },
    getTimes(time) {
      if (time === "") {
        return "";
      }
      return uParseTime(time, "{y}-{m}-{d}");
    },
    // 表单全选
    handleSelectionChange(val) {
      this.array = []
      this.checkArray = []
      this.returnArray = []
     for(let i=0;i<val.length;i++){
      this.array.push(val[i].id)
      if(val[i].is_check == 1){
        this.checkArray.push(val[i].is_check)
      }
      if(val[i].is_check == 2){
        this.returnArray.push(val[i].is_check)
      }
     }
    },
    // 页表操作
    handleSizeChange(val) {
      this.array= []
      this.checkArray = []
      this.returnArray = []
      this.limit = val;
      this.getlist();
    },
    handleCurrentChange(val) {
      this.array= []
      this.checkArray = []
      this.returnArray = []
      this.page = val;
      this.getlist();
    },

    // 表格样式
    changColor({ rowIndex }) {
      if (rowIndex % 2 == 1) {
        return {
          backgroundColor: "#C4E1FF",
          color: "#303133",
        };
      } else {
        return {
          backgroundColor: "#ACD6FF",
          color: "#303133",
        };
      }
    },
    getlist() {
      var params = {
        check_id: this.check_id,
        start_time: this.start_time,
        end_time: this.end_time,
        keyword: this.keywords,
        page: this.page,
        limit: this.limit,
      };
      console.log("params32232332323",params)
      getAllSecondOrderList(params).then((response) => {
        if (response.data.state == 1) {
          var list = response.data.data.list;
          this.tableData = list;
          var total = response.data.data.total;
          this.total = total;
          this.houseList = response.data.data.houseList
          this.doctorList = response.data.data.doctorList
        }
      });
    },
    getName(id) {
      var name = "";
      for (let i = 0; i < this.supplyList.length; i++) {
        if (id == this.supplyList[i].id) {
          name = this.supplyList[i].supplier_name;
        }
      }
      return name;
    },
    getDocName(id) {
      var user_name = "";
      for (let i = 0; i < this.doctorList.length; i++) {
        if (id == this.doctorList[i].admin_user_id) {
          user_name = this.doctorList[i].user_name;
        }
      }
      return user_name;
    },
    getTime(time) {
      if (time === "") {
        return "";
      }
      return uParseTime(time, "{y}-{m}-{d}");
    },
    getHouseName(id){
      var storehouse_name = ""
      for(let i=0;i<this.houseList.length;i++){
         if(id == this.houseList[i].id){
           storehouse_name = this.houseList[i].storehouse_name
         }
      }
      return storehouse_name
    },
    toEdit(row){
      this.$router.push("/stock/inventoryTransfer/transedit?id="+row.id)
    }
  },
  created(){
    var now = new Date(); //当前日期
    var nowMonth = now.getMonth(); //当前月
    var nowYear = now.getFullYear(); //当前年
    //本月的开始时间
    var monthStartDate = new Date(nowYear, nowMonth, 1);
    this.start_time = this.getTimes(monthStartDate);
    this.end_time = this.getTimes(new Date());

    // this.org_id = this.$store.getters.xt_user.org_id;
    // var start_time =  window.sessionStorage.getItem('purchase_start_time')
    
    // var end_time =  window.sessionStorage.getItem('purchase_end_time')
   
    // if(start_time !=null){
    //   this.start_time = ""
    //   this.start_time = start_time
    // }
    // if(end_time!=null){
    //   this.end_time = ""
    //   this.end_time = end_time
    // }
    // window.sessionStorage.removeItem('purchase_start_time')
    // window.sessionStorage.removeItem('purchase_end_time')
    this.getlist();
  }
};
</script>

<style rel="stylesheet/css" lang="scss" scoped>
</style>