<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>
      <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="invoName" :rules="rules.required">
                <el-input
                v-if="isShow"
                v-model="listForm.invoName"
                placeholder="请输入开票名称"
                maxlength="50"
              ></el-input>
              <div class="content" v-else>
                {{listForm.invoName}}
              </div>
            </el-form-item>
            <el-form-item label="发票号码" prop="invoNo"  :rules="rules.required">
                <el-input
                v-if="isShow"
                v-model="listForm.invoNo"
                placeholder="请输入发票号码"
                maxlength="50"
              ></el-input>
              <div class="content" v-else>
                {{listForm.invoNo}}
              </div>
            </el-form-item>
            <el-form-item label="开票日期" prop="invoDate"  :rules="rules.dateRequired">
                <el-date-picker
                v-model="listForm.invoDate"
                type="date"
                value-format="yyyy-MM-dd"
                v-if="isShow"
                placeholder="选择日期">
                </el-date-picker>
                <div class="content" v-else>
                {{listForm.invoDate}}
              </div>
            </el-form-item>
          </div>
          <div class="flex-css">
            <el-form-item label="开票金额" prop="invoAmt"  :rules="rules.numPot2">
                <el-input
                v-if="isShow"
                v-model="listForm.invoAmt"
                placeholder="请输入开票金额"
                maxlength="50"
              ></el-input>
              <div class="content" v-else>
                {{listForm.invoAmt}}
              </div>
            </el-form-item>
            <el-form-item label="发票文件"  prop="invoFile" :rules="rules.uploadRequired" >
                <yl-upload
                v-if="isShow"
              :fileId="listForm.invoFile"
              @getUpload="getUpload"
              urlName="acco"
            >
              <template v-slot:dec>只能上传pdf文件</template>
            </yl-upload>
            <yl-upload
                v-else
              :fileId="listForm.invoFile"
              readonly
            >
            </yl-upload>
            </el-form-item>
             <el-form-item label="核验文件" prop="invoChkFile"  :rules="rules.uploadRequired" >
                <yl-upload
                v-if="isShow"
              :fileId="listForm.invoChkFile"
              @getUpload="getUpload1"
              urlName="acco"
            >
              <template v-slot:dec>只能上传pdf文件</template>
            </yl-upload>
            <yl-upload
                v-else
              :fileId="listForm.invoChkFile"
              readonly
            >
            </yl-upload>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="common-card">
      <h3>明细信息</h3>
      <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="retnCnt" align="center"/> -->
          <!-- <el-table-column label="有效期" prop="prodEntp" align="center"/> -->
          <el-table-column label="厂商" prop="prodEntp" align="center"/>
          </el-table-column>
          </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="danger" @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} from "@/api/procurement-settlement/index"
import rules from "@/utils/rules";

export default {
  components: {
    ylStep,
    ylPagination,
    ylUpload,
  },
  data() {
    return {
      total:"",
      rules,
      listForm: {
        stmtNo:"",
        branchName:"",
        isFas:"",
        amt:"",
        stmtPrd:"",
        stas:"",
        invoFile:"",
        invoChkFile:"",
        invoName:"",
        invoNo:"",
        invoDate :"",
        invoAmt:"",
      },
      stasOptions: [
        { value: "C", lable: "待录入发票" },
        { value: "D", lable: "已录入发票" },
      ],
      isFasOptions: [
        { value: "0", lable: "非集采" },
        { value: "1", lable: "集采" },
      ],
      listLoading: false,
      list: [{prodName:"q",amt:"1"},{prodName:"v",amt:"3"},{prodName:"w",amt:"2"}],
      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 == "C") {
      this.isShow = true;
    } else {
      this.isShow = false;
    }
    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: {
    //设置表格第一行的颜色
    // 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) {
      this.listForm.invoFile = id;
      if (id) {
        this.$refs.listform.clearValidate("invoFile");
        console.log(this.listForm.invoFile,"this.listForm.invoFile")
      } else {
        this.$refs.listform.validateField("invoFile");
      }
    },
    getUpload1(id) {
      this.listForm.invoChkFile = id;
      if (id) {
        this.$refs.listform.clearValidate("invoChkFile");
        console.log(this.listForm.invoChkFile,"this.listForm.invoChkFile")
      } else {
        this.$refs.listform.validateField("invoChkFile");
      }
    },
    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() {
        this.$refs["listform"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.submitLoad = true;
              this.listForm.stas = "D";
              insertSetlInvo(this.listForm)
                .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%;
 }
}


</style>
