<template>
  <!-- 待出库 -->
  <div>
    <div class="right-button">
      <el-button style="margin-right:6px" type="danger" @click="handleEnd" :loading="overLoading">结束订单</el-button>
      <el-button style="margin-right:6px" type="primary" @click="handlemultiplex">订单复用</el-button>
    </div>
    <div class="common-card">
      <h3>基本信息</h3>
      <el-form :model="listForm" ref="listform" label-width="180px" 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" v-show="cShow">
      <h3>手术信息</h3>
      <el-form :model="listForm" ref="listform" label-width="150px" class="grid-form-class">
        <div class="form-body">
          <div class="flex-css">
            <el-form-item label="手术名称" prop="oprn">
              <div class="content">
                {{ listForm.oprn }}
              </div>
            </el-form-item>
            <el-form-item label="手术间" prop="oprtRoom">
              <div class="content">
                {{ listForm.oprtRoom }}
              </div>
            </el-form-item>
          </div>
          <div class="flex-css">
            <el-form-item label="主治医生" prop="atddr">
              <div class="content">
                {{ listForm.atddr }}
              </div>
            </el-form-item>
            <el-form-item label="手术日期" prop="oprtTime">
              <div class="content">
                {{ listForm.oprtTime }}
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="common-card">
      <h3>耗材明细</h3>
      <el-form :model="listQuery" ref="listQuery" :inline="true" label-width="90px">
        <el-form-item size="mini" label="生产企业" prop="prodEntp" class="long">
          <el-input v-model="listQuery.prodEntp" placeholder="请输入生产企业"></el-input>
        </el-form-item>
        <el-form-item size="mini" label="是否集采" prop="isFas" class="long">
          <el-select v-model="listQuery.isFas" placeholder="请选择是否集采" clearable>
            <el-option v-for="item in isFasData" :key="item.value" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item size="mini" label="注册证号" prop="regcertno" class="long">
          <el-input v-model="listQuery.regcertno" placeholder="请输入注册证号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getData()">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-form :model="tableData" ref="tabledata">
        <el-table :data="tableData" v-loading="loding" element-loading-text="加载中..." border :span-method="handleSpan" height="500"
          @selection-change="handleSelectionChange">
          <template slot="empty">
            <img src="@/assets/nopage.png" alt />
            <p>暂无数据</p>
          </template>
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column fixed label="序号" width="60">
            <template slot-scope="scope">
              <span>{{ scopIndex(scope.$index) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="耗材编码" prop="prodCode" />
          <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 == '0'">否</span>
              <span v-if="row.isFas == '1'">是</span>
            </template>
          </el-table-column>
          <el-table-column label="包装" prop="convrat" width="120px">
            <template #default="{ row }">
              <span>{{ row.purcUnt }} ({{ row.convrat }}{{ row.prcUnt }}/{{ row.purcUnt }})</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="采购数量" prop="purcCnt" />
          <el-table-column label="采购价" prop="purcPric" >
            <template #default="{ row }">
              <span>{{row.purcPric}}元/{{row.prcUnt}}</span>
            </template>
          </el-table-column> -->
          <!-- <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="lotNumCheck(scope.row, lotNumRule)">
                <el-input placeholder="请输入" v-model="scope.row.lotNum"
                  @change="handleEDIT(scope.row, scope.$index)"></el-input>
              </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="manuDate" width="220" v-if="!cShow">
            <template slot-scope="scope">
              <el-form-item label-width="0" class="item" :prop="scope.$index + '.manuDate'"
                :rules="lotNumCheck(scope.row, manuDateRule)">
                <el-date-picker style="width: 100%" v-model="scope.row.manuDate" :picker-options="TimeOption1"
                  type="date" placeholder="请选择生产日期" value-format="yyyy-MM-dd"
                  @change="handleEDIT(scope.row, scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="有效期至" width="220" prop="prodExpy" v-if="!cShow">
            <template slot-scope="scope">
              <el-form-item label-width="0" class="item" :prop="scope.$index + '.prodExpy'"
                :rules="lotNumCheck(scope.row, prodExpyRule)">
                <el-date-picker style="width: 100%" v-model="scope.row.prodExpy" :picker-options="TimeOption"
                  type="date" placeholder="请选择有效期" value-format="yyyy-MM-dd"
                  @change="handleEDIT(scope.row, scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <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="delvAmt" width="90px">
            <template slot-scope="scope">
              <span>{{ rejAmtNub(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="UDI码" prop="udi" v-if="cShow">
            <!-- <el-table-column label="UDI码" prop="udi"> -->
            <template slot-scope="scope">
              <el-button type="text" @click="handleudi(scope.row, scope.$index)">{{ scope.row.delvCnt }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="报关单" prop="invoFileId" width="200">
            <template slot-scope="scope">
              <yl-upload v-if="scope.row.prodSouc == '2'" :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"
        >提交</el-button>

        <el-button type="info" @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>
    <!-- UDI码 -->
    <el-dialog title="UDI码填写" :visible.sync="udidialog" width="70%" :close-on-click-modal="false"
      :before-close="handleClose">
      <el-form :model="udiData" ref="udiForm">
        <el-table element-loading-text="加载中" :data="udiData" 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="耗材信息" width="230">
            <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 == '0'">否</span>
              <span v-if="row.isFas == '1'">是</span>
            </template>
          </el-table-column>
          <el-table-column label="批号" prop="lotNum">
          </el-table-column>
          <!-- <el-table-column label="生产日期" prop="manuDate">
          </el-table-column>
          <el-table-column label="有效期至" prop="prodExpy">
          </el-table-column> -->
          <el-table-column label="包装" prop="convrat" width="120px">
            <template #default="{ row }">
              <span>{{ row.purcUnt }} ({{ row.convrat }}{{ row.prcUnt }}/{{ row.purcUnt }})</span>
            </template>
          </el-table-column>
          <el-table-column label="UDI码" prop="udi" width="150" fixed="right">
            <template slot-scope="scope">
              <el-form-item label-width="0" class="item" :prop="scope.$index + '.udi'" :rules="[
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur',
                },
              ]">
                <el-input placeholder="请输入" v-model="scope.row.udi"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div class="foot-button" style="margin-top: 30px">
        <el-button type="primary" @click="clickUdi">确 认</el-button>
      </div>
    </el-dialog>
    <!-- 订单复用 mulDialog-->
    <el-dialog title="订单复用" :visible.sync="mulDialog" width="70%">
      <el-table element-loading-text="加载中" :data="mulData" fit stripe border height="500px">
        <template slot="empty">
          <img src="@/assets/nopage.png" alt />
          <p>暂无数据</p>
        </template>
        <el-table-column fixed="left" width="45px">
          <template slot-scope="scope">
            <el-radio v-model="roleRadio" style="margin-left: 10px" :label="scope.row.delvOrdId"
              @change.native="getTemplateRow(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="采购单号" prop="purcOrdId" />
        <el-table-column label="出库单号" prop="delvOrdId" />
        <el-table-column label="手术名称" prop="oprn" />
        <el-table-column label="手术日期" prop="oprtTime" />
        <el-table-column label="品总数" prop="detlCnt">
        </el-table-column>
        <el-table-column label="申领总数" prop="qtySum">
        </el-table-column>
        <el-table-column label="申领金额" prop="purcAmt">
        </el-table-column>
        <el-table-column label="使用数量" prop="bcckl">
        </el-table-column>
        <el-table-column label="使用金额" prop="amt" />
        <el-table-column label="客户名称" prop="branchName" />
        <!-- <el-table-column label="采购员" prop="docmker" /> -->
        <el-table-column label="采购时间" prop="purcTime" />
      </el-table>
      <!--分页-->
      <yl-pagination v-show="totalm > 0" :total="totalm" :page.sync="listQuerym.current" :limit.sync="listQuerym.size"
        @pagination="getOutboundData" />
      <div class="foot-button" style="margin-top: 30px">
        <el-button type="primary" @click="clickMul">确 认</el-button :loading="fyLoad">
      </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 printView from "./printView.vue";
import mcsInfo from "@/views/components/mcs-info.vue";
import { countNumPrice, getTotalAmount } from "@/utils/utils";
import moment from "moment";
import {
  getOrdDetlList,
  getSplerMcsDelvOrdPage,
  retnDelvOrdCommit
} from "@/api/orderManage-sup/index";
import {
  getMcsOrdDckDetl,
  saveDelvOrd,
  finishDelvOrd,
  getBillPage,
  submitMcsDelvOrd,
  selectDelvOrdCopy,
  finishMcsDelvOrd,
} from "@/api/orderManage-sup/index";
export default {
  components: {
    ylStep,
    ylPagination,
    ylUpload,
    mcsInfo,
    printView,
  },
  data() {
    return {
      roleRadio: "",
      cShow: false,
      pdfSrc: "",
      dialogVisible: false,
      saveLoad: false,
      confirmLoad: false,
      endLoad: false,
      number: [],
      delvOrdId: "",
      isLotnum: false, //批号是否有重复
      orderData: [], //出库单打印数据
      lotNumRule: [
        {
          required: true,
          message: "请输入",
          trigger: "blur",
        },
      ],
      manuDateRule: [
        {
          required: true,
          message: "请选择生产日期",
          trigger: "change",
        },
      ],
      prodExpyRule: [
        {
          required: true,
          message: "请选择有效日期",
          trigger: "change",
        },
      ],
      multipleSelection: [],
      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: [],
      fileIndex: null,
      fileIndex1: null,
      endBtn: false,
      listQuery: {
        prodEntp: "",
        isFas: "",
        regcertno: "",
      },
      isFasData: [
        { value: "1", name: "是" },
        { value: "0", name: "否" },
      ],
      TimeOption: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      TimeOption1: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      udidialog: false,
      mulDialog: false,
      udiData: [],
      mulData: [],
      mcsSum: 0,
      purcOrdId: "",
      rowIndex: 0,
      listQuerym: {
        current: 1,
        size: 10,
        id: "",
        branchName: "",
        docmkDateStart: "",
        docmkDateEnd: "",
        docmkDate: [],
        stas: "",
        spdId: this.$route.query.spdId,
        fyLoad: false,
      },
      overLoading: 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;
    this.listForm.oprn = this.$route.query.oprn;
    this.listForm.oprtRoom = this.$route.query.oprtRoom;
    this.listForm.oprtTime = this.$route.query.oprtTime;
    this.listForm.atddr = this.$route.query.atddr;
    if (this.listForm.stas == "部分出库") {
      this.endBtn = true;
    }
    if (this.$route.query.purcType == "2") {
      this.cShow = true;
    } else {
      this.cShow = false;
    }
    // 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: {
    //待出库金额计算
    rejAmtNub(row) {
      row.delvAmt =
        Number(row.delvCnt) * Number(row.convrat) * Number(row.purcPric);
      return parseFloat(row.delvAmt.toFixed(4));
    },
    scopIndex(index) {
      return index + 1;
    },
    lotNumCheck(row, ruleArray) {
      let rule = [];
      let isId = this.multipleSelection.filter((item) => {
        return item.id == row.id;
      });
      if (isId.length > 0) {
        rule = ruleArray;
      } else {
        rule = [];
      }
      return rule;
    },
    //表格选中触发
    handleSelectionChange(val) {
      val.length > 0 &&
        val.map((item) => {
          item.purcOrdId = this.$route.query.id;
          item.materialId = item.prodCode;
        });
      this.multipleSelection = val;
    },
    getData() {
      this.listLoading = true;
      getOrdDetlList({
        delvOrdId: this.$route.query.delvOrdId,
        purcOrdId: this.$route.query.purcOrdId,
        spdId: this.$route.query.spdId,
        prodEntp: this.listQuery.prodEntp,
        isFas: this.listQuery.isFas,
        regcertno: this.listQuery.regcertno
      })
        .then((res) => {
          this.tableData = res.data;
          this.tableData.udiList = [];
          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);
      this.tableData[index].udiList = [];
    },
    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.prodCode == row.prodCode) {
          num += item.delvCnt;
        }
      });
      return num;
    },
    //公共函数
    shanchu(row) {
      this.tableData.forEach(async (item) => {
        await this.numAll(row);
        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);
        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);
        if (item.prodCode == row.prodCode) {
          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;
    },
    // 添加批次
    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,
        convrat: row.convrat,
        prcUnt: row.prcUnt,
        purcUnt: row.purcUnt,
        invoFileId: "",
        lotNum: "",
        manuDate: "",
        prodExpy: "",
        dyntFileId: "",
        isFas: row.isFas,
        // udiList:[],
      };
      this.tableData.splice(index + 1, 0, list);
      list.showDeleteButton = true;
      this.computeCell(this.tableData);
      // const aa = this.tableData.findIndex((item) => item.id === row.id);
      // this.number.splice(aa+1,0,this.number[aa])
    },
    handleEDIT(row, index) {
      this.tableData[index].udiList = [];
    },
    // 筛选合并项
    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].prodCode == tableData[i - 1].prodCode) {
            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 === 2 ||
        columnIndex === 3 ||
        columnIndex === 4 ||
        columnIndex === 5 ||
        columnIndex === 6 ||
        columnIndex === 7 ||
        columnIndex === 8 ||
        columnIndex === 9 ||
        columnIndex === 11 ||
        columnIndex === 12 ||
        columnIndex === 13
      ) {
        // 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,
          };
        }
      }
    },
    //删除
    handleDelete(row, i) {
      const index = this.tableData.findIndex(
        (item) => item.prodCode === row.prodCode
      );
      if (index !== -1) {
        let qwe = this.tableData.findIndex(function (item) {
          return item.prodCode == row.prodCode;
        });
        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();
    },
    // 填写UDI码
    handleudi(row, index) {
      if (row.lotNum && row.delvCnt) {
        this.rowIndex = index;
        if (
          !this.tableData[index].udiList ||
          this.tableData[index].udiList.length == 0 ||
          this.tableData[index].udiList.length !== row.delvCnt ||
          this.tableData[index].lotNum !==
            this.tableData[index].udiList[0].lotNum
        ) {
          let udiObj = {
            ...row,
            udi: "",
          };
          const n = row.delvCnt;
          const copiedObjects = Array.from({ length: n }, () => ({
            ...udiObj,
          }));
          this.tableData[index].udiList = copiedObjects;
        }
        this.$nextTick(() => {
          this.udidialog = true;
          this.udiData = this.tableData[index].udiList;
        });
      } else {
        this.$message.warning("先填写必填信息，再填写UDI码");
      }
    },
    // 去chong
    handleClose() {
      this.udiData.forEach((v) => {
        if (v.udi) {
          let udicf = this.udif(this.udiData);
          if (udicf == true) {
            this.$message({
              message: "同一产品的udi码不能重复",
              type: "error",
            });
            throw new Error("同一产品的udi码不能重复");
          } else {
            this.udidialog = false;
          }
        } else {
          this.udidialog = false;
        }
      });
    },

    // 确定UDI
    clickUdi() {
      this.$refs.udiForm.validate((valid) => {
        if (valid) {
          let udicf = this.udif(this.udiData);
          if (udicf == true) {
            this.$message({
              message: "同一产品的udi码不能重复",
              type: "info",
            });
            throw new Error("同一产品的udi码不能重复");
          }
          this.$confirm("确认提交udi码", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.tableData[this.rowIndex].udiList = this.udiData;
            this.udidialog = false;
          });
        } else {
          this.$message({
            type: "warning",
            message: "请填写必填项信息",
          });
        }
      });
    },
    // 判断一个数组对象的属性是否有重复
    pf(arr) {
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          // console.log(arr[i].prodCode, arr[j].prodCode);
          if (arr[i].prodCode == arr[j].prodCode) {
            var set = new Set(); //创建个集合Set对象（用object对象也可以）
            return arr.some(function (v, i) {
              //遍历 arr数组，当返回值为true时提前退出遍历。
              var f = set.has(v.lotNum); //判断每个对象里number属性的值是否在集合Set
              set.add(v.lotNum); //将number属性的值添加到集合Set中
              return f;
            });
          } else {
            console.log("else");
          }
        }
      }
    },
    udif(arr) {
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          // console.log(arr[i].prodCode, arr[j].prodCode);
          if (arr[i].prodCode == arr[j].prodCode) {
            var set = new Set(); //创建个集合Set对象（用object对象也可以）
            return arr.some(function (v, i) {
              //遍历 arr数组，当返回值为true时提前退出遍历。
              var f = set.has(v.udi); //判断每个对象里number属性的值是否在集合Set
              set.add(v.udi); //将number属性的值添加到集合Set中
              return f;
            });
          } else {
            console.log("else");
          }
        }
      }
    },
    // 选择同行单
    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() {
      if (this.multipleSelection.length <= 0) {
        this.$message({
          message: "请选择出库耗材",
          type: "error",
        });
        return;
      }
      let obj = {};
      let reduce = this.multipleSelection.reduce((curr, next) => {
        obj[next.prodCode + next.lotNum]
          ? ""
          : (obj[next.prodCode + next.lotNum] = curr.push(next));
        return curr;
      }, []);
      if (reduce.length !== this.multipleSelection.length) {
        this.$message({
          message: "同一产品的批号不能重复",
          type: "info",
        });
        return;
      }
      this.multipleSelection.forEach((item) => {
        if (item.delvCnt == "0") {
          this.$message({
            message: "本次出库数量必须大于0",
            type: "warning",
          });
          throw new Error("本次出库数量必须大于0");
        }
        //  if (item.prodSouc=="2" && !item.invoFileId) {
        //   this.$message({
        //     // message: "请填写相应信息，并选择报关单和随货单",
        //     message: "请填写相应信息，并选择报关单",
        //     type: "warning",
        //   });
        //   throw new Error("请填写相应信息，并选择报关单");
        // }
        if (this.cShow == true && (!item.udiList || item.udiList.length == 0)) {
          this.$message.warning("请填写udi再提交");
          throw new Error("请填写udi再提交");
        }
        item.udiList.forEach((v, index) => {
          if (v.udi == "" || v.udi == null) {
            this.$message.warning("请填写udi再提交");
            throw new Error("请填写udi再提交");
          }
        });
      });

      this.$refs.tabledata.validate((valid) => {
        if (valid) {
          this.mcsSum = 0;
          this.multipleSelection.forEach((item) => {
            let rowSum = 0;
            rowSum = item.purcPric * item.convrat * item.delvCnt;
            this.mcsSum += rowSum;
          });
          this.mcsSum = this.mcsSum.toFixed(4);
          this.handleConfirm();
        } else {
          this.$message({
            type: "warning",
            message: "请填写必填项信息",
          });
        }
      });
    },
    // 出库确认
    handleConfirm() {
      this.$confirm("确认出库", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let data2 = {
          delvOrdId: this.$route.query.delvOrdId,
          detlList: this.multipleSelection,
          deptId: this.$route.query.deptId,
          spdId: this.$route.query.spdId,
          deptName: this.$route.query.deptName,
        };
        retnDelvOrdCommit(data2)
          .then((res) => {
            this.printVisible = false;
            this.$message.success("出库成功");
            this.$router.push({
              name: "devsuccs",
              query: {
                form: JSON.stringify({
                  ...this.listForm,
                  delvOrdId: res.data.id,
                  docmker: res.data.docmker,
                  docmkDate: res.data.docmkDate,
                  quit: "outbound",
                }),
                data: JSON.stringify(this.multipleSelection),
              },
            });
          })
          .catch((err) => {
            // this.$message.error("出库失败")
            // 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,
      };
      this.saveLoad = true;
      saveDelvOrd(data2)
        .then((res) => {
          this.saveLoad = false;
        })
        .catch((err) => {
          this.saveLoad = false;
        });
    },
    // 订单复用
    handlemultiplex() {
      this.mulDialog = true;
      this.getOutboundData();
      this.roleRadio = "";
      this.purcOrdId = "";
    },
    // 结束订单
    handleEnd() {
      this.$confirm("确认结束订单", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.overLoading = true;
        let data = {
          purcOrdId: this.$route.query.id,
        };
        finishMcsDelvOrd(data)
          .then((res) => {
            this.overLoading = false;
            this.$message.success("结束订单成功");
            this.$router.push({
              name: "purOrderDelivery",
              query: {
                spdId: this.$route.query.spdId,
                activeName: this.$route.query.activeName,
              },
            });
          })
          .catch((err) => {
            this.overLoading = false;
            this.$message.error("结束订单失败");
          });
      });
    },
    // 复用查询
    getOutboundData() {
      getSplerMcsDelvOrdPage(this.listQuerym)
        .then((res) => {
          this.mulData = res.data.records;
          this.totalm = res.data.total;
        })
        .catch((err) => {});
    },
    // 返回
    handleBack() {
      this.$router.push({
        name: "purOrderDelivery",
        query: {
          spdId: this.$route.query.spdId,
          activeName: this.$route.query.activeName,
        },
      });
    },
    // 重置
    reset() {
      this.$refs.listQuery.resetFields();
      this.getData();
    },
    // 复用单选
    getTemplateRow(index, row) {
      this.purcOrdId = row.purcOrdId;
      this.delvOrdId = row.delvOrdId;
    },
    // 复用确认
    clickMul() {
      if (!this.purcOrdId) {
        this.$message.warning("请选择要复用的订单");
      } else {
        this.$confirm("确认复用该订单", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          selectDelvOrdCopy({
            delvOrdId: this.delvOrdId,
            purcOrdId: this.purcOrdId,
          })
            .then((res) => {
              this.fyLoad = true;
              if (res.success == true) {
                this.$message.success("操作成功");
                this.mulDialog = false;
                this.fyLoad = false;
                this.purcOrdId = "";
              } else {
                // this.$message.error("操作失败")
                this.$message(res.message);
                this.fyLoad = false;
                this.purcOrdId = "";
              }
            })
            .catch((err) => {
              // this.$message(res.message)
              this.fyLoad = false;
            });
        });
      }
    },
  },
};
</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>
