<template>
  <!-- 耗材退货管理————待确认 -->
  <div>
    <!-- <div class="right-button">
      <el-button type="primary" v-print="printObj">打印</el-button>
      <el-button type="primary"  @click="handleConfirm" :loading="sureLoading"
        >确 认</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="stmtNo">
              <div class="content">
                {{ listForm.stmtNo }}
              </div>
            </el-form-item>
            <el-form-item label="客户名称" prop="branchName">
              <div class="content">
                {{ listForm.branchName }}
              </div>
            </el-form-item>
            <!-- <el-form-item label="对账类型" prop="isFas">
              <div class="content">
                {{ listForm.isFas }}
              </div>
            </el-form-item> -->
            <el-form-item label="对账周期" prop="stmtPrd">
              <div class="content">
                {{ listForm.stmtPrd }}
              </div>
            </el-form-item>
          </div>
          <div class="flex-css">
            <el-form-item label="对账金额" prop="amt">
              <div class="content">
                {{ listForm.amt }}
              </div>
            </el-form-item>
            <el-form-item label="状态" prop="stas">
              <div class="content">
                {{ listForm.stas }}
              </div>
            </el-form-item>
            <el-form-item label=" " prop="">
              <div class="content"></div>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="common-card">
      <h3>发票信息</h3>
      <div
        style="
          width: 120px;
          height: 40px;
          position: absolute;
          right: 20px;
          top: 5px;
        "
      >
        <el-button type="primary" @click="addInvoData()" v-if="isShow"
          >添加发票信息</el-button
        >
      </div>
      <el-form :model="invoForm" ref="invoForm">
        <el-table
          ref="table"
          v-loading="listLoading"
          element-loading-text="加载中"
          :data="invoForm.invoData"
          class="print-table"
          border
        >
          <template slot="empty">
            <img src="@/assets/nopage.png" alt />
            <p>暂无数据</p>
          </template>
          <el-table-column type="index" label="序号" border align="center" />
          <el-table-column label="开票名称" props="invoName" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'invoData.' + scope.$index + '.invoName'"
                :rules="rules.required"
              >
                <el-input
                  v-model="scope.row.invoName"
                  placeholder="请输入开票名称"
                  maxlength="50"
                  v-if="isShow"
                ></el-input>
                <span v-else>{{ scope.row.invoName }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="发票号码" props="invoNo" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'invoData.' + scope.$index + '.invoNo'"
                :rules="rules.required"
              >
                <el-input
                  v-model="scope.row.invoNo"
                  placeholder="请输入发票号码"
                  maxlength="50"
                  v-if="isShow"
                ></el-input>
                <span v-else>{{ scope.row.invoNo }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="开票日期" props="invoDate" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'invoData.' + scope.$index + '.invoDate'"
                :rules="rules.dateRequired"
              >
                <el-date-picker
                  v-model="scope.row.invoDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  v-if="isShow"
                >
                </el-date-picker>
                <span v-else>{{ formatDate(scope.row.invoDate) }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="开票金额" props="invoAmt" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'invoData.' + scope.$index + '.invoAmt'"
                :rules="rules.numPot2"
              >
                <el-input
                  v-model="scope.row.invoAmt"
                  placeholder="请输入开票金额"
                  maxlength="50"
                  v-if="isShow"
                ></el-input>
                <span v-else>{{ scope.row.invoAmt }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="发票文件" props="invoFile" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'invoData.' + scope.$index + '.invoFile'"
                :rules="rules.uploadRequired"
                style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                "
              >
                <yl-upload
                  :fileId="scope.row.invoFile"
                  @getUpload="getUpload"
                  urlName="acco"
                  :index="scope.$index"
                  :readonly="!isShow"
                >
                  <!-- <template v-slot:dec>只能上传pdf文件</template> -->
                </yl-upload>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="核验文件" props="invoChkFile" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'invoData.' + scope.$index + '.invoChkFile'"
                :rules="rules.uploadRequired"
                style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                "
              >
                <yl-upload
                  :fileId="scope.row.invoChkFile"
                  @getUpload="getUpload1"
                  urlName="acco"
                  :index="scope.$index"
                  :readonly="!isShow"
                >
                  <!-- <template v-slot:dec>只能上传pdf文件</template> -->
                </yl-upload>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope" v-if="isShow">
              <div>
                <el-button type="text" @click="deleteInvoData(scope.$index)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="common-card">
      <h3>明细信息</h3>
      <div class="right-btn">
        <el-button type="primary" @click="exportExal()">导出</el-button>
      </div>
      <div id="printMe">
        <el-table
          ref="table"
          v-loading="listLoading"
          element-loading-text="加载中"
          :data="list"
          show-summary
          :summary-method="getSummaries"
          :span-method="arraySpanMethod"
          show-summary
          :header-cell-style="getRowClass"
          class="print-table"
        >
          <template slot="empty">
            <img src="@/assets/nopage.png" alt />
            <p>暂无数据</p>
          </template>
          <el-table-column :label="tableLabel" align="center">
            <!-- :header-cell-style="{background:'#ccc',borderColor:'#000'}" -->
            <el-table-column type="index" label="序号" border align="center" />
            <el-table-column label="耗材名称" prop="prodName" align="center" />
            <el-table-column label="规格" prop="spec" align="center" />
            <el-table-column label="型号" prop="mol" align="center">
            </el-table-column>
            <el-table-column label="数量" prop="cnt" align="center" />
            <el-table-column label="单位" prop="unt" align="center" />
            <el-table-column label="单价" prop="pric" align="center" />
            <el-table-column label="总计" prop="amt" align="center" />
            <el-table-column label="类别" prop="mcsType" align="center">
              <template #default="{ row }">
                <span v-if="row.mcsType == '0'">普通耗材</span>
                <span v-if="row.mcsType == '1'">高值耗材</span>
                <span v-if="row.mcsType == '2'">试剂</span>
              </template>
            </el-table-column>
            <el-table-column label="是否集采" prop="isFas" align="center">
              <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" align="center">
            </el-table-column>
            <el-table-column label="厂商" prop="prodEntp" align="center" />
          </el-table-column>
        </el-table>
        <p class="price-css">共计 {{ total }} 条</p>
      </div>
    </div>
    <div class="foot-button">
      <el-button
        type="primary"
        @click="handleSubmit"
        :loading="submitLoad"
        v-if="isShow"
        >提交</el-button
      >
      <el-button type="info" @click="handleBack">返 回</el-button>
    </div>
  </div>
</template>

<script>
import ylStep from "@/components/yl-step";
import ylPagination from "@/components/yl-pagination";
import ylUpload from "@/components/yl-upload";
import {
  selectSetlStmtDetlD,
  insertSetlInvo,
  exportAllSetlExcel
} from "@/api/procurement-settlement/index";
import { exportData } from "../../consumCataManage-sup/const.js";
import moment from "moment";
import rules from "@/utils/rules";

export default {
  components: {
    ylStep,
    ylPagination,
    ylUpload
  },
  data() {
    return {
      total: "",
      rules,
      invoForm: {
        invoData: [] //发票数据
      },
      listForm: {
        stmtNo: "",
        branchName: "",
        isFas: "",
        amt: "",
        stmtPrd: "",
        stas: "",
        invoFile: "",
        invoChkFile: "",
        invoName: "",
        invoNo: "",
        invoDate: "",
        invoAmt: ""
      },
      stasOptions: [
        { value: "B", lable: "待录入发票" },
        { value: "C", lable: "已录入发票" },
        { value: "R", lable: "已撤回" }
      ],
      isFasOptions: [
        { value: "0", lable: "非集采" },
        { value: "1", lable: "集采" }
      ],
      listLoading: false,
      list: [],
      isShow: false,
      sureLoading: false,
      printLoading: false,
      tableLabel: "",
      submitLoad: false,
      // 打印
      printObj: {
        id: "printMe",
        popTitle: "", // 打印配置页上方标题
        extraHead: "", //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: "", // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: "", // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: "", // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: "", // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        beforeEntryIframe() {
          const cells = document.querySelectorAll(".cell");
          for (let k7 = 0; k7 < cells.length; k7++) {
            const cell = cells[k7];
            // 在这里添加样式只是修改了打印的样式，不会污染原页面的样式
            // 为了让表格中的内容自动换行，不需要的话可以删掉
            cell.style.whiteSpace = "pre-wrap";
          }
        },
        // beforeEntryIframe(copy) {
        //   console.log(copy,"copy")
        //   // copy是ele对象的深度拷贝，修改copy对象不会更改页面中table表格的样式，只会更改打印预览生成的表格的样式
        //   const cells = copy.querySelectorAll('.cell');
        //   const tableNode = copy.querySelectorAll('.el-table__header,.el-table__body');
        //   ;[].slice.call(cells).forEach(item => {
        //     // 为了让表格中的内容自动换行，不需要的话可以删掉
        //     item.style.whiteSpace = 'pre-wrap'
        //   })
        //   // el-table打印不全的问题
        //   ;[].slice.call(tableNode).forEach(item => {
        //     item.style.width = '100%';
        //     const child = item.childNodes;
        //     ;[].slice.call(child).forEach(element => {
        //       if(element.localName === 'colgroup') {
        //         element.innerHTML = ''
        //       }
        //     })
        //   })
        // },
        previewBeforeOpenCallback() {}, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback: () => {}, // 开启打印前的回调事件
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback() {}, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: "",
        standard: "",
        extraCss: ""
      }
    };
  },
  created() {
    if (this.$route.query.stas == "B" || this.$route.query.stas == "R") {
      this.isShow = true;
    } else {
      this.isShow = false;
    }
    this.invoForm.invoData = JSON.parse(this.$route.query.invoFile) || [];
    this.tableLabel = this.$route.query.branchName + "对账明细";
    this.listForm.stmtNo = this.$route.query.stmtNo;
    this.listForm.branchName = this.$route.query.branchName;
    this.listForm.amt = this.$route.query.amt;
    this.listForm.stmtPrd = this.$route.query.stmtPrd;
    this.listForm.invoFile = this.$route.query.invoFile;
    this.listForm.invoChkFile = this.$route.query.invoChkFile;
    this.listForm.invoName = this.$route.query.invoName;
    this.listForm.invoNo = this.$route.query.invoNo;
    this.listForm.invoAmt = this.$route.query.invoAmt;
    this.listForm.invoDate = this.$route.query.invoDate;
    this.stasOptions.forEach(i => {
      if (i.value == this.$route.query.stas) {
        this.listForm.stas = i.lable;
      }
    });
    this.isFasOptions.forEach(i => {
      if (i.value == this.$route.query.isFas) {
        this.listForm.isFas = i.lable;
      }
    });
  },
  mounted() {
    this.getData();
  },
  methods: {
    //导出
    exportExal() {
      exportAllSetlExcel({ stmtNo: this.$route.query.stmtNo }).then(res => {
        const _res = res.data;
        exportData(_res, "对账明细");
      });
    },
    formatDate(row) {
      return moment(row).format("YYYY-MM-DD");
    },
    //删除某一行发票
    deleteInvoData(index) {
      let newTableData = [...this.invoForm.invoData];
      newTableData.splice(index, 1);
      this.invoForm.invoData = newTableData;
    },
    //添加发票
    addInvoData() {
      let itemTableData = {
        invoName: "",
        invoNo: "",
        invoDate: "",
        invoAmt: "",
        invoFile: "",
        invoChkFile: ""
      };
      this.invoForm.invoData = [...this.invoForm.invoData, itemTableData];
    },
    //设置表格第一行的颜色
    // getRowClass({ row, column, rowIndex, columnIndex }) {
    //     return "background:#e2e1e1;text-align:center";
    // },
    arraySpanMethod() {
      //table合计行合并单元格
      setTimeout(() => {
        if (this.$refs.table.$el) {
          let current = this.$refs.table.$el
            .querySelector(".el-table__footer-wrapper")
            .querySelector(".el-table__footer");
          let cell = current.rows[0].cells;
          cell[1].colSpan = "13";
        }
      }, 50);
    },
    getSummaries(param) {
      //table自定义合计行方法summary-method
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 7) {
          const values = data.map(item => Number(item[column.property]));
          sums[1] = values.reduce((prev, curr) => {
            return prev + curr;
          }, 0);
          sums[1] = sums[1].toFixed(2) + "元";
        }
      });
      return sums;
    },
    getUpload(id, index) {
      this.$set(this.invoForm.invoData[index], "invoFile", id);
      this.invoForm = JSON.parse(JSON.stringify(this.invoForm));
      if (id) {
        this.$refs.invoForm.clearValidate("invoFile");
      } else {
        this.$refs.invoForm.validateField("invoFile");
      }
      this.$nextTick(() => {
        this.$refs.invoForm.validate();
      });
    },
    getUpload1(id, index) {
      this.$set(this.invoForm.invoData[index], "invoChkFile", id);
      this.invoForm = JSON.parse(JSON.stringify(this.invoForm));
      if (id) {
        this.$refs.invoForm.clearValidate("invoChkFile");
      } else {
        this.$refs.invoForm.validateField("invoChkFile");
      }
      this.$nextTick(() => {
        this.$refs.invoForm.validate();
      });
    },
    getData() {
      this.listLoading = true;
      selectSetlStmtDetlD({ stmtNo: this.$route.query.stmtNo })
        .then(res => {
          this.list = res.data;
          this.total = this.$route.query.detlCnt;
          this.listLoading = false;
        })
        .catch(err => {
          this.listLoading = false;
        });
    },
    // 确认
    handleSubmit() {
      if (this.invoForm.invoData.length <= 0) {
        this.$message({
          message: "请添加发票信息",
          type: "error"
        });
        return;
      }
      this.$refs["invoForm"].validate(valid => {
        if (valid) {
          this.$confirm("确认提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.submitLoad = true;
              this.invoForm.invoData.map(item => {
                item.stmtNo = this.$route.query.stmtNo;
              });
              insertSetlInvo(this.invoForm.invoData)
                .then(response => {
                  this.$message({
                    message: "提交成功",
                    type: "success"
                  });
                  this.submitLoad = false;
                  this.$router.push({
                    name: "InvoiceManage",
                    query: {
                      spdId: this.$route.query.spdId,
                      activeNameTab: this.$route.query.activeNameTab
                    }
                  });
                })
                .catch(() => {
                  this.submitLoad = false;
                  this.$message({
                    message: "提交失败",
                    type: "error"
                  });
                });
            })
            .catch(() => {});
        }
      });
    },
    // 返回
    handleBack() {
      this.$router.push({
        name: "InvoiceManage",
        query: {
          spdId: this.$route.query.spdId,
          activeNameTab: this.$route.query.activeNameTab
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
#printMe {
  ::v-deep .print-table {
    border: 1px solid #999;
    td,
    th {
      border-right: 1px solid #999;
      border-bottom: 1px solid #999;
    }
  }
  ::v-deep .price-css {
    margin-left: 94%;
  }
}
.right-btn {
  width: 100%;
  height: 50px;
  padding-right: 20px;
  position: absolute;
  left: 0;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
