<template>
  <div>
    <div style="display: flex; gap: 15px">
      <div style="width: 40%">
        <div style="display: flex; justify-content: space-between">
          <h4
            style="
              color: rgba(255, 141, 26, 1);
              font-weight: 600;
              margin-top: 15px;
            "
          >
            入住信息
          </h4>
          <div style="display: flex">
            <div style="display: flex; flex-direction: column">
              <a-icon
                type="clock-circle"
                style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /><a-button type="link"> 叫醒服务 </a-button>
            </div>
            <div style="display: flex; flex-direction: column">
              <a-icon
                type="compass"
                style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /><a-button
                type="link"
                :disabled="selectRoomId == '1'"
                @click="splitLiving"
              >
                拆分房间
              </a-button>
            </div>
          </div>
        </div>
        <a-divider />
        <a-tabs @change="tabChange" v-model="tabSelectRoomId">
          <a-tab-pane
            :key="item.roomId"
            v-for="(item, livingIndex) in model.livingRoomIds"
          >
            <span slot="tab">
              {{ item.roomName }}
              <a-badge
                dot
                :number-style="{ backgroundColor: '#52c41a' }"
                v-if="item.livingOrder && item.livingOrder.settleType == 1"
              >
                <span style="font-size: 12px">已结退房</span>
              </a-badge>
              <a-badge
                dot
                :number-style="{ backgroundColor: '#52c41a' }"
                v-if="item.livingOrder && item.livingOrder.settleType == 2"
              >
                <span style="font-size: 12px">未结退房</span>
              </a-badge>
            </span>
            <a-descriptions :column="2">
              <a-descriptions-item label="主客姓名">
                {{
                  item.livingCustomers && item.livingCustomers[0]
                    ? item.livingCustomers[0].customerName
                    : "--"
                }}
                <a-icon
                  v-if="livingIndex > 0"
                  @click="editCustomer(item)"
                  type="edit"
                  style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /></a-descriptions-item>
              <a-descriptions-item label="性别">
                {{
                  item.livingCustomers && item.livingCustomers[0]
                    ? item.livingCustomers[0].gender === 1
                      ? "男"
                      : "女"
                    : "--"
                }}</a-descriptions-item
              >
              <a-descriptions-item label="房间数量">
                {{ livingIndex == 0 ? model.livingRoomIds.length - 1 : 1 }}间
              </a-descriptions-item>
              <a-descriptions-item label="手机号">
                {{
                  item.livingCustomers && item.livingCustomers[0]
                    ? item.livingCustomers[0].phone
                    : "--"
                }}
                <a-icon
                  v-if="livingIndex > 0"
                  @click="editCustomer(item)"
                  type="edit"
                  style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /></a-descriptions-item>

              <a-descriptions-item label="宾客类型">
                {{ customerTypeName(item.livingOrder.customerType) }}
                <a-icon
                  v-if="livingIndex > 0"
                  @click="editCustomerType(item)"
                  type="edit"
                  style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /></a-descriptions-item>
              <a-descriptions-item label="入住时间">
                {{ item.livingOrder.arrivalTime }}
              </a-descriptions-item>
              <a-descriptions-item label="房价方案"> -- </a-descriptions-item>
              <a-descriptions-item label="预离时间">
                {{ item.livingOrder.dueOutTime }}
              </a-descriptions-item>
              <a-descriptions-item label="订单来源">
                {{ customerSourceName(item.livingOrder.customerSource) }}
                <a-icon
                  v-if="livingIndex > 0"
                  @click="editCustomerSource(item)"
                  type="edit"
                  style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /></a-descriptions-item>
              <a-descriptions-item label="入住类型">
                {{  getlivingTypeText(item.livingOrder.livingType) }}
                <a-icon
                  v-if="livingIndex > 0"
                  @click="editBookingType(item)"
                  type="edit"
                  style="color: rgba(255, 141, 26, 1); font-size: 18px"
                />
              </a-descriptions-item>
              <a-descriptions-item label="入住天数">
                {{ item.livingOrder.dayCount }}
              </a-descriptions-item>
              <a-descriptions-item label="早餐券">
                {{ item.livingOrder.breakfastNum }}
                <a-icon
                  v-if="livingIndex > 0"
                  @click="editBreakfastNum(item)"
                  type="edit"
                  style="color: rgba(255, 141, 26, 1); font-size: 18px"
                />
              </a-descriptions-item>
              <a-descriptions-item label="外部单号">
                {{ model.orderInfo.outerOrdersNo }}
              </a-descriptions-item>
              <a-descriptions-item label="销售员工">
                {{ warranterName(item.livingOrder.warranter) }}
                <a-icon
                  v-if="livingIndex > 0"
                  @click="editWarranter(item)"
                  type="edit"
                  style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /></a-descriptions-item>
              <a-descriptions-item label="订单备注" :span="2">
                {{ item.livingOrder.remark
                }}<a-icon
                  v-if="livingIndex > 0"
                  @click="editRemark(item)"
                  type="edit"
                  style="color: rgba(255, 141, 26, 1); font-size: 18px"
                />
              </a-descriptions-item>
              <template
                v-if="
                  wakeList.filter((item) => {
                    return tabSelectRoomId == 1
                      ? item
                      : tabSelectRoomId == item.roomId;
                  }).length == 0
                "
              >
                <a-descriptions-item label="叫醒服务" :span="2">
                  <a-icon
                    type="plus-circle"
                    class="dynamic-delete-button"
                    @click="puls()"
                  />
                </a-descriptions-item>
              </template>
              <template v-else>
                <a-descriptions-item
                  label="叫醒服务"
                  :span="2"
                  v-for="(item, index) in wakeList.filter((item) => {
                    return tabSelectRoomId == 1
                      ? item
                      : tabSelectRoomId == item.roomId;
                  })"
                  :key="index"
                >
                  {{ item.roomName }}
                  {{ item.jxDate ? item.jxDate + " /" : "" }} {{ item.jxTime }}
                  <a-icon
                    v-if="
                      wakeList.filter((item) => {
                        return tabSelectRoomId == 1
                          ? item
                          : tabSelectRoomId == item.roomId;
                      }).length -
                        1 ==
                      index
                    "
                    type="plus-circle"
                    class="dynamic-delete-button"
                    @click="puls()"
                  />
                  <a-icon
                    type="minus-circle"
                    style="color: #f56c6c"
                    class="dynamic-delete-button"
                    @click="removeWakeService(item.id)"
                  />
                </a-descriptions-item>
              </template>
            </a-descriptions>
            <div style="display: flex; justify-content: space-between">
              <h4
                style="
                  color: rgba(255, 141, 26, 1);
                  font-weight: 600;
                  margin-top: 15px;
                "
              >
                同住人
              </h4>
              <div style="display: flex">
                <div style="display: flex; flex-direction: column">
                  <a-icon
                    type="user-add"
                    style="color: rgba(255, 141, 26, 1); font-size: 18px"
                  /><a-button
                    type="link"
                    @click="addlivingCustomer(item.livingOrder.id, item.roomId)"
                  >
                    添加
                  </a-button>
                </div>
              </div>
            </div>
            <div id="livingCustomers-grid">
              <a-row
                v-for="(customer, index) in item.livingCustomers"
                :key="customer.id"
              >
                <template v-if="index > 0">
                  <a-col :span="6">
                    ({{ getRoomName(customer.roomId) }}){{
                      customer.customerName
                    }}
                  </a-col>
                  <a-col :span="2"
                    >{{ customer.gender == 1 ? "男" : "女" }}
                  </a-col>
                  <a-col :span="8"> {{ customer.certNo || "--" }}</a-col>
                  <a-col :span="6"> {{ customer.phone }}</a-col>
                  <a-col :span="2">
                    <a-icon
                      type="minus-circle"
                      style="color: #f56c6c"
                      class="dynamic-delete-button"
                      @click="() => removeLivingCustomer(customer.id)"
                  /></a-col>
                </template>
              </a-row>
            </div>
          </a-tab-pane>
        </a-tabs>
        <template v-if="vipCustomer && vipCustomer.id">
          <h4
            style="
              color: rgba(255, 141, 26, 1);
              font-weight: 600;
              margin-top: 50px;
            "
          >
            会员信息
          </h4>
          <a-divider />
          <a-descriptions :column="2">
            <a-descriptions-item label="姓名">
              {{ vipCustomer.name }}
            </a-descriptions-item>
            <a-descriptions-item label="证件号"
              >{{ vipCustomer.certificateNo }}
            </a-descriptions-item>
            <a-descriptions-item label="卡号">
              {{ vipCustomer.cardNo }}
            </a-descriptions-item>
            <a-descriptions-item label="手机号">
              {{ vipCustomer.mobile }}
            </a-descriptions-item>
            <a-descriptions-item label="会员级别">
              {{ vipCustomer.gradeName }}
            </a-descriptions-item>
            <a-descriptions-item label="余额"
              >{{ vipCustomer.balance.toFixed(2) }} 元
            </a-descriptions-item>
            <a-descriptions-item label="积分">
              {{ vipCustomer.integral }} 分
            </a-descriptions-item>
          </a-descriptions></template
        >
      </div>
      <div style="width: 40%">
        <div style="display: flex; justify-content: space-between">
          <h4
            style="
              color: rgba(255, 141, 26, 1);
              font-weight: 600;
              margin-top: 15px;
            "
          >
            消费详情
          </h4>
          <div style="display: flex">
            <div style="display: flex; flex-direction: column">
              <a-icon
                type="tool"
                style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /><a-button
                type="link"
                :disabled="selectRoomId == '1'"
                @click="addProjectFee"
              >
                增加消费
              </a-button>
            </div>
            <div style="display: flex; flex-direction: column">
              <a-icon
                type="import"
                style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /><a-button
                type="link"
                :disabled="selectedRowKeys1.length == 0 || selectRoomId == '1'"
                @click="tuidan"
              >
                退单
              </a-button>
            </div>
            <div style="display: flex; flex-direction: column">
              <a-icon
                type="property-safety"
                style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /><a-button
                type="link"
                :disabled="selectedRowKeys1.length == 0 || selectRoomId == '1'"
                @click="partialSettle"
              >
                部分结账
              </a-button>
            </div>
          </div>
        </div>
        <a-divider />
        <a-table
          :columns="columns"
          :data-source="feesList"
          :pagination="false"
          :scroll="{ y: 160 }"
          rowKey="id"
          :row-selection="rowSelection"
        >
          <template slot="subjectType" slot-scope="text, record, index">
            {{ getSubjectTypeText(text) }}
          </template>
          <template slot="roomId" slot-scope="text, record, index">
            {{ getRoomName(text) }}
          </template>
        </a-table>
        <div
          style="
            color: rgba(255, 87, 51, 1);
            font-weight: 600;
            text-align: right;
          "
        >
          合计消费：{{ feesAmount.toFixed(2) }}
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            margin-top: 30px;
          "
        >
          <h4
            style="
              color: rgba(255, 141, 26, 1);
              font-weight: 600;
              margin-top: 15px;
            "
          >
            收款详情
          </h4>
          <div style="display: flex">
            <div style="display: flex; flex-direction: column">
              <a-icon
                type="transaction"
                style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /><a-button type="link"> 收款 </a-button>
            </div>
            <div style="display: flex; flex-direction: column">
              <a-icon
                type="trademark"
                style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /><a-button type="link"> 退款 </a-button>
            </div>
            <div style="display: flex; flex-direction: column">
              <a-icon
                type="pound"
                style="color: rgba(255, 141, 26, 1); font-size: 18px"
              /><a-button type="link"> 冲账 </a-button>
            </div>
          </div>
        </div>
        <a-divider />
        <a-table
          :columns="columns2"
          :data-source="paymentList"
          :pagination="false"
          :scroll="{ y: 160 }"
          rowKey="id"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
        >
          <template slot="payType" slot-scope="text, record, index">
            {{ getPayTypeText(text) }}
          </template>
          <template slot="subjectType" slot-scope="text, record, index">
            {{ getSubjectTypeText(record.subjectType) }}
          </template>
        </a-table>
        <div
          style="
            color: rgba(255, 87, 51, 1);
            font-weight: 600;
            text-align: right;
          "
        >
          合计收款：{{ paymentAmount.toFixed(2) }}
        </div>
      </div>
      <div style="width: 20%">
        <h4 style="color: rgba(255, 141, 26, 1); font-weight: 600">财务汇总</h4>
        <a-divider />
        <a-descriptions :column="1">
          <a-descriptions-item label="合计收款">
            + {{ paymentAmount.toFixed(2) }}
          </a-descriptions-item>
          <a-descriptions-item label="合计消费"
            >-{{ feesAmount.toFixed(2) }}
          </a-descriptions-item>
          <a-descriptions-item
            label="结账应退"
            v-if="paymentAmount - feesAmount > 0"
          >
            {{ (paymentAmount - feesAmount).toFixed(2) }}
          </a-descriptions-item>
          <a-descriptions-item label="结账应收" v-else>
            {{ (paymentAmount - feesAmount).toFixed(2) }}
          </a-descriptions-item>
        </a-descriptions>

        <a-button
          v-if="paymentAmount - feesAmount > 0"
          @click="handleAdd"
          type="danger"
          style="margin-left: 100px"
          :disabled="btnSisabled"
          >结账退款</a-button
        >
        <a-button
          v-else
          @click="handleAdd"
          type="danger"
          style="margin-left: 100px"
          :disabled="btnSisabled"
          >结账收款</a-button
        >
      </div>
    </div>
    <customer-modal ref="modalCustomerForm" @ok="modalFormOk"></customer-modal>
    <refund-modal ref="modalRefundForm" @ok="modalFormOk"></refund-modal>
    <payment-modal ref="modalPaymentForm" @ok="modalFormOk"></payment-modal>
    <fee-modal ref="modalFeeForm" @ok="modalFormOk"></fee-modal>
    <member-message-modal ref="modalMemberMessage"></member-message-modal>
    <lease-goods-modal ref="modalLeaseGoods"></lease-goods-modal>
    <select-check-in-room-order-modal
      ref="modalSelectCheckInRoomOrder"
      @ok="modalFormOk"
    ></select-check-in-room-order-modal>
    <edit-customer-modal
      ref="modalEditCustomer"
      @ok="modalFormOk"
    ></edit-customer-modal>
    <edit-customer-type-modal
      ref="modalEditCustomerType"
      @ok="modalFormOk"
    ></edit-customer-type-modal>
    <edit-customer-source-modal
      ref="modalEditCustomerSource"
      @ok="modalFormOk"
    ></edit-customer-source-modal>
    <edit-warranter-modal
      ref="modalEditWarranter"
      @ok="modalFormOk"
    ></edit-warranter-modal>
    <edit-remark-modal
      ref="modalEditRemarkModal"
      @ok="modalFormOk"
    ></edit-remark-modal>
    <edit-breakfast-num-modal
      ref="modalEditBreakfastNumModal"
      @ok="modalFormOk"
    ></edit-breakfast-num-modal>
    <edit-booking-type-modal
      ref="modalEditBookingTypeModal"
      @ok="modalFormOk"
    ></edit-booking-type-modal>

    <!-- 叫醒服务弹窗 -->
    <a-modal
      :title="'叫醒服务'"
      :visible="wakeService"
      @cancel="wakeService = false"
      @ok="wakeServiceOk"
      destroyOnClose
    >
      <a-select
        style="width: 100px"
        placeholder="房间号"
        @change="onChange"
        v-model="wakeTime.id"
      >
        <a-select-option
          :value="item.livingOrder.id"
          v-for="(item, index) in (model.livingRoomIds || []).filter(
            (item) => item.roomName != '全部'
          )"
          :key="index"
        >
          {{ item.roomName }}
        </a-select-option>
        <!-- <a-select-option value="lucy"> 1002 </a-select-option> -->
      </a-select>
      <a-date-picker
        style="width: 120px; margin-left: 2px"
        placeholder="日期"
        @change="onChangeWakeService"
      />
      <a-time-picker
        style="width: 100px; margin-left: 2px"
        format="HH:mm"
        @change="onChangeWakeServiceTime"
      />
    </a-modal>
  </div>
</template>

<script>
import { httpAction, getAction, deleteAction, postAction } from "@/api/manage";
import { validateDuplicateValue } from "@/utils/util";
import moment from "moment";
import CustomerModal from "./CustomerModal.vue";
import RefundModal from "./RefundModal.vue";
import PaymentModal from "./PaymentModal.vue";
import FeeModal from "./FeeModal";
import MemberMessageModal from "@/views/room/modules/membergoodsmanage/membermessageModal";
import LeaseGoodsModal from "@/views/room/modules/leasegoods/leasegoodsModal";
import SelectCheckInRoomOrderModal from "./SelectCheckInRoomOrderModal.vue";
import EditCustomerModal from "./EditCustomerModal.vue";
import EditCustomerTypeModal from "./EditCustomerTypeModal.vue";
import EditCustomerSourceModal from "./EditCustomerSourceModal.vue";
import EditWarranterModal from "./EditWarranterModal.vue";
import EditRemarkModal from "./EditRemarkModal.vue";
import EditBreakfastNumModal from "./EditBreakfastNumModal.vue";
import EditBookingTypeModal from "./EditBookingTypeModal.vue";
import { match } from "assert";
const columns = [
  // {
  //     title: "",
  //     dataIndex: "key",
  //     width: 20,
  //   },
  {
    title: "房间号",
    dataIndex: "roomId",
    width: 70,
    scopedSlots: { customRender: "roomId" },
  },
  {
    title: "费项",
    dataIndex: "subjectType",
    width: 60,
    scopedSlots: { customRender: "subjectType" },
  },
  {
    title: "入账日期",
    dataIndex: "dayTime",
    width: 110,
  },
  {
    title: "单价",
    dataIndex: "id",
    // width: 60,
    customRender: function (text, record) {
      return record.money;
    },
  },
  {
    title: "优惠价",
    dataIndex: "money",
    // width: 80,
  },
  {
    title: "数量",
    dataIndex: "feeType",
    // width: 60,
    customRender: function (text) {
      return 1;
    },
  },
  {
    title: "小计",
    dataIndex: "livingOrderId",
    // width: 60,
    customRender: function (text, record) {
      return record.money;
    },
  },
];
const columns2 = [
  {
    title: "入账时间",
    dataIndex: "createTime",
    // width: 110,
  },
  {
    title: "支付方式",
    dataIndex: "payType",
    // width: 100,
    scopedSlots: { customRender: "payType" },
  },
  {
    title: "备注",
    dataIndex: "remark",
    // width: 120,
    scopedSlots: { customRender: "subjectType" },
  },
  {
    title: "金额",
    dataIndex: "money",
    // width: 60,
  },
];
const data = [];
for (let i = 0; i < 100; i++) {
  data.push({
    key: i,
    name: `100${i}`,
    age: "房费",
    address: 280,
  });
}
const data2 = [];
for (let i = 0; i < 8; i++) {
  data2.push({
    key: i,
    name: `2023-02-0${i} 10:52`,
    age: "支付宝",
    remark: "押金",
    amount: 888,
  });
}
const date = new Date();
const endDate = new Date(date.setDate(date.getDate() + 1));
export default {
  name: "BusMeetingRoomForm",
  components: {
    CustomerModal,
    RefundModal,
    PaymentModal,
    FeeModal,
    MemberMessageModal,
    LeaseGoodsModal,
    SelectCheckInRoomOrderModal,
    EditCustomerModal,
    EditCustomerTypeModal,
    EditCustomerSourceModal,
    EditWarranterModal,
    EditRemarkModal,
    EditBreakfastNumModal,
    EditBookingTypeModal,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      wakeService: false,
      wakeTime: {
        id: "",
        date: "",
        time: "",
      },
      selectedRowKeys: [],
      data,
      columns,
      data2,
      columns2,
      wakeList: [{}],
      model: {
        // data: data,
        orderInfo: {},
        roomIds: [],
        layoutDayPrices: [],
        livingRoomIds: [],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        dateRange: [{ required: true, message: "请选择维修时间!" }],
        remark: [{ required: true, message: "请输入维修原因!" }],
      },
      url: {
        add: "/business/busMeetingRoom/add",
        edit: "/business/busMeetingRoom/edit",
        queryById: "/business/busMeetingRoom/queryById",
        getBookingOrderInfo:
          "/business/busRoomBookingOrders/getBookingOrderInfo",
      },
      id: "",
      roomId: "",
      tabSelectRoomId: "",
      customerSourceList: [],
      warranterList: [],
      key: 0,
      feesList: [],
      oldfeesList: [],
      paymentList: [],
      oldpaymentList: [],
      payTypeList: [],
      vipCustomer: {},
      selectRoomId: "1",
      selectedRowKeys1: [],
    };
  },
  computed: {
    formDisabled() {
      return this.disabled;
    },
    feesAmount() {
      return this.feesList.reduce(function (total, item) {
        return total + item.money;
      }, 0);
    },
    paymentAmount() {
      // var list = this.paymentList.filter((t) => t.subjectType !== 5);
      // var amount = list.reduce(function (total, item) {
      //   return total + item.money;
      // }, 0);

      // var list2 = this.paymentList.filter((t) => t.subjectType == 5);
      // var amount2 = list2.reduce(function (total, item) {
      //   return total + item.money;
      // }, 0);
      var amount = this.paymentList.reduce(function (total, item) {
        return total + item.money;
      }, 0);
      return amount;
    },
    btnSisabled() {
      var index = this.model.livingRoomIds.findLastIndex(
        (t) => t.roomId == this.selectRoomId
      );
      var find = this.model.livingRoomIds[index];
      if (find) {
        return find.livingOrder.settleType == 1;
      }
      return false;
    },
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          // console.log(
          //   `selectedRowKeys: ${selectedRowKeys}`,
          //   "selectedRows: ",
          //   selectedRows
          // );
          this.selectedRowKeys1 = selectedRowKeys;
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.preferentialStatus === 2,
            id: record.id,
          },
        }),
      };
    },
  },
  created() {
    var _info = JSON.parse(localStorage.getItem("storeInfo"));
    if (_info) {
      this.model.hotelId = _info.id;
    }
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    getAction("/business/busDictItem/list", {
      hotelId: _info.id,
      dictId: "1639538915239743490",
    }).then((res) => {
      if (res.success) {
        this.customerSourceList = res.result.records;
      }
    });
    getAction("/business/busSalesPerson/list", {
      hotelId: _info.id,
      pageNo: 1,
      pageSize: 100,
    }).then((res) => {
      if (res.success) {
        this.warranterList = res.result.records;
      }
    });
  },
  methods: {
    // 叫醒服务
    wakeServiceOk() {
      console.log(this.wakeTime);
      if (!this.wakeTime.id) {
        this.$message.warning("请选择房间号");
        return;
      }
      if (!this.wakeTime.date) {
        this.$message.warning("请选择日期");
        return;
      }
      if (!this.wakeTime.time) {
        this.$message.warning("请选择时间");
        return;
      }
      let obj = {
        livingOrderId: this.wakeTime.id,
        jxDate: this.wakeTime.date,
        jxTime: this.wakeTime.time,
      };
      postAction("/fw/fwLivingJx/add", obj).then((res) => {
        if (res.success) {
          this.$message.success("添加成功");
          this.wakeTime = {};
          this.getWakeServiceData();
          this.wakeService = false;
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    //获取叫醒服务数据
    getWakeServiceData() {
      let ids = [];
      this.model.livingRoomIds.forEach((item) => {
        if (item.roomName != "全部") {
          ids.push(item.livingOrder.id);
        }
      });
      getAction("/fw/fwLivingJx/list?livingOrderId=" + ids.toString()).then(
        (res) => {
          if (res.success) {
            this.wakeList = res.result.records;
          }
        }
      );
    },
    //删除叫醒服务
    removeWakeService(id) {
      deleteAction("/fw/fwLivingJx/delete?id=" + id).then((res) => {
        if (res.success) {
          this.$message.success("删除成功");
          this.getWakeServiceData();
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    onChangeWakeService(e, e1) {
      console.log(e, e1);
      this.wakeTime.date = e1;
    },
    onChangeWakeServiceTime(e, e1) {
      console.log(e, e1);
      this.wakeTime.time = e1;
    },
    editBookingType(item) {
      var obj = {
        orderId: item.livingOrder.id,
        liveType: item.livingOrder.livingType,
        fangAnId: item.livingOrder.hourRoomId,
        livingDayPrices: item.livingDayPrices,
        roomId: item.roomId,
      };
      this.$refs.modalEditBookingTypeModal.edit(obj);
      this.$refs.modalEditBookingTypeModal.title = "修改";
      this.$refs.modalEditBookingTypeModal.disableSubmit = false;
    },
    editBreakfastNum(item) {
      var obj = {
        orderId: item.livingOrder.id,
        brkfstNum: item.livingOrder.breakfastNum,
      };
      this.$refs.modalEditBreakfastNumModal.edit(obj);
      this.$refs.modalEditBreakfastNumModal.title = "修改";
      this.$refs.modalEditBreakfastNumModal.disableSubmit = false;
    },
    editRemark(item) {
      var obj = {
        orderId: item.livingOrder.id,
        remark: item.livingOrder.remark,
      };
      this.$refs.modalEditRemarkModal.edit(obj);
      this.$refs.modalEditRemarkModal.title = "修改";
      this.$refs.modalEditRemarkModal.disableSubmit = false;
    },
    editWarranter(item) {
      var obj = {
        orderId: item.livingOrder.id,
        warranter: item.livingOrder.warranter,
      };
      this.$refs.modalEditWarranter.edit(obj);
      this.$refs.modalEditWarranter.title = "修改";
      this.$refs.modalEditWarranter.disableSubmit = false;
    },
    getlivingTypeText(livingType) {
      var text = "";
      if (livingType === 1) {
        text = "全天";
      } else if (livingType === 2) {
        text = "钟点";
      } else if (livingType === 3) {
        text = "自用";
      } else if (livingType === 4) {
        text = "免费";
      } else if (livingType === 4) {
        text = "长租";
      }
      return text;
    },
    editCustomerSource(item) {
      var obj = {
        orderId: item.livingOrder.id,
        customerSource: item.livingOrder.customerSource,
      };
      this.$refs.modalEditCustomerSource.edit(obj);
      this.$refs.modalEditCustomerSource.title = "修改";
      this.$refs.modalEditCustomerSource.disableSubmit = false;
    },
    editCustomerType(item) {
      var obj = {
        orderId: item.livingOrder.id,
        customerType: item.livingOrder.customerType,
        vipCustomerId: item.livingOrder.vipCustomerId,
        contractTeamId: item.livingOrder.contractTeamId,
        contractTeamProtocolId: item.livingOrder.contractTeamProtocolId,
      };
      this.$refs.modalEditCustomerType.edit(obj);
      this.$refs.modalEditCustomerType.title = "修改";
      this.$refs.modalEditCustomerType.disableSubmit = false;
    },
    editCustomer(item) {
      var customer = item.livingCustomers[0] || {};
      var obj = {
        orderId: item.livingOrder.id,
        cusName: customer.customerName,
        cusPhone: customer.phone,
        cusId: customer.id,
      };
      this.$refs.modalEditCustomer.edit(obj);
      this.$refs.modalEditCustomer.title = "修改";
      this.$refs.modalEditCustomer.disableSubmit = false;
    },
    splitLiving() {
      var that = this;
      this.$confirm({
        title: "提示",
        content: "确认要拆分房间?",
        onOk: function () {
          var index = that.model.livingRoomIds.findLastIndex(
            (t) => t.roomId == that.selectRoomId
          );
          var livingRoom = that.model.livingRoomIds[index];
          httpAction(
            "business/busRoomBookingOrders/split-living?livingOrderId=" +
              livingRoom.livingOrder.id,
            {},
            "post"
          )
            .then((res) => {
              if (res.success) {
                that.$message.success("拆分成功");
                that.getBookingOrderInfo();
                that.$emit("ok");
              } else {
                that.$message.warning(res.message);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
            });
        },
      });
    },
    addUnion() {
      if (this.selectRoomId === "1") {
        this.$message.warning("请先选择房间");
        return;
      }
      var index = this.model.livingRoomIds.findLastIndex(
        (t) => t.roomId == this.selectRoomId
      );
      console.log(this.model.livingRoomIds);
      var find = this.model.livingRoomIds[index];
      let arr = [];
      this.model.livingRoomIds.forEach((ele) => {
        if (ele.roomName != "全部") {
          arr.push(ele.livingOrder.id);
        }
      });
      this.$refs.modalSelectCheckInRoomOrder.add();
      this.$refs.modalSelectCheckInRoomOrder.title = "请选择需要关联的订单";
      this.$refs.modalSelectCheckInRoomOrder.disableSubmit = false;
      this.$refs.modalSelectCheckInRoomOrder.livingOrderId =
        find.livingOrder.id;
      this.$refs.modalSelectCheckInRoomOrder.filterIds = arr;
      this.$refs.modalSelectCheckInRoomOrder.livingRoomId = find.roomId;
    },
    addLeaseGoods() {
      // if (this.selectRoomId === "1") {
      //   this.$message.warning("请先选择房间");
      //   return;
      // }
      var index = this.model.livingRoomIds.findLastIndex(
        (t) => t.roomId == this.selectRoomId
      );
      var find = this.model.livingRoomIds[index];
      var livingOrderId = "";
      if (find.roomId != "1") {
        livingOrderId = find.livingOrder.id;
      } else {
        this.model.livingRoomIds
          .filter((t) => t.roomId != "1")
          .forEach((t) => {
            livingOrderId += t.livingOrder.id + ",";
          });
      }
      this.$refs.modalLeaseGoods.add();
      this.$refs.modalLeaseGoods.title = "客人留言";
      this.$refs.modalLeaseGoods.disableSubmit = false;
      this.$refs.modalLeaseGoods.livingOrderId = livingOrderId; //find.livingOrder.id;
    },
    addMessage() {
      if (this.selectRoomId === "1") {
        this.$message.warning("请先选择房间");
        return;
      }
      var index = this.model.livingRoomIds.findLastIndex(
        (t) => t.roomId == this.selectRoomId
      );
      var find = this.model.livingRoomIds[index];
      this.$refs.modalMemberMessage.add();
      this.$refs.modalMemberMessage.title = "客人留言";
      this.$refs.modalMemberMessage.disableSubmit = false;
      this.$refs.modalMemberMessage.livingOrderId = find.livingOrder.id;
    },
    addProjectFee() {
      var index = this.model.livingRoomIds.findLastIndex(
        (t) => t.roomId == this.selectRoomId
      );
      var livingRoom = this.model.livingRoomIds[index];
      this.$refs.modalFeeForm.add();
      this.$refs.modalFeeForm.livingOrderId = livingRoom.livingOrder.id;
      this.$refs.modalFeeForm.title = "增加消费项目";
      this.$refs.modalFeeForm.disableSubmit = false;
    },
    tuidan() {
      postAction(
        "/business/busRoomBookingOrders/退你麻痹单狗东西",
        this.selectedRowKeys1
      ).then((res) => {
        if (res.success) {
          this.$message.success("退单成功");
          this.getBookingOrderInfo();
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    partialSettle() {
      var list2 = this.feesList.filter((t) =>
        this.selectedRowKeys1.includes(t.id)
      );
      console.log(list2);
      var amount = list2.reduce(function (total, item) {
        return total + item.money;
      }, 0);
      var index = this.model.livingRoomIds.findLastIndex(
        (t) => t.roomId == this.selectRoomId
      );
      var livingRoom = this.model.livingRoomIds[index];
      this.$refs.modalPaymentForm.edit({
        billAmount: parseFloat(amount.toFixed(2)),
        deposit: 0,
        roomFee: parseFloat(amount.toFixed(2)),
        subjectType: 5,
        feeType: 2,
        bookingOrderId: this.model.orderInfo.id,
        livingOrderId:
          livingRoom.roomId != "1" ? livingRoom.livingOrder.id : "",
        preferentialType: 1,
        couponFirstAmount: 0,
        discount: 9,
        vipCustomerId: this.model.orderInfo.vipCustomerId,
        selectedFeeIds: this.selectedRowKeys1,
      });
      this.$refs.modalPaymentForm.title = "部分结账收款";
      this.$refs.modalPaymentForm.disableSubmit = false;
      this.$refs.modalPaymentForm.showYinshou = false;
    },
    tabChange(e) {
      console.log(e);
      this.selectRoomId = e;
      if (e == "1") {
        this.feesList = this.oldfeesList;
        this.paymentList = this.oldpaymentList;
      } else {
        this.feesList = this.oldfeesList.filter((t) => t.roomId == e);
        this.paymentList = this.oldpaymentList.filter((t) => t.roomId == e);
      }
    },
    getPayTypeText(text) {
      var find = this.payTypeList.find((t) => t.id == text);
      return find ? find.name : "";
    },
    getRoomName(id) {
      var index = this.model.livingRoomIds.findLastIndex((t) => t.roomId == id);
      var find = this.model.livingRoomIds[index];
      return find ? find.roomName : "";
    },
    getSubjectTypeText(text) {
      var msg = "";
      if (text == 1) {
        msg = "押金";
      } else if (text == 2) {
        msg = "预收房费";
      } else if (text == 3) {
        msg = "每日房费";
      } else if (text == 4) {
        msg = "优惠金额";
      } else if (text == 5) {
        msg = "结账收款";
      } else if (text == 6) {
        msg = "商品";
      } else if (text == 7) {
        msg = "点餐";
      } else if (text == 8) {
        msg = "夜审房费";
      } else if (text == 9) {
        msg = "会议室";
      } else if (text == 10) {
        msg = "手工房费";
      } else if (text == 11) {
        msg = "水电煤抄表";
      } else if (text == 12) {
        msg = "赔偿费";
      } else if (text == 13) {
        msg = "退单结账";
      }
      return msg;
    },
    async getbusRoomPayType() {
      await getAction("/business/busRoomPayType/list", {
        pageSize: 99999,
        pageNo: 1,
      }).then((res) => {
        if (res.success) {
          this.payTypeList = res.result.records;
        }
      });
    },
    removeLivingCustomer(id) {
      deleteAction("/business/busLivingCustomer/delete", { id: id }).then(
        (res) => {
          if (res.success) {
            this.getBookingOrderInfo();
          }
        }
      );
    },
    addlivingCustomer(id, roomId) {
      console.log(id, roomId);
      this.$refs.modalCustomerForm.add(id, roomId);
      this.$refs.modalCustomerForm.title = "添加同住人";
      this.$refs.modalCustomerForm.disableSubmit = false;
    },
    modalFormOk(e) {
      this.getBookingOrderInfo();
      this.$emit("ok");
    },
    customerTypeName(customerType) {
      switch (customerType) {
        case 1:
          return "散客";
        case 2:
          return "会员";
        case 3:
          return "协议单位";
        case 4:
          return "中介";
        default:
          return "散客";
      }
    },
    warranterName(warranter) {
      var find = this.warranterList.find((t) => t.id == warranter);
      return find ? find.name : "--";
    },
    customerSourceName(customerSource) {
      var find = this.customerSourceList.find((t) => t.id == customerSource);
      return find ? find.itemText : "--";
    },
    getMemberCard() {
      getAction("/business/busMemberCard/list", {
        id: this.model.orderInfo.vipCustomerId,
      }).then((res) => {
        if (res.success) {
          if (res.result.records && res.result.records.length > 0) {
            this.vipCustomer = res.result.records[0];
          }
        }
      });
    },
    async getBookingOrderInfo() {
      if (this.payTypeList == 0) {
        await this.getbusRoomPayType();
      }
      var obj = {
        bookingNo: this.id,
      };
      if (this.key && this.key == 1) {
        obj = {
          bookingOrderId: this.id,
        };
      }
      getAction(this.url.getBookingOrderInfo, obj).then((res) => {
        if (res.success) {
          var livingRoomId = JSON.parse(
            JSON.stringify(res.result.livingRoomIds[0])
          );
          livingRoomId.roomId = "1";
          livingRoomId.roomName = "全部";
          var list = [];
          res.result.livingRoomIds.forEach((t) => {
            if (t.livingCustomers) {
              list = [...list, ...t.livingCustomers];
            }
          });
          livingRoomId.livingCustomers = list;
          res.result.livingRoomIds.unshift(livingRoomId);
          this.tabSelectRoomId = this.roomId
            ? this.roomId
            : res.result.livingRoomIds[1].roomId;
          this.selectRoomId = this.tabSelectRoomId;
          this.model = res.result;
          this.getWakeServiceData();
          getAction("/business/busRoomBookingOrders/living-fees", {
            bookingOrderId: this.model.orderInfo.id,
          }).then((res) => {
            if (res.success) {
              if (res.result && res.result.length > 0) {
                this.feesList = res.result.filter((t) => t.feeType === 1);
                this.oldfeesList = JSON.parse(JSON.stringify(this.feesList));
                this.paymentList = res.result.filter((t) => t.feeType === 2);
                this.oldpaymentList = JSON.parse(
                  JSON.stringify(this.paymentList)
                );
              }
            }
          });
          if (this.model.orderInfo.vipCustomerId) {
            this.getMemberCard();
          }
        }
      });
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    async handleAdd() {
      var that = this;
      var index = this.model.livingRoomIds.findLastIndex(
        (t) => t.roomId == this.selectRoomId
      );
      var livingRoom = this.model.livingRoomIds[index];
      var livingOrderId = "";
      if (livingRoom.roomId != "1") {
        livingOrderId = livingRoom.livingOrder.id;
      } else {
        this.model.livingRoomIds
          .filter((t) => t.roomId != "1")
          .forEach((t) => {
            livingOrderId += t.livingOrder.id + ",";
          });
      }
      /*判断是否有租借物品未归还*/
      var count = 0;
      await getAction("/order/cesOrderLeaseGoods/checkReturnGoods", {
        livingOrderId: livingOrderId,
      }).then((res) => {
        if (res.success) {
          if (res.result && res.result > 0) {
            count = res.result;
            that.$confirm({
              title: "提示",
              content: "您还有" + count + "件物品未归还，是否跳转物品租借页面?",
              onOk: function () {
                that.addLeaseGoods();
              },
              onCancel() {},
            });
          }
        }
      });
      if (count == 0) {
        var list = this.paymentList.filter((t) => t.subjectType === 1);
        var deposit = list.reduce(function (total, item) {
          return total + item.money;
        }, 0);

        var list2 = this.paymentList.filter((t) => t.subjectType === 2);
        var sum = list2.reduce(function (total, item) {
          return total + item.money;
        }, 0);

        var list3 = this.feesList.filter((t) => t.subjectType === 3);
        var sum2 = list3.reduce(function (total, item) {
          return total + item.money;
        }, 0);
        if (this.paymentAmount - this.feesAmount > 0) {
          this.$refs.modalRefundForm.edit({
            billRefund: this.paymentAmount - this.feesAmount,
            deposit: deposit - (sum - sum2),
            roomFee: sum - sum2,
            money: this.paymentAmount - this.feesAmount,
            subjectType: 5,
            feeType: 2,
            bookingOrderId: this.model.orderInfo.id,
            livingOrderId:
              livingRoom.roomId != "1" ? livingRoom.livingOrder.id : "",
            vipCustomerId: livingRoom.livingOrder.vipCustomerId,
            contractTeamId: livingRoom.livingOrder.contractTeamId,
            contractTeamProtocolId:
              livingRoom.livingOrder.contractTeamProtocolId,
          });
          this.$refs.modalRefundForm.title = "结账退款";
          this.$refs.modalRefundForm.disableSubmit = false;
        } else {
          this.$refs.modalPaymentForm.edit({
            billAmount: parseFloat(
              Math.abs(this.paymentAmount - this.feesAmount).toFixed(2)
            ),
            deposit: deposit - (sum - sum2),
            roomFee: parseFloat(
              Math.abs(this.paymentAmount - this.feesAmount).toFixed(2)
            ),
            subjectType: 5,
            feeType: 2,
            bookingOrderId: this.model.orderInfo.id,
            livingOrderId:
              livingRoom.roomId != "1" ? livingRoom.livingOrder.id : "",
            preferentialType: 1,
            couponFirstAmount: 0,
            discount: 9,
            vipCustomerId: livingRoom.livingOrder.vipCustomerId,
            contractTeamId: livingRoom.livingOrder.contractTeamId,
            contractTeamProtocolId:
              livingRoom.livingOrder.contractTeamProtocolId,
          });
          this.$refs.modalPaymentForm.title = "结账收款";
          this.$refs.modalPaymentForm.disableSubmit = false;
        }
      }
    },
    puls() {
      this.wakeService = true;
      // this.wakeList.push({});
    },
    remove(index) {
      this.wakeList.splice(index, 1);
    },
    moment,
    onChange(e) {
      console.log(e);
    },
    add(id, key, roomId) {
      this.key = key;
      this.id = id;
      this.roomId = roomId;
      this.edit(this.modelDefault);
      this.getBookingOrderInfo();
    },
    edit(record) {
      this.model = Object.assign({}, record);
      this.visible = true;
    },
    handleLeaveNotSettle() {
      if (this.selectRoomId === "1") {
        this.$message.warning("请先选择房间");
        return;
      }
      var index = this.model.livingRoomIds.findLastIndex(
        (t) => t.roomId == this.selectRoomId
      );
      var find = this.model.livingRoomIds[index];
      httpAction(
        "/business/busRoomBookingOrders/leave-not-settle?bookingOrderId=" +
          find.bookingOrdersId +
          "&livingOrderId=" +
          find.livingOrder.id,
        {},
        "post"
      ).then((res) => {
        if (res.success) {
          this.$message.success(res.message);
          this.getBookingOrderInfo();
          this.$emit("ok");
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    submitForm() {
      const that = this;
      that.$message.warning("未实现");
      return;
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = "";
          let method = "";
          if (!this.model.id) {
            httpurl += this.url.add;
            method = "post";
          } else {
            httpurl += this.url.edit;
            method = "put";
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit("ok");
              } else {
                that.$message.warning(res.message);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
            });
        }
      });
    },
  },
};
</script>
<style scoped>
/deep/ .ant-btn-link {
  flex: 1;
  color: rgba(255, 141, 26, 1) !important;
}
.menu {
  display: flex;
  flex-direction: column;
  flex: 1;
  color: #fff;
  margin-top: 12px;
}
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  /* top: 4px; */
  margin-left: 5px;
  font-size: 18px;
  color: #1890ff;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
/deep/.ant-table-thead > tr > th {
  background: rgba(42, 130, 228, 1);
  color: #ffffff;
}
/deep/.ant-divider-horizontal {
  margin: 12px 0 !important;
}
/deep/ .ant-table-tbody .ant-table-row td {
  padding-top: 5px;
  padding-bottom: 5px;
}
/deep/.ant-table-thead > tr > th,
.ant-table-tbody > tr > td {
  padding: 5px 5px !important;
  overflow-wrap: break-word;
}

#livingCustomers-grid [class~="ant-col"] {
  border: #ccc 1px solid;
}
#livingCustomers-grid [class~="ant-col"]:last-child {
  border: 0;
}
</style>