<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="编码" prop="code">
            <el-input
              v-model="queryParams.code"
              placeholder="请输入编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结算开始日期" prop="startDate">
            <el-date-picker clearable
                            v-model="queryParams.startDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择结算开始日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结算截止日期" prop="endDate">
            <el-date-picker clearable
                            v-model="queryParams.endDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择结算截止日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结算单号" prop="settleNo">
            <el-input
              v-model="queryParams.settleNo"
              placeholder="请输入结算单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :offset="21">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pu:doc:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pu:doc:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pu:doc:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pu:doc:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="docList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编码" align="center" prop="code" :width="tableAttr.width"/>
      <el-table-column label="服务费" align="center" prop="serviceFee" :width="tableAttr.width"/>
      <el-table-column label="医院编码" align="center" prop="custCode" :width="tableAttr.width"/>
      <el-table-column label="医院名称" align="center" prop="custName" :width="tableAttr.width"/>
      <el-table-column label="供应商编码" align="center" prop="supplierCode" :width="tableAttr.width"/>
      <el-table-column label="供应商名称" align="center" prop="supplierName" :width="tableAttr.width"/>
      <el-table-column label="结算单号" align="center" prop="settleNo" :width="tableAttr.width"/>
      <el-table-column label="结算开始日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结算截止日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合计金额" align="center" prop="totalAmount" :width="tableAttr.width"/>
      <el-table-column label="备注" align="center" prop="remark" :width="tableAttr.width"/>
      <el-table-column label="是否汇总" align="center" prop="isSum" :width="tableAttr.width"/>
      <el-table-column label="审批人" align="center" prop="approver" :width="tableAttr.width"/>
      <el-table-column label="单据状态" align="center" prop="verifyState" :width="tableAttr.width"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pu:doc:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pu:doc:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改或查看【消耗单明细主表】对话框 -->
    <el-drawer :title="title" :visible.sync="open" direction="rtl" size="100%">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col span="6">
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="编码后台自动生成" disabled :size="tableAttr.attrSize.mini"/>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="服务费合计" prop="serviceFee">
              <el-input-number
                v-model="form.serviceFee" placeholder="自动汇总服务费" :precision="tableAttr.decimal" :step="0.1" :min="0" :size="tableAttr.attrSize.medium" disabled>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="医院编码" prop="custCode">
              <el-input v-model="form.custCode" placeholder="请输入医院编码" :disabled="tableAttr.isShow" :size="tableAttr.attrSize.mini"/>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="医院名称" prop="custName">
              <el-input v-model="form.custName" placeholder="请输入医院名称" :disabled="tableAttr.isShow" :size="tableAttr.attrSize.mini"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col span="6">
            <el-form-item label="供应商编码" prop="supplierCode">
              <el-input v-model="form.supplierCode" placeholder="请输入供应商编码" :disabled="tableAttr.isShow" :size="tableAttr.attrSize.mini"/>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称" :disabled="tableAttr.isShow" :size="tableAttr.attrSize.mini"/>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="结算单号" prop="settleNo">
              <el-input v-model="form.settleNo" placeholder="请输入结算单号" :disabled="tableAttr.isShow" :size="tableAttr.attrSize.mini"/>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="结算开始日期" prop="startDate">
              <el-date-picker clearable
                              v-model="form.startDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择结算开始日期" :disabled="tableAttr.isShow" :size="tableAttr.attrSize.mini">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col span="6">
            <el-form-item label="结算截止日期" prop="endDate">
              <el-date-picker clearable
                              v-model="form.endDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择结算截止日期" :disabled="tableAttr.isShow" :size="tableAttr.attrSize.mini">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="合计金额" prop="totalAmount">
              <el-input-number
                v-model="form.totalAmount" placeholder="自动汇总小计" :precision="tableAttr.decimal" :step="0.1" :min="0" :size="tableAttr.attrSize.medium" disabled>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" :disabled="tableAttr.isShow" :size="tableAttr.attrSize.mini"/>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="单据状态" prop="verifyState">
              <el-select v-model="form.verifyState" disabled :size="tableAttr.attrSize.mini">
                <el-option v-for="dict in dict.type.sys_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div>
        <el-row :gutter="10" class="mb8" style="display: flex; justify-content: flex-end;">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addRow">增行</el-button>
          </el-col>
        </el-row>
        <el-tabs type="border-card" style="width: 99%; margin: 0 auto;">
          <el-tab-pane label="消耗单明细">
            <el-table :data="docItemList" @selection-change="handleSelectionChange" :max-height="tableAttr.maxHeight">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="医保编码" align="center" prop="healthCode" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input v-model="docItemList[scope.$index].healthCode" placeholder="请输入医保编码" :size="tableAttr.attrSize.mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="物料编码" align="center" prop="itemCode" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input v-model="docItemList[scope.$index].itemCode" placeholder="请输入物料编码" :size="tableAttr.attrSize.mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="物料名称" align="center" prop="itemName" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input v-model="docItemList[scope.$index].itemName" placeholder="请输入物料名称" :size="tableAttr.attrSize.mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="规格型号" align="center" prop="itemSpec" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input v-model="docItemList[scope.$index].itemSpec" placeholder="请输入规格型号" :size="tableAttr.attrSize.mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="厂家" align="center" prop="manufactor" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input v-model="docItemList[scope.$index].manufactor" placeholder="请输入厂家" :size="tableAttr.attrSize.mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="单位" align="center" prop="itemUom" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input v-model="docItemList[scope.$index].itemUom" placeholder="请输入单位" :size="tableAttr.attrSize.mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="是否带量" align="center" prop="isWhether" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-select v-model="docItemList[scope.$index].isWhether" :size="tableAttr.attrSize.mini">
                    <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label"
                               :value="dict.value"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="服务费率%" align="center" prop="ratio" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="docItemList[scope.$index].ratio" :precision="tableAttr.decimal" :step="1" :min="0" :size="tableAttr.attrSize.mini"
                    @change="calculateServiceFee(scope.$index, docItemList[scope.$index].ratio, docItemList[scope.$index].amount)">
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" prop="qty" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input-number v-model="docItemList[scope.$index].qty" :step="1" :min="0" :size="tableAttr.attrSize.mini"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="单价" align="center" prop="price" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="docItemList[scope.$index].price" :precision="tableAttr.decimal" :step="0.1" :min="0" :size="tableAttr.attrSize.mini">
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="小计" align="center" prop="amount" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="docItemList[scope.$index].amount" :precision="tableAttr.decimal" :step="0.1" :min="0" :size="tableAttr.attrSize.mini" disabled>
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="detailRemark" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input v-model="docItemList[scope.$index].detailRemark" placeholder="请输入备注" :size="tableAttr.attrSize.mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="服务费" align="center" prop="serviceFee" :width="tableAttr.subWidth">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="docItemList[scope.$index].serviceFee" :precision="tableAttr.decimal"
                    :step="0.1" :min="0" :size="tableAttr.attrSize.mini" disabled
                  >
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :width="tableAttr.width" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                  >复制
                  </el-button>
                  <el-button
                    @click.native.prevent="deleteRow(scope.$index, docItemList)"
                    type="text"
                    size="small">
                    删行
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <div slot="footer" class="dialog-footer" style="margin-left: 90%; margin-top: 1%">
          <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
          <el-button @click="cancel" size="mini">返 回</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {listDoc, getDoc, delDoc, addDoc, updateDoc} from "@/api/business/spd/sales/doc";
import * as util from "@/api/business/spd/sales/utils"

export default {
  dicts: ["sys_status", "sys_yes_no"],
  name: "Doc",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【消耗单明细主表】表格数据
      docList: [],
      docItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        dr: null,
        supplierName: null,
        supplierCode: null,
        startDate: null,
        custCode: null,
        endDate: null,
        totalAmount: null,
        settleNo: null,
        serviceFee: null,
        isSum: null,
        approver: null,
        verifyState: null,
        custName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      tableAttr: {
        width: 100,
        subWidth: 150,
        isShow: false,
        decimal: 2,
        attrSize: {
          medium: 'medium',
          large: 'large',
          small: 'small',
          mini: 'mini'
        },
        maxHeight: 250
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【消耗单明细主表】列表 */
    getList() {
      this.loading = true;
      listDoc(this.queryParams).then(response => {
        this.docList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        dr: null,
        supplierName: null,
        supplierCode: null,
        startDate: null,
        custCode: null,
        endDate: null,
        remark: null,
        totalAmount: null,
        settleNo: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        serviceFee: null,
        isSum: null,
        approver: null,
        verifyState: null,
        custName: null,
        docItemList: []
      };
      this.docItemList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.verifyState = '0'
      this.open = true;
      this.title = "添加【消耗单明细主表】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDoc(id).then(response => {
        this.form = response.data;
        this.docItemList = JSON.parse(JSON.stringify(response.data.itemList))
        this.open = true;
        this.title = "修改【消耗单明细主表】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.docItemList = JSON.parse(JSON.stringify(this.docItemList))
            console.log('form', this.form);
            updateDoc(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              console.log('response', response);
            });
          } else {
            addDoc(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function () {
        return delDoc(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pu/doc/export', {
        ...this.queryParams
      }, `doc_${new Date().getTime()}.xlsx`)
    },
    // 子表删行
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    // 子表增行
    addRow() {
      let docItem = {
        healthCode: '',
        itemCode: '',
        itemName: '',
        itemSpec: '',
        manufactor: '',
        itemUom: '',
        isWhether: '',
        ratio: 0,
        qty: 0,
        price: 0,
        amount: 0,
        detailRemark: '',
        serviceFee: null,
        createBy: this.$store.state.user.name,
        createTime: util.getCurrentTime('yyyy-MM-dd HH:mm:ss'),
        updateBy: this.$store.state.user.name,
        dr: 0,
        parent: (this.form.id === null || this.form.id === undefined) ? this.form.id : null
      }
      this.docItemList.push(docItem)
    },
    // 计算子表服务费
    calculateServiceFee(index, ratio, amount) {
      this.docItemList[index].serviceFee = (ratio/100) * amount
      let docItemList = this.docItemList;
      let amountSum = 0
      let serviceFeeSum = 0
      for (const element of docItemList) {
        amountSum += element.amount > 0 ? element.amount : 0
        serviceFeeSum += element.serviceFee > 0 ? element.serviceFee : 0
      }
      this.form.totalAmount = amountSum
      this.form.serviceFee = serviceFeeSum
    }
  }
};
</script>
