<template>
  <div id="editExpendMx">
    <el-card style="position: relative">
      <span>基本信息</span>
      <el-form
        :model="basicForm"
        :rules="basicRules"
        ref="basic"
        label-width="auto"
        :show-message="false"
      >
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-form-item label="编码" prop="code">
              <el-input
                style="width: 200px"
                clearable
                disabled
                :size="size"
                v-model="basicForm.code"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="服务费合计" prop="serviceFee">
              <el-input-number
                style="width: 200px"
                clearable
                disabled
                v-model="publishedBooksMessage"
                :size="size"
                :precision="2"
              >
                <!-- <el-input style="width: 200px" clearable disabled :size="size" v-model="basicForm.serviceFee"> -->
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="医院编码" prop="custCode">
              <el-input
                style="width: 200px"
                clearable
                :disabled="sonDisable"
                :size="size"
                v-model="basicForm.custCode"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="医院名称" prop="custName">
              <el-input
                style="width: 200px"
                clearable
                :disabled="sonDisable"
                :size="size"
                v-model="basicForm.custName"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="供应商编码" prop="supplierCode">
              <el-input
                style="width: 200px"
                clearable
                :disabled="sonDisable"
                :size="size"
                v-model="basicForm.supplierCode"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input
                style="width: 200px"
                clearable
                :disabled="sonDisable"
                :size="size"
                v-model="basicForm.supplierName"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="结算单号" prop="settleNo">
              <el-input
                style="width: 200px"
                clearable
                :disabled="sonDisable"
                :size="size"
                v-model="basicForm.settleNo"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="结算开始日期" prop="startDate">
              <el-date-picker
                v-model="basicForm.startDate"
                :disabled="sonDisable"
                clearable
                type="date"
                value-format="yyyy-MM-dd"
                :size="size"
                style="width: 200px"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="结算截止日期" prop="endDate">
              <el-date-picker
                v-model="basicForm.endDate"
                :disabled="sonDisable"
                clearable
                type="date"
                value-format="yyyy-MM-dd"
                :size="size"
                style="width: 200px"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="合计金额" prop="totalAmount">
              <el-input-number
                style="width: 200px"
                clearable
                disabled
                v-model="publishedBooksMessage2"
                :size="size"
                :precision="2"
              >
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="是否汇总" prop="isSum">
              <el-select
                style="width: 200px"
                :size="size"
                :disabled="true"
                clearable
                v-model="basicForm.isSum"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="汇总单据号" prop="sumCode">
              <el-input
                style="width: 200px"
                disabled
                :size="size"
                v-model="basicForm.sumCode"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="是否带量" prop="isWhether">
              <el-select
                style="width: 200px"
                :size="size"
                :disabled="sonDisable"
                clearable
                v-model="basicForm.isWhether"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options1"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="备注" prop="remark">
              <el-input
                style="width: 200px"
                clearable
                :disabled="sonDisable"
                :size="size"
                v-model="basicForm.remark"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="btn_group">
        <!-- <el-button type="primary" :size="size"  @click="toOA" v-if="sonPageStu == 'check'">提交</el-button> -->
        <el-button
          type="primary"
          :size="size"
          @click="editPage"
          v-if="sonPageStu == 'check'"
          >编辑</el-button
        >
        <el-button
          type="primary"
          :size="size"
          @click="save"
          v-if="sonPageStu == 'add' || sonPageStu == 'edit'"
          >保存</el-button
        >
        <el-button :size="size" plain @click="back">返回</el-button>
      </div>

      <div class="btn_grooup">
        <span>明细信息</span>
        <div>
          <el-button
            type="primary"
            :size="size"
            @click="editLine"
            v-if="!sonDisable"
            >批量修改</el-button
          >
          <el-button
            v-if="sonPageStu == 'check'"
            :size="size"
            :disabled="!(basicForm.isSum == '0' && (basicForm.sumCode == null || basicForm.sumCode == ''))"
            @click="cancelDisassembly"
            >取消拆单</el-button
          >
          <el-button
            v-if="sonPageStu == 'check'"
            :size="size"
            :disabled="!ids.length"
            @click="useDisassembly"
            >拆 单</el-button
          >
          <!-- <el-button type="primary" :size="size" @click="delLines" v-if="!sonDisable">删行</el-button> -->
        </div>
      </div>

      <el-dialog
        title="批量修改"
        @close="clearInfo"
        :visible.sync="dialogFormVisible"
      >
        <el-form :model="dialogForm" label-width="auto">
          <el-form-item label="明细信息">
            <el-select :size="size" v-model="dialogForm.region">
              <el-option label="服务费率" value="ratio"></el-option>
              <el-option label="单价" value="price"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="修改值">
            <el-input-number
              clearable
              :size="size"
              :min="0"
              v-model="dialogForm.info"
            ></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :size="size" @click="dialogFormVisible = false"
            >取 消</el-button
          >
          <el-button :size="size" type="primary" @click="confirm"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <ux-grid
        :data="basicForm.itemList"
        border
        :cell-style="{ borderColor: '#c0c0c0' }"
        :header-cell-style="{ borderColor: '#c0c0c0' }"
        class="exporttable"
        height="410"
        max-height="410"
        style="font-size: 12px"
        @selection-change="handleSelectionChange"
        ref="table"
        show-header-overflow="tooltip"
        show-overflow="tooltip"
        keep-source
        beautifyTable
        :checkbox-config="{ highlight: true, trigger: 'row' }"
        :edit-config="{ trigger: 'click', mode: 'row'}"
      >
        >
        <ux-table-column resizable type="checkbox" width="50px" fixed="left" />
        <ux-table-column
          resizable
          title="医保编码"
          field="healthCode"
          align="center"
        />
        <ux-table-column
          resizable
          title="拆单数量"
          field="divideNum"
          align="center"
          edit-render
        >
        <template v-slot:edit="scope">
          <span @click.stop>
            <el-input-number
              :disabled="!ids.length"
              :min="1"
              :max="Number(scope.row.qty)"
              :size="size"
              v-model="scope.row.divideNum"
            />
            </span>
          </template>
        </ux-table-column>
        <ux-table-column
          resizable
          title="物料编码"
          field="itemCode"
          align="center"
        />
        <ux-table-column
          resizable
          title="物料名称"
          field="itemName"
          align="center"
        />
        <ux-table-column
          resizable
          title="规格型号"
          field="itemSpec"
          align="center"
        />
        <ux-table-column
          resizable
          title="厂家"
          field="manufactor"
          align="center"
        />
        <ux-table-column
          resizable
          title="单位"
          field="itemUom"
          align="center"
        />
        <ux-table-column
          resizable
          title="是否带量"
          field="isWhether"
          align="center"
          :formatter="hangStatus"
        />
        <ux-table-column
          resizable
          title="服务费率(%)"
          field="ratio"
          align="center"
          edit-render
        >
          <template v-slot:edit="scope">
            <el-input-number
              clearable
              :disabled="sonDisable"
              :min="0"
              :size="size"
              v-model="scope.row.ratio"
              @input="changeFei(scope.rowIndex, scope.row)"
            />
          </template>
        </ux-table-column>
        <ux-table-column resizable title="数量" field="qty" align="center" />
        <ux-table-column
          resizable
          title="单价"
          field="price"
          align="center"
          edit-render
        >
          <template v-slot:edit="scope">
            <el-input-number
              clearable
              :disabled="sonDisable"
              :min="1"
              :size="size"
              v-model="scope.row.price"
              @input="changeFei(scope.rowIndex, scope.row)"
            />
          </template>
        </ux-table-column>
        <ux-table-column resizable title="小计" field="amount" align="center" />
        <ux-table-column
          resizable
          title="备注"
          field="detailRemark"
          align="center"
        />
        <ux-table-column
          resizable
          title="服务费"
          field="serviceFee"
          align="center"
        />
      </ux-grid>
    </el-card>
  </div>
</template>

<script>
import {
  Mxdetail,
  editSaveMx,
  toOAs,
  divideDoc,
  cancelDoc,
} from "@/api/expend/expendMx.js";
export default {
  props: ["pageStu", "row", "disable"],
  model: {
    prop: "isList",
    event: "jugislist",
  },
  data() {
    return {
      size: "mini",
      // 不能直接改变props传来的值
      sonPageStu: this.pageStu,
      sonDisable: this.disable,
      basicForm: {
        id: "",
        code: "",
        serviceFee: 0,
        custCode: "",
        custName: "",
        supplierCode: "",
        supplierName: "",
        settleNo: "",
        startDate: "",
        endDate: "",
        totalAmount: "",
        isSum: "",
        sumCode: "",
        isWhether: "",
        remark: "",
        itemList: [],
      },
      options: [
        { value: "0", label: "是" },
        { value: "2", label: "否" },
      ],
      options1: [
        { value: "0", label: "否" },
        { value: "1", label: "是" },
      ],
      basicRules: {},
      ids: [],
      dialogFormVisible: false,
      dialogForm: {
        region: "ratio",
        info: "",
      },
    };
  },
  created() {
    if (this.pageStu == "check") {
      // console.log("数据", this.row);
      this.getDetails(this.row);
    } else if (this.pageStu == "edit") {
      this.getDetails(this.row);
    } else if (this.pageStu == "add") {
    }
  },
  computed: {
    // 一个计算属性的 getter
    publishedBooksMessage: {
      get() {
        this.basicForm.serviceFee = this.basicForm.itemList.reduce(
          (sum, item) => {
            return (Math.round((sum += item.ratio * 0.01 * item.amount) * 10000) / 10000);
          },
          0
        );
        return this.basicForm.serviceFee;
      },
      set() {},
    },
    publishedBooksMessage2: {
      get() {
        this.basicForm.totalAmount = this.basicForm.itemList.reduce(
          (sum, item) => {
            return (Math.round((sum += item.qty * item.price) * 10000) / 10000);
          },
          0
        );
        return this.basicForm.totalAmount;
      },
      set() {},
    },
  },
  methods: {
    getToFixed(prop, val = 2) {
      return Number(prop.toFixed(val));
    },
    getDetails(row) {
      Mxdetail(row.id).then((res) => {
        if (res.code === 200) {
          this.basicForm = res.data;
          this.basicForm.itemList.forEach(item => {
            item.divideNum = Number(item.qty)
          })
        }
      });
    },
    editPage() {
      this.sonPageStu = "edit";
      this.sonDisable = false;
    },
    save() {
      editSaveMx(this.basicForm).then((res) => {
        if (res.code === 200) {
          this.$modal.notifySuccess("编辑保存成功");
          this.sonPageStu = "check";
          this.sonDisable = true;
          this.getDetails(this.row);
          this.ids = [];
        }
      });
    },
    back() {
      this.$emit("jugislist", true);
      this.$emit("refresh");
    },
    handleSelectionChange(selection) {
      // this.ids = selection.map(item =>{
      //   return item.id
      // })
      console.log('selection', selection)
      let lin = selection.map(item => { return item.id })
      console.log('lin',lin)

      this.basicForm.itemList.forEach(item => {
        if(!lin.includes(item.id)) {
          item.divideNum = Number(item.qty)
        }
      })
      // selection.forEach(item => {
      //   item.divideNum = Number(item.qty)
      // })
      this.ids = selection;
    },
    editLine() {
      if (this.ids.length <= 0) {
        this.$modal.notifyWarning("请至少选择一条数据进行操作!");
      } else {
        this.dialogFormVisible = true;
      }
    },
    // 取消拆单
    cancelDisassembly() {
      cancelDoc(this.basicForm.code).then(res => {
        if(res.code === 200) {
          this.$modal.notifySuccess("取消拆单成功");
          this.back()
        }
      })
    },
    // 拆单
    async useDisassembly() {
      try {
        let ids = this.ids.map((item) => item.id);

        let tableLit = _.cloneDeep(this.basicForm.itemList);
        tableLit = tableLit.map((item) => {
          let index = ids.findIndex((i) => i === item.id);

          if (index !== -1) {
            item.isWhether = "1";
          }
          return item;
        });
        let { code, msg } = await divideDoc({
          ...this.basicForm,
          itemList: tableLit,
        });
        if (code === 200) {
          this.$notify.success(msg);
          this.back();
        }
      } catch (error) {}
    },
    confirm() {
      console.log("修改值", this.dialogForm);
      this.ids.forEach((item) => {
        item[this.dialogForm.region] = this.dialogForm.info;
        // 小计 = 数量 * 单价
        item.amount = item.qty * item.price;
        item.serviceFee = (item.ratio * 0.01 * item.amount).toFixed(2);
      });
      this.dialogFormVisible = false;
    },
    clearInfo() {
      this.dialogForm = {
        region: "ratio",
        info: "",
      };
    },
    delLines() {},
    toOA() {
      this.$modal.loading("正在提交，请稍后...");
      toOAs(this.basicForm)
        .then((res) => {
          if (res.code === 200) {
            this.$modal.closeLoading();
            this.$modal.notifySuccess(res.msg);
            this.back();
          }
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },
    changeFei(index, row) {
      row.amount = row.qty * row.price;
      row.serviceFee = (row.ratio * 0.01 * row.amount).toFixed(2);
      // this.basicForm.serviceFee = this.basicForm.itemList.map(item => {
      //   return item.serviceFee += item.serviceFee
      // })
    },
    hangStatus(row) {
      switch (row.row.isWhether) {
        case "0":
          return "否";
        case "":
          return "否";
        case "1":
          return "是";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.btn_group {
  display: flex;
  justify-content: space-between;
  position: absolute;
  top: 10px;
  right: 20px;
}
.btn_grooup {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}
</style>
