<template>
  <!-- 待出库 -->
  <div>
    <!-- <div class="common-card">
            <h3>订单状态</h3>
            <yl-step></yl-step>
        </div> -->
        <!-- <div class="right-button">
            <el-button class="lake-Blue" @click="handleConfirm">出库</el-button>
            <el-button type="danger" @click="handleRefuse">关闭订单</el-button>
        </div> -->
    <div class="common-card">
      <h3>基本信息</h3>
      <el-form
        :model="listForm"
        ref="listform"
        label-width="237px"
        class="grid-form-class"
      >
        <div class="form-body">
          <div class="flex-css">
            <el-form-item label="采购单号" prop="id">
              <div class="content">
                {{ listForm.id }}
              </div>
            </el-form-item>
            <el-form-item label="采购品种" prop="detlCnt">
              <div class="content">
                {{ listForm.detlCnt }}
              </div>
            </el-form-item>
            <el-form-item label="采购总数量" prop="qtySum">
              <div class="content">
                {{ listForm.qtySum }}
              </div>
            </el-form-item>
          </div>
          <div class="flex-css">
            <el-form-item label="总金额" prop="purcAmt">
              <div class="content">
                {{ listForm.purcAmt }}
              </div>
            </el-form-item>
           
            <el-form-item label="部门名称" prop="deptName">
              <div class="content">
                {{ listForm.deptName }}
              </div>
            </el-form-item>
            <el-form-item label="医院名称" prop="branchName">
              <div class="content">
                {{ listForm.branchName }}
              </div>
            </el-form-item> 
          </div>
          <div class="flex-css">
           
          
            <el-form-item label="当前状态" prop="stas">
              <div class="content">
                {{ listForm.stas }}
              </div>
            </el-form-item>
            <el-form-item label="采购时间" prop="docmkDate">
              <div class="content">
                {{ listForm.docmkDate }}
              </div>
            </el-form-item>
            <el-form-item label=" " prop="">
              <div class="content">
                <!-- {{ listForm.docmker }} -->
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="common-card">
      <h3>商品明细</h3>
      <el-form :model="tableData" ref="tabledata">
        <el-table
          :data="tableData"
          v-loading="loding"
          element-loading-text="加载中..."
          border
          :span-method="handleSpan"
        >
          <template slot="empty">
            <img src="@/assets/nopage.png" alt />
            <p>暂无数据</p>
          </template>
          <el-table-column fixed type="index" label="序号" width="60" />
          <el-table-column label="耗材编码" prop="materialId" />
          <el-table-column label="医保编码" prop="hiCode" />
          <el-table-column label="耗材名称" width="300">
            <template slot-scope="scope">
                <mcs-info :info="scope.row"></mcs-info>
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="spec" />
          <el-table-column label="型号" prop="mol" />
          <el-table-column label="材质" prop="matl" />
          <el-table-column label="是否集采" prop="isFas" >
            <template #default="{ row }">
              <span v-if="row.isFas == '1'">否</span>
              <span v-if="row.isFas == '0'">是</span>
            </template>
          </el-table-column>
          <el-table-column label="计价单位" prop="prcUnt" />
          <el-table-column label="采购单位" prop="purcUnt" />
          <el-table-column label="包装内数量" prop="convrat" />
          <el-table-column label="单价" prop="purcPric" />
          <el-table-column label="批号" prop="lotNum" width="120">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                class="item"
                :prop="scope.$index + '.lotNum'"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input placeholder="请输入" v-model="scope.row.lotNum"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" prop="manuDate" width="220">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                class="item"
                :prop="scope.$index + '.manuDate'"
                :rules="[
                  {
                    required: true,
                    message: '请选择生产日期',
                    trigger: 'change',
                  },
                ]"
              >
                <el-date-picker
                  style="width: 100%"
                  v-model="scope.row.manuDate"
                  type="date"
                  placeholder="请选择生产日期"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="有效期至" width="220" prop="prodExpy">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                class="item"
                :prop="scope.$index + '.prodExpy'"
                :rules="[
                  {
                    required: true,
                    message: '请选择有效期',
                    trigger: 'change',
                  },
                ]"
              >
                <el-date-picker
                  style="width: 100%"
                  v-model="scope.row.prodExpy"
                  type="date"
                  placeholder="请选择有效期"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="需求数量" prop="purcCnt" />
          <el-table-column label="已出库数量" prop="delvCntYck" width="90px" />
          <el-table-column label="剩余出库量" prop="toDelvCnt" width="90px" />
          <el-table-column label="本次出库数量" prop="delvCnt" width="150">
              <template slot-scope="scope">
                  <el-form-item
                      label-width="0"
                      class="item"
                      :prop="scope.$index + '.delvCnt'"
                      :rules="[
                      {
                          required: true,
                          pattern: /^[0-9]\d*$/,
                          message: '请输入正整数',
                          trigger: 'blur',
                      },
                      ]"
                  >
                      <el-input-number v-model="scope.row.delvCnt" controls-position="right" @change="updateNum(scope.row,scope.$index)" :min="0"></el-input-number>
                  </el-form-item>
              </template>
          </el-table-column>
          
          <el-table-column label="报关单" prop="invoFileId" width="200">
            <template slot-scope="scope">
              <yl-upload
                v-if="scope.row.prodSouc=='进口'"
                :fileId="scope.row.invoFileId"
                @getUpload="getUpload1"
                urlName="acco"
                :index="scope.$index"
                >
                <template v-slot:dec>只能上传pdf文件</template>
                </yl-upload>
            </template>
          </el-table-column>
          <!-- <el-table-column label="随货单" prop="dyntFileId" width="200">
            <template slot-scope="scope">
                <yl-upload
                :fileId="scope.row.dyntFileId"
                @getUpload="getUpload"
                urlName="acco"
                :index="scope.$index"
                >
                <template v-slot:dec>只能上传pdf文件</template>
                </yl-upload>
            </template>
          </el-table-column> -->
          <el-table-column label="备注" prop="memo" width="120">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                class="item"
              >
                <el-input placeholder="请输入" v-model="scope.row.memo"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.showDeleteButton"
                class="red"
                type="text"
                @click="handleDelete(scope.row, scope.$index)"
                >删除</el-button
              >
              <el-button v-else type="text" @click="handleBatch(scope.row, scope.$index)"
                >添加批次
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div class="foot-button" style="margin-top: 30px">
        <el-button
          type="primary"
          @click="handleDelivery"
          v-if="listForm.stas === '待出库'"
          >出库</el-button
        >
        <el-button
          type="primary"
          @click="handleDelivery"
          v-if="listForm.stas === '部分出库'"
          >出库</el-button
        >
        <!-- <el-button type="danger" @click="handleOrderEnd" v-show="endBtn" :loading="endLoad">结束订单</el-button> -->
        <el-button type="success" @click="handleBack" >返回</el-button>
      </div>
    </div>

    <!-- 选择发票 -->
    <el-dialog title="选择发票" :visible.sync="dialogFa" width="55%">
      <el-form :model="faForm" ref="faForm" :inline="true">
        <el-form-item label="发票信息" prop="billInfo">
          <el-input v-model="faForm.billInfo" placeholder="请输入发票名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getFaData('search')">查询</el-button>
          <el-button @click="faReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="faLoading"
        element-loading-text="加载中"
        :data="faData"
        fit
        stripe
        border
      >
        <template slot="empty">
          <img src="@/assets/nopage.png" alt />
          <p>暂无数据</p>
        </template>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="发票名称" prop="billName" />
        <el-table-column label="开票金额" prop="billAmt" />
        <el-table-column label="发票号码" prop="invoNum" />
        <el-table-column label="开票时间" prop="billDate" />
        <el-table-column label="上传时间" prop="upldDate" />
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="primary" plain @click="handleRow(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <yl-pagination
        v-show="faTotal > 0"
        :total="faTotal"
        :page.sync="faForm.current"
        :limit.sync="faForm.size"
        @pagination="getFaData"
      />
    </el-dialog>
    <!-- 选择同行单 -->
    <el-dialog title="选择同行单" :visible.sync="dialogTong" width="55%">
      <el-form :model="tongForm" ref="tongForm" :inline="true">
        <el-form-item label="发票信息" prop="billInfo">
          <el-input v-model="tongForm.billInfo" placeholder="请输入同行单名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTongData('search')">查询</el-button>
          <el-button @click="tongReset()">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="tongLoading"
        element-loading-text="加载中"
        :data="tongData"
        fit
        stripe
        border
      >
        <template slot="empty">
          <img src="@/assets/nopage.png" alt />
          <p>暂无数据</p>
        </template>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="票据名称" prop="billName" />
        <el-table-column label="票据金额" prop="billAmt" />
        <el-table-column label="票据单号" prop="invoNum" />
        <el-table-column label="开票时间" prop="billDate" />
        <el-table-column label="上传时间" prop="upldDate" />
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="primary" plain @click="handleRowTong(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <yl-pagination
        v-show="tongTotal > 0"
        :total="tongTotal"
        :page.sync="tongForm.current"
        :limit.sync="tongForm.size"
        @pagination="getTongData"
      />
    </el-dialog>
    <!-- PDF预览 -->
    <el-dialog
      title="PDF预览"
      class="dd"
      :visible.sync="dialogVisible"
      width="70%"
      center
    >
      <iframe :src="pdfSrc" frameborder="0" style="width: 100%; height: 100%"></iframe>
    </el-dialog>
    <!-- 出库单预览 -->
    <el-dialog title="出库单预览" :visible.sync="printVisible" width="70%">
      <div id="printMe">
        <table cellspacing="0" cellpadding="0" border="1" width="100%" class="chuTable">
          <tr height="50px">
            <th :colspan="12" :rowspan="1" style="font-size: 26px; font-weight: 800">
              送货单
            </th>
            <th :colspan="8" :rowspan="1" style="font-size: 20px">
              NO:<span style="color: red">{{ listForm.id }}</span>
            </th>
          </tr>
          <tr class="hang">
            <th :colspan="2">医院名称：</th>
            <th :colspan="8">
              {{ listForm.branchName }}
            </th>
            <!-- <th>
                            制单人：
                        </th>
                        <th :colspan="4">
                            {{ listForm.docmker }}
                        </th> -->
            <th :colspan="2">制单时间：</th>
            <th :colspan="8">
              {{ listForm.docmkDate }}
            </th>
          </tr>
          <tr class="hang">
            <th :colspan="2">出库人：</th>
            <th :colspan="8">
              {{ $store.state.user.username }}
            </th>
            <th :colspan="2">出库日期：</th>
            <th :colspan="8">
              {{ listForm.OutboundDate }}
            </th>
          </tr>
          <tr class="hang">
            <th>序号</th>
            <th>耗材编码</th>
            <th>医保编码</th>
            <th>耗材名称</th>
            <th>商品类别</th>
            <th>规格</th>
            <th>型号</th>
            <th>材质</th>
            <th>生产来源</th>
            <th>注册证号</th>
            <th>生产企业</th>
            <th>单价</th>
            <th>批号</th>
            <th>生产日期</th>
            <th>有效期至</th>
            <th>需求数量</th>
            <th>已出库数量</th>
            <th>剩余出库量</th>
            <th>本次出库数量</th>
            
          </tr>
          <tr v-for="(item, index) in chuList" :key="index" class="hang">
            <td align="center">
              {{ index + 1 }}
            </td>
            <td align="center">
              {{ item.materialId }}
            </td>
            <td align="center">
              {{ item.hiCode }}
            </td>
            <td align="center">
              {{ item.prodName }}
            </td>
            <td align="center">
              <span v-if="item.mcsType=='0'">普通耗材</span>
              <span v-if="item.mcsType=='1'">高值耗材</span>
              <span v-if="item.mcsType=='2'">试剂</span>
            </td>
            <td align="center">
              {{ item.spec }}
            </td>
            <td align="center">
              {{ item.mol }}
            </td>
            <!-- 材质 -->
            <td align="center">
              {{ item.matl }}
            </td>
            <td align="center">
              <span v-if="item.prodSouc=='1'">国产</span>
              <span v-if="item.prodSouc=='2'">进口</span>
            </td>
            <td align="center">
              {{ item.regcertno }}
            </td>
            <td align="center">
              {{ item.prodEntp }}
            </td>
            <td align="center">
              {{ item.purcPric }}
            </td>
            <td align="center">
              {{ item.lotNum }}
            </td> 
            <td align="center">
              {{ item.manuDate }}
            </td>
            <td align="center">
              {{ item.prodExpy }}
            </td>

            <td align="center">
              {{ item.purcCnt }}
            </td>
            <td align="center">
              {{ item.delvCntYck }}
            </td>
            <td align="center">
              {{ item.toDelvCnt }}
            </td>
            <td align="center">
              {{ item.delvCnt }}
            </td>
          </tr>
          <tr class="hang">
            <th align="left" :colspan="6" >合计</th>
            <td :colspan="13" align="left">
              {{ moneySum | toChineseAmount }}
            </td>
            <!-- <td align="center"> -->
              <!-- {{ numSum }} -->
            <!-- </td> -->
          </tr>
          <tr class="hang">
            <th :colspan="6" align="left">发货金额（人民币）大写：</th>
            <td :colspan="13">
              {{ moneySum | toChineseAmount }}
            </td>
          </tr>
          <tr height="50px">
            <th :colspan="6" align="left">备注：</th>
            <td :colspan="13"></td>
          </tr>
          <!-- <tr class="hang">
            <th align="left" :colspan="6">收货人：</th>
            <td :colspan="13"></td>
          </tr> -->
        </table>
      </div>
      <div class="foot-button" style="margin-top: 40px">
        <el-button type="primary" :loading="comfirmLoad" @click="handleConfirm"
          >确认</el-button
        >
        <el-button type="primary" v-print="printObj">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ylStep from "@/components/yl-step";
import ylPagination from "@/components/yl-pagination";
import ylUpload from "@/components/yl-upload";
import mcsInfo from "@/views/components/mcs-info.vue";
import { countNumPrice, getTotalAmount } from "@/utils/utils";
import moment from "moment";
import {
  getMcsOrdDckDetl,
  saveDelvOrd,
  finishMcsDelvOrd,
  finishDelvOrd,
  getBillPage,
  submitMcsDelvOrd,
} from "@/api/orderManage-sup/index";
export default {
  components: {
    ylStep,
    ylPagination,
    ylUpload,
    mcsInfo
  },
  data() {
    return {
      pdfSrc: "",
      dialogVisible: false,
      saveLoad: false,
      confirmLoad: false,
      endLoad: false,
      number: [],
      listForm: {
        id: "",
        detlCnt: "",
        orgName: "",
        docmker: "",
        docmkDate: "",
        stas: "",
        deptName:"",
        branchName:"",
      },
      stasOptions: [
        { value: "A", lable: "未受理" },
        { value: "B", lable: "未出库" },
        { value: "R", lable: "被驳回" },
        { value: "C", lable: "已出库" },
        { value: "D", lable: "部分出库" },
        { value: "Y", lable: "已入库" },
        { value: "P", lable: "部分入库" },
      ],
      essdrugOptions: ["非基药", "基药"],
      tableData: [],
      loading: false,
      cellList: [],
      count: null,
      // 选择发票
      dialogFa: false,
      faForm: {
        billType: "invo",
        billInfo: "",
        billName: "",
        current: 1,
        size: 10,
      },
      faLoading: false,
      faData: [],
      faTotal: 0,
      faIndex: "",
      // 选择同行单
      dialogTong: false,
      tongForm: {
        billType: "acco",
        billInfo: "",
        billName: "",
        current: 1,
        size: 10,
      },
      tongLoading: false,
      tongData: [],
      tongTotal: 0,
      tongIndex: "",
      code: "",
      // 出库单预览
      printVisible: false,
      chuList: [],
      // 打印
      printObj: {
        id: "printMe",
        popTitle: "", // 打印配置页上方标题
        extraHead: "", //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: "", // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: "", // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: "", // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: "", // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {}, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback: () => {}, // 开启打印前的回调事件
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback() {}, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: "",
        standard: "",
        extraCss: "",
      },
      fileIndex:null,
      fileIndex1:null,
      endBtn:false,
    };
  },
  created() {
    this.listForm.id = this.$route.query.id;
    // this.listForm.materialId = this.$route.query.materialId;
    this.listForm.detlCnt = this.$route.query.detlCnt;
    this.listForm.qtySum = this.$route.query.qtySum;
    this.listForm.purcAmt = this.$route.query.purcAmt;
    this.listForm.docmker = this.$route.query.docmker;
    this.listForm.stas = this.$route.query.stas;
    this.listForm.docmkDate = this.$route.query.docmkDate;
    this.listForm.OutboundDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    this.listForm.branchName = this.$route.query.branchName;
    this.listForm.deptName = this.$route.query.deptName;
    if(this.listForm.stas=='部分出库'){
      this.endBtn = true
    }
    // this.stasOptions.forEach((i)=>{
    //     if(i.value == this.$route.query.stas){
    //         this.listForm.stas = i.lable
    //     }
    // })
    // console.log(this.listForm.stas,"listForm.stas")
  },
  computed: {
    numSum: function () {
      return this.chuList
        .map((row) => row.delvCnt)
        .reduce((acc, cur) => (parseFloat(acc) + parseFloat(cur)).toFixed(2), 0);
    },
    moneySum: function () {
      return this.chuList
        .map((row) => row.price)
        .reduce((acc, cur) => (parseFloat(acc) + parseFloat(cur)).toFixed(2), 0);
    },
  },
  filters: {
    toChineseAmount(money) {
      var cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
      var cnIntRadice = ["", "拾", "佰", "仟"];
      var cnIntUnits = ["", "万", "亿", "兆"];
      var cnDecUnits = ["角", "分", "毫", "厘"];
      var cnInteger = "整";
      var cnIntLast = "元";
      var maxNum = 999999999999999.9999;
      var integerNum;
      var decimalNum;
      var chineseStr = "";
      var parts;
      if (money === "") {
        return "";
      }
      money = parseFloat(money);
      if (money >= maxNum) {
        return "";
      }
      if (money === 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
      }
      money = money.toString();
      if (money.indexOf(".") === -1) {
        integerNum = money;
        decimalNum = "";
      } else {
        parts = money.split(".");
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
      }
      if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
          var n = integerNum.substr(i, 1);
          var p = IntLen - i - 1;
          var q = p / 4;
          var m = p % 4;
          if (n === "0") {
            zeroCount++;
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0];
            }
            zeroCount = 0;
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m === 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        chineseStr += cnIntLast;
      }
      if (decimalNum !== "") {
        var decLen = decimalNum.length;
        for (i = 0; i < decLen; i++) {
          n = decimalNum.substr(i, 1);
          if (n !== "0") {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (chineseStr === "") {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (decimalNum === "") {
        chineseStr += cnInteger;
      }
      return chineseStr;
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      this.listLoading = true;
      getMcsOrdDckDetl({ id: this.$route.query.id })
        .then((res) => {
          this.tableData = res.data;
          this.chuList = res.data;
          this.listLoading = false;
          this.computeCell(this.tableData);
          this.tableData.forEach((item) => {
            if (!item.delvCnt) {
              // item.delvCnt = 0;
              this.$set(item, "delvCnt", 0);
            }
            item.essdrugType = this.essdrugOptions[item.essdrugType * 1];
          });
          // 将待出库数量放入number数组
          // this.number = this.tableData.map((i)=>{
          //     return i.toDelvCnt
          // })
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },
    // 出库数量变更
    updateNum(row, index) {
      // const aa = this.tableData.findIndex((item) => item.id === row.id);
      // if(this.number[aa]){
      //     this.shanchu2(row,aa);
      // }else{
      //     this.shanchu(row);
      // }
      this.shanchu3(row);
      this.numOrPriceChange(index, row);
    },
    numOrPriceChange(index, row) {
      this.$set(
        this.tableData[index],
        "price",
        getTotalAmount(row.delvCnt, row.purcPric)
      );
      this.amount = countNumPrice(this.tableData);
    },
    //获取出库数量和
    numAll(row) {
      let num = 0;
      this.tableData.forEach((item) => {
        if (item.materialId == row.materialId) {
          num += item.delvCnt;
        }
      });
      return num;
    },
    //公共函数
    shanchu(row) {
      this.tableData.forEach(async (item) => {
        await this.numAll(row);
        console.log(this.numAll(row), "he");
        if (item.id == row.id) {
          if (this.numAll(row) > item.purcCnt) {
            this.$message.info("出库数量不能大于订货数");
            row.delvCnt = 0;
            item.toDelvCnt = item.purcCnt - this.numAll(row);
            return;
          }
          item.toDelvCnt = item.purcCnt - this.numAll(row);
        }
        let choose = this.tableData;
        this.tableData = choose;
      });
    },
    shanchu2(row, index) {
      this.tableData.forEach(async (item) => {
        await this.numAll(row);
        console.log(this.numAll(row), "he");
        if (item.id == row.id) {
          if (this.numAll(row) > this.number[index]) {
            this.$message.info("出库数量不能大于待出库数量");
            row.delvCnt = 0;
            row.toDelvCnt = this.number[index];
            item.toDelvCnt = this.number[index] - this.numAll(row);
            return;
          }
          item.toDelvCnt = this.number[index] - this.numAll(row);
        }
        let choose = this.tableData;
        this.tableData = choose;
      });
    },
    shanchu3(row) {
      this.tableData.forEach(async (item) => {
        await this.numAll(row);
        console.log(this.numAll(row), "he");
        if (item.materialId == row.materialId) {
          if (this.numAll(row) > item.toDelvCnt) {
            this.$message.warning("出库数量不能大于待出库数量");
            row.delvCnt = 0;
            row.price = 0;
            return;
          }
        }
        let choose = this.tableData;
        this.tableData = choose;
      });
    },
    // 预览文件
    dataURLtoBlob(e) {
      let bstr = atob(e);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      } //确定解析格式
      let blob = new Blob([u8arr], { type: "application/pdf;chartset=UTF-8" });
      let url = window.URL.createObjectURL(blob);
      return url;
    },
    // 详情
    openPdf(row) {
      // let file = {
      //     id: row.fileId,
      // };
      // uploadCheck(file).then((res) => {
      //     if (res.success == true) {
      //         this.dialogVisible = true;
      //         const a = this.dataURLtoBlob(res.data.fileContent);
      //         this.pdfSrc = a;
      //     }
      // });
    },
    // 添加批次
    handleBatch(row, index) {
      let list = {
        prodCode:row.prodCode,
        regcertno:row.regcertno,
        delvCnt: "",
        delvCntYck:row.delvCntYck,
        docmkDate:row.docmkDate,
        docmker:row.docmker,
        essdrugType:row.essdrugType,
        prodEntp: row.prodEntp,
        materialId: row.materialId,
        prodName: row.prodName,
        hiCode:row.hiCode,
        mol: row.mol,
        matl: row.matl,
        memo:row.memo,
        mcsType:row.mcsType,
        purcPric: row.purcPric,
        purcAmt: row.purcAmt,
        purcCnt: row.purcCnt,
        prodSouc:row.prodSouc,
        spec: row.spec,
        toDelvCnt: row.toDelvCnt,
        invoFileId: "",
        lotNum: "",
        manuDate: "",
        prodExpy: "",
        dyntFileId: "",
      };
      this.tableData.splice(index + 1, 0, list);
      list.showDeleteButton = true;
      this.computeCell(this.tableData);
      console.log(this.tableData,"tableData")
      // const aa = this.tableData.findIndex((item) => item.id === row.id);
      // this.number.splice(aa+1,0,this.number[aa])
    },
    // 筛选合并项
    computeCell(tableData) {
      this.cellList = [];
      this.count = null;
      for (let i = 0; i < tableData.length; i++) {
        if (i == 0) {
          // 先设置第一项
          this.cellList.push(1); // 初为1，若下一项和此项相同，就往cellList数组中追加0
          this.count = 0;
          console.log("索引", 0, this.count);
        } else {
          // 判断当前项与上项的设备类别是否相同，因为是合并这一列的单元格
          if (tableData[i].materialId == tableData[i - 1].materialId) {
            this.cellList[this.count] += 1; // 增加计数
            this.cellList.push(0); // 相等就往cellList数组中追加0
            console.log("索引", i, this.count);
          } else {
            this.cellList.push(1); // 不等就往cellList数组中追加1
            this.count = i; // 将索引赋值为计数
            console.log("索引", i, this.count);
          }
        }
      }
    },
    // 合并列
    handleSpan({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 1 ||
        columnIndex === 2 ||
        columnIndex === 3 ||
        columnIndex === 4 ||
        columnIndex === 5 ||
        columnIndex === 6 ||
        columnIndex === 7 ||
        columnIndex === 8 ||
        columnIndex === 9 ||
        columnIndex === 10 ||
        columnIndex === 11 ||
        columnIndex === 15 ||
        columnIndex === 16 ||
        columnIndex === 17 
      ) {
        // console.log("单元格数组，若下一项为0，则代表合并上一项", this.cellList);
        const rowCell = this.cellList[rowIndex];
        if (rowCell > 0) {
          const colCell = 1;
          // console.log(`动态竖向合并单元格, 第${colCell}列，竖向合并${rowCell}个单元格 `);
          return {
            rowspan: rowCell,
            colspan: colCell,
          };
        } else {
          // 清除原有的单元格，必须要加，否则就会出现单元格会被横着挤到后面了！！！
          // 本例中数据是写死的不会出现，数据若是动态后端获取的，就会出现了！！！
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }

      // if (columnIndex === 2 && rowIndex == 0) {
      //     return {
      //         rowspan: this.pos,
      //         colspan: 1
      //     };
      // }else{
      //     for(let i=1;i<this.pos;i++){
      //         if(rowIndex === this.pos-i && columnIndex == 2){
      //             return {
      //                 rowspan: 0,
      //                 colspan: 0
      //             };
      //         }
      //     }
      // }
    },
    //删除
    handleDelete(row, i) {
      const index = this.tableData.findIndex((item) => item.materialId === row.materialId);
      if (index !== -1) {
        let qwe = this.tableData.findIndex(function (item) {
          return item.materialId == row.materialId;
        });
        this.tableData.splice(i, 1);
        this.cellList.splice(i, 1);
        this.cellList[qwe]--;
      }
      row.showDeleteButton = false;

      this.shanchu3(row);
      // if(this.number[index]){
      //     this.shanchu2(row,index);
      // }else{
      //     this.shanchu(row);
      // }
      // this.number.splice(i,1);
    },
    getUpload1(id,index) {
      this.tableData[index].invoFileId = id
      if (id) {
        this.$refs.tabledata.clearValidate("invoFileId");
      } else {
        this.$refs.tabledata.validateField("invoFileId");
      }
    },
    getUpload(id,index) {
      this.tableData[index].dyntFileId = id
      if (id) {
        this.$refs.tabledata.clearValidate("dyntFileId");
      } else {
        this.$refs.tabledata.validateField("dyntFileId");
      }
    },
    
    
    // 获取发票信息
    getFaData(type) {
      if (type == "search") {
        this.faForm.current = 1;
      }
      this.faLoading = true;
      getBillPage(this.faForm)
        .then((res) => {
          this.faData = res.data.records;
          this.faTotal = res.data.total;
          this.faLoading = false;
        })
        .catch((err) => {
          this.faLoading = false;
        });
      // this.faData = [{aa:"资质文件.pdf",bb:"1111"},{aa:"出库文件.pdf",bb:"2222"}];
      // this.faTotal = 1
    },
    faReset() {
      this.$refs.faForm.resetFields();
      this.getFaData();
    },
    // 选择发票
    handleFa(e, row) {
      this.faIndex = e;
      this.dialogFa = true;
      this.getFaData();
      this.code = "";
      this.code = row.id;
    },
    // 选择发票 确认选择
    handleRow(row) {
      this.tableData[this.faIndex].invoFileId = row.fileId;
      // this.tableData.forEach((i)=>{
      //     if(i.id == this.code){
      //         i.invoFileId = row.fileId
      //     }
      // })
      this.computeCell(this.tableData);
      this.dialogFa = false;
    },
    // 获取同行单信息
    getTongData(type) {
      if (type == "search") {
        this.tongForm.current = 1;
      }
      this.tongLoading = true;
      getBillPage(this.tongForm)
        .then((res) => {
          this.tongData = res.data.records;
          this.tongTotal = res.data.total;
          this.tongLoading = false;
        })
        .catch((err) => {
          this.tongLoading = false;
        });
      // this.tongData = [{aa:"资质文件.pdf",bb:"1111"},{aa:"出库文件.pdf",bb:"2222"}];
      // this.tongTotal = 1
    },
    tongReset() {
      this.$refs.tongForm.resetFields();
      this.getTongData();
    },
    // 选择同行单
    handleTong(e, row) {
      this.tongIndex = e;
      this.dialogTong = true;
      this.getTongData();
      this.code = "";
      this.code = row.id;
    },
    // 选择同行单 确认选择
    handleRowTong(row) {
      // this.tableData[this.tongIndex].dyntFileId = row.fileId;
      this.tableData.forEach((i) => {
        if (i.id == this.code) {
          i.dyntFileId = row.fileId;
        }
      });
      this.computeCell(this.tableData);
      this.dialogTong = false;
    },
    // 出库
    handleDelivery() {
      this.tableData.forEach((item) => {
        // console.log(item, "item");
        if (item.delvCnt=='0') {
          this.$message({
            message: "本次出库数量必须大于0",
            type: "warning",
          });
          throw new Error("本次出库数量必须大于0");
        }
         if (item.prodSouc=="进口" && !item.invoFileId) {
          this.$message({
            // message: "请填写相应信息，并选择报关单和随货单",
            message: "请填写相应信息，并选择报关单",
            type: "warning",
          });
          throw new Error("请填写相应信息，并选择报关单");
        }
      });
      this.$refs.tabledata.validate((valid) => {
        if (valid) {
          this.$confirm("确认出库", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.printVisible = true;
          });
        } else {
          this.$message({
            type: "warning",
            message: "请填写必填项信息",
          });
        }
      });
    },
    // 出库确认
    handleConfirm() {
      console.log(this.tableData,"this.tableData")
      this.$confirm("确认出库", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let data = this.tableData.map((i) => {
          console.log(i,"1111")
          return {
            materialId: i.prodCode,
            memo:i.memo,
            delvCnt: i.delvCnt,
            hiCode:i.hiCode,
            delvPric:i.purcPric,
            lotNum: i.lotNum,
            manuDate: i.manuDate,
            prodExpy: i.prodExpy,
            invoFileId: i.invoFileId,
            dyntFileId: i.dyntFileId,
            noRow:i.index
          };
        });
        let data2 = {
          delvOrdId: "",
          purcOrdId: this.$route.query.id,
          detlList: data,
          deptId: this.$route.query.deptId,
          spdId: this.$route.query.spdId,
          deptName: this.$route.query.deptName,
        };
        console.log(data, "data");
        submitMcsDelvOrd(data2)
          .then((res) => {
            this.printVisible = false;
            this.$router.push("purOrderDelivery");
          })
          .catch((err) => {
            // this.confirmLoadLoad = false;
          });
      });
    },
    // 保存
    handleSave() {
      let data = this.tableData.map((i) => {
        return {
          drugListId: i.drugListId,
          delvCnt: i.delvCnt,
          lotNum: i.lotNum,
          manuDate: i.manuDate,
          prodExpy: i.prodExpy,
          invoFileId: i.invoFileId,
          dyntFileId: i.dyntFileId,
        };
      });
      let data2 = {
        delvOrdId: "",
        purcOrdId: this.$route.query.id,
        detlList: data,
      };
      console.log(data, "data");
      this.saveLoad = true;
      saveDelvOrd(data2)
        .then((res) => {
          this.saveLoad = false;
        })
        .catch((err) => {
          this.saveLoad = false;
        });
    },
    // 结束订单
    handleOrderEnd() {
      // console.log(this.tableData, "tanleData");
      // this.tableData.forEach((item) => {
      //   if (!item.invoFileId || !item.dyntFileId) {
      //     this.$message({
      //       message: "请填写相应信息，并选择发票和同行单",
      //       type: "warning",
      //     });
      //     throw new Error("请填写相应信息，并选择发票和同行单");
      //   }
      // });
      // this.$refs.tabledata.validate((valid) => {
        // if (valid) {
          this.$confirm("确认结束订单", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            let data = {
              delvOrdId: this.$route.query.id,
            };
            this.endLoad = true;
            finishMcsDelvOrd(data)
              .then((res) => {
                this.endLoad = false;
                this.$router.push({
                  name: "purOrderDelivery",
                });
              })
              .catch((err) => {
                this.endLoad = false;
              });
          });
        // } else {
          // this.$message({
            // type: "warning",
            // message: "请填写必填项信息",
          // });
        // }
      // });
    },

    // 返回
    handleBack(){
      this.$router.push({
        name: "purOrderDelivery",
        query:{spdId:this.$route.query.spdId,activeName:this.$route.query.activeName}
      });
    }
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table__body tr.hover-row > td {
  background-color: transparent !important;
}
::v-deep .el-table {
  th.el-table__cell.is-leaf,
  td.el-table__cell {
    border-bottom: 1px solid #eee;
  }
}
::v-deep .dd .el-dialog {
  height: 90%;
  margin-top: 30px !important;
}
::v-deep .dd .el-dialog__body {
  height: 90%;
  padding: 0 25px 0px;
}
.chuTable {
  color: #000;
}
.hang {
  height: 30px;
}
</style>
