<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="">
              <a-range-picker
                format="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']"
                @change="onChange"
                v-model="datetime"
                :allowClear="false"
              />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <span
              style="float: left; overflow: hidden"
              class="table-page-search-submitButtons"
            >
              <span style="margin-right:10px;">
                包含当日预离房<a-switch v-model="queryParam.isContainLeave" />
              </span>
              <a-button type="primary" @click="searchQuery" icon="search"
                >查询</a-button
              >
              <!-- <a-button
                type="primary"
                @click="searchReset"
                icon="reload"
                style="margin-left: 8px"
                >重置</a-button
              > -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- table区域-begin -->
    <div>
      <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div> -->

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <!-- <template
          :slot="item.dataIndex"
          slot-scope="text, record, index"
          v-for="item in columns"
        >
          0/0/{{ text }}
        </template> -->

        <template :slot="'long'" slot-scope="text, record">
          <!-- {{text.leaveCount}}/{{text.livingCount}} -->
          <a @click="leaveCountOpen(text)">{{text.leaveCount}}</a> / <a @click="openModal(text)">{{text.livingCount}}</a> / <span>{{record.count*1 - text.livingCount*1}}</span>
        </template>

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text, record">
          <span v-if="!text" style="font-size: 12px; font-style: italic"
            >无图片</span
          >
          <img
            v-else
            :src="getImgView(text)"
            :preview="record.id"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic"
            >无文件</span
          >
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)"
          >
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm
                  title="确定删除吗?"
                  @confirm="() => handleDelete(record.id)"
                >
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>



        <!-- <template slot="footer" slot-scope="currentPageData" v-if="dataList.length>0">
          <a-table size="middle" :scroll="{ x: true }" bordered rowKey="id" :showHeader="false" :pagination="false" :columns="columns" :dataSource="dataList">
              <template slot="action" slot-scope="text, record">
                  {{record}}
              </template>
          </a-table>
        </template> -->
      </a-table>
    </div>

    <!-- <bus-member-balance-log-modal
      ref="modalForm"
      @ok="modalFormOk"
    ></bus-member-balance-log-modal> -->
    <ForWardFangTaiModal ref="forWardModal" />
  </a-card>
</template>

<script>
import "@/assets/less/TableExpand.less";
import { mixinDevice } from "@/utils/mixin";
import { JeecgListMixin } from "@/mixins/JeecgListMixin2";
import { formatDate } from "@/utils/util";
import EditableCell from "@views/room/modules/checkIn/EditableCell.vue";
import { httpAction, postAction,getAction } from "@/api/manage";
import ForWardFangTaiModal from './forWardFangTaiModal.vue';

const hotelInfo = JSON.parse(localStorage.getItem("storeInfo"));
import moment from "moment";
const date = new Date();
const endDate = new Date(date.setDate(date.getDate() + 7));
export default {
  name: "BusMemberBalanceLogList",
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    EditableCell,
    ForWardFangTaiModal
  },
  data() {
    return {
      description: "远期房态",
      queryParam: {
        gradeId: "全天房",
        start: moment(new Date()).format("YYYY-MM-DD"),
        end: moment(endDate).format("YYYY-MM-DD"),
        isContainLeave: true
      },
      modalVisible:false,
      modalTitle: "占用房间",
      datetime: [
        moment(new Date(), "YYYY-MM-DD"),
        moment(endDate, "YYYY-MM-DD"),
      ],
      setColumns: true,
      // 表头
      columns: [
        {
          title: "房型",
          align: "center",
          dataIndex: "layout_name",
        },
      ],
      url: {
        list:"/business/busRoomBookingOrders/forward-fangtai",
        delete: "/business/busMemberBalanceLog/delete",
        deleteBatch: "/business/busMemberBalanceLog/deleteBatch",
        exportXlsUrl: "/business/busMemberBalanceLog/exportXls",
        importExcelUrl: "business/busMemberBalanceLog/importExcel",
      },
      dictOptions: {},
      superFieldList: [],
      hotelList: [],
    };
  },
  created() {
    // this.getSuperFieldList();
    getAction(
      "/business/busHotel/list",
      { pageNo: 1, pageSize: 100 }
    ).then((res) => {
      if (res.success) {
        this.hotelList = res.result.records;
      }
    });
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG["domianURL"]}/${this.url.importExcelUrl}`;
    },
    dataList() {
            if (this.dataSource.length == 0) {
                return []
            }
            let arr = Object.keys(this.dataSource[0])
            let brr = [] 
            arr = arr.filter(item => item != 'layout_name' && item != 'flag' && item != 'data' && item!='count')
            let sum = 0
            console.log(arr);
            arr.forEach(item => {
                sum += this.dataSource[this.dataSource.length - 1][item]
            })
            arr.forEach(item => {
                console.log(item);
                let a = {}
                a[item] = `${this.dataSource.reduce((a, b) => a + b[item].leaveCount, 0)} ` + '/' + ` ${this.dataSource.reduce((a, b) => a + b[item].livingCount, 0)}` + ' / ' + (this.dataSource.reduce((a, b) => a + b.count*1, 0) - this.dataSource.reduce((a, b) => a + b[item].livingCount, 0))
                brr.push(a)
            })
            let obj1 = {}
            obj1=Object.assign({}, ...brr, {layout_name: '合计'},{flag:true}, {count: this.dataSource.reduce((a, b) => a + b.count*1, 0)});
            console.log(obj1);
            return [obj1]
        }
  },
  methods: {
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource];
      const target = dataSource[dataIndex];
      if (target) {
        target[key] = value;
        this.dataSourcea = dataSource;
      }
      console.log("this.dataSource", this.dataSource);

      postAction("/rooms/cesRoomLayoutPriceDate/editPrice", {
        roomLayoutPriceId: target.price_id,
        date: key,
        price: value,
      })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {});
    },
    moment,
    searchQuery() {
      if (this.queryParam.hotelIds && this.queryParam.hotelIds.length > 0) {
        this.url.list = "/rooms/cesRoomLayoutPriceDate/pageList";
      } else {
        this.url.list = "/business/busRoomBookingOrders/forward-fangtai"
          // "/rooms/cesRoomLayoutPriceDate/pageList?hotelIds[]=" + hotelInfo.id;
      }
      this.loadData(1);
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    searchReset() {
      this.datetime = [];
      this.queryParam = {};
      this.loadData(1);
    },
    onChange(e, dateString) {
      // console.log("Selected Time: ", e);
      // console.log("Formatted Selected Time: ", dateString);
      this.queryParam.start = dateString[0];
      this.queryParam.end = dateString[1];
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({ type: "string", value: "tenantId", text: "关联租户" });
      fieldList.push({ type: "string", value: "hotelId", text: "关联酒店" });
      fieldList.push({ type: "string", value: "memberId", text: "会员id" });
      fieldList.push({ type: "int", value: "type", text: "类型" });
      fieldList.push({ type: "number", value: "money", text: "充值金额" });
      fieldList.push({ type: "number", value: "balance", text: "金额余额" });
      fieldList.push({ type: "number", value: "giveMoney", text: "赠送金额" });
      fieldList.push({ type: "string", value: "remarks", text: "备注" });
      fieldList.push({ type: "string", value: "staffId", text: "推荐员工" });
      fieldList.push({
        type: "string",
        value: "paymentMethod",
        text: "支付方式",
      });
      fieldList.push({ type: "number", value: "payMoney", text: "支付金额" });
      fieldList.push({ type: "string", value: "code", text: "流水号" });
      this.superFieldList = fieldList;
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      this.loading = true;
      this.columns = [
        {
          title: "房型",
          align: "center",
          dataIndex: "layout_name",
          width: 300,
        },
        {
          title: "",
          align: "center",
          dataIndex: "count",
          width: 40,
        }
      ],
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result.dateList || res.result;
          if (res.result.layoutRooms.length>0) {
            // this.dataSource = this.dataSource.map((item, index) => ({
            //   layout_name:item
            // }))
            let brr = []
            res.result.layoutRooms.forEach(ele=>{
              // console.log(ele);
              brr.push({
                layout_name:ele.layoutName,
                count:ele.roomCount,
                data:res.result.dateList.filter(item => item.layoutId == ele.layoutId)
              })
              // brr = res.result.dateList.filter(item => item.layoutId == ele.layoutId)
            })
            brr.forEach(ele=>{
              ele.data.forEach(item=>{
                ele[item.date] = item
              })
            })
            let arr = []
            brr[0].data.forEach(ele=>{
              arr.push({
                title: ele.date,
                align: "center",
                dataIndex: ele.date,
                width:'120px',
                scopedSlots: {
                        customRender: 'long'
                    },
              })
            })
            let arrayKeys = Object.keys(brr[0])
            arrayKeys = arrayKeys.filter(item => item != 'layout_name' && item != 'flag' && item != 'data' && item!='count')
            let obj = {}
            arrayKeys.forEach(ele=>{
              obj[ele] = {
                data:ele,
                leaveCount:brr.reduce((pre, cur)=> pre + cur[ele].leaveCount,0 ),
                livingCount:brr.reduce((pre, cur)=> pre + cur[ele].livingCount,0 ),
                leaveOrders:brr.map(item=>item[ele].leaveOrders).flat(),
                livingOrders:brr.map(item=>item[ele].livingOrders).flat()
              }
            })
            obj=Object.assign({}, obj, {layout_name: '合计'}, {count: brr.reduce((a, b) => a + b.count*1, 0)});
            brr.push(obj)
            this.dataSource = brr
            this.columns = this.columns.concat(arr)
          }
          if (res.result.total) {
            this.ipagination.total = res.result.total;
          } else {
            this.ipagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },

    leaveCountOpen(data){
      console.log(data);
      this.$refs.forWardModal.modalVisible = true
      this.$refs.forWardModal.modalTitle = '今日预离'
      this.$refs.forWardModal.tableData = data.leaveOrders
      this.$refs.forWardModal.tableDataCopy = data.leaveOrders
    },
    openModal(data){
      console.log(data);
      this.$refs.forWardModal.modalVisible = true
      this.$refs.forWardModal.modalTitle = '占用房间'
      this.$refs.forWardModal.tableData = data.livingOrders
      this.$refs.forWardModal.tableDataCopy = data.livingOrders
    }
  },
};
</script>
<style lang="less" scoped>
@import "~@assets/less/common.less";
/deep/ .ant-table-content .ant-table-body {
    position: relative;
    z-index: 2;
    background: #FFFFFF;
}

/deep/ .ant-table-footer .ant-table-body {
    // overflow: hidden !important;
    position: relative !important;
    z-index: 1 !important;
}

/deep/ .ant-table-content>.ant-table-footer {
    padding: 0 !important;
    top: 0px;
    position: relative;
    z-index: 0;
}
/deep/.ant-table-footer{
    padding: 0 !important;
    top: 0px;
    position: relative;
    z-index: 2;
}
</style>