<template>
  <div>
<!--  <a-calendar>-->
<!--    <ul slot="dateCellRender" slot-scope="value" class="events">-->
<!--      <li v-for="item in getListData(value)" :key="item.content">-->
<!--        <a-badge :status="item.type" :text="item.content" />-->
<!--      </li>-->
<!--    </ul>-->
<!--    <template slot="monthCellRender" slot-scope="value">-->
<!--      <div v-if="getMonthData(value)" class="notes-month">-->
<!--        <section>{{ getMonthData(value) }}</section>-->
<!--        <span>Backlog number</span>-->
<!--      </div>-->
<!--    </template>-->
<!--  </a-calendar>-->
<!--        <ul class="events">-->
          <!--          <li v-for="item in getListData(value)" :key="item.content">-->
          <!--            <a-badge :status="'success'" :text="item.classify_rname +'('+item.num+')'" />-->
          <!--          </li>-->
          <!--        </ul>-->
  <!-- <div>
    <a-calendar style="background: #fff" @select="handleSelecrt" @panelChange="onPanelChange" :header-render="headerRender">
      <div slot="dateFullCellRender" slot-scope="value" class="ant-fullcalendar-date" :class="{'ant-fullcalendar-date-has-content':getListData(value).length>0}">
        <div class="ant-fullcalendar-value">{{getCaledarDate(value)}}</div>
        <div class="ant-fullcalendar-content">
          <div style="padding-top: 5px;" v-for="item in getListData(value)" :key="item.content">
            <a-button type="primary" @click="e=>handleMoney(e,value,item)">
              {{item.content}}
            </a-button>
          </div>
          
        </div>
      </div>
    </a-calendar> -->

    <a-modal v-model="visibleMoney" title="修改房价" @ok="handleOk">
      <a-input-number style="width: 100%;margin: auto" v-model="updateMoney" />
    </a-modal>
  <!-- </div> -->
  <a-table :columns="columns" :alert="true" :data-source="calendarData" :rowKey="(record, index) => index + 1">
    <!-- 111 -->
    <!-- <template slot="layoutName" slot-scope="text, record">
      <a-button type="primary">Primary Button</a-button>
    </template> -->
    <!-- <div slot-scope="text, record" v-for="item in columns"> -->
    <template v-for="item in columns" :slot="item.dataIndex" slot-scope="text, record">
      <!-- {{  }} -->
      <div :class="isWeekend(new Date(item.dataIndex)) ? 'cell_style' : 'cell_stylez'" @click="editPrice(record,item,record[item.dataIndex])">
      <!-- <div class="cell_style"> -->
        {{ record[item.dataIndex] }}
        <!-- <a-button block></a-button>  -->
      </div>
      <!-- <a-button type="primary">Primary Button</a-button> -->
    </template>
    <!-- </div> -->
      <!-- <template slot-scope="text, record">
         -->
          <!-- 111 -->
          <!-- <template :slot="item.dataIndex" slot-scope="text, record">
            111
          </template> -->
          <!-- {{ record[index] }}111 -->
          <!-- {{ record[index] = 1 }} -->
          
        <!-- <template :slot="record[index]" slot-scope="text, record">
          {{ record[index] }}
        </template>
        <template :slot="record[index]" slot-scope="text, record">
          {{ record[index] }}
        </template>
        <template :slot="record[index]" slot-scope="text, record">
          {{ record[index] }}
        </template> -->
      <!-- </div>
      </template> -->
      <!-- <template slot-scope="scopes">
        {{ calendarData }}
        <div v-for="item in scopes">
          
        </div>
      </template> -->
    
      
      <!-- {{ record.dataIndex }} -->
       <!-- <div>
            111
        </div> -->
        <!-- <el-dialog
    title="提示"
    :visible.sync="visibleMoney"
    width="30%"
    :before-close="handleClose">
    <span>这是一段信息</span>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visibleMoney = false">取 消</el-button>
      <el-button type="primary" @click="visibleMoney = false">确 定</el-button>
    </span>
  </el-dialog> -->
  </a-table>
</div>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import moment from 'moment';
  import * as dayjs from "dayjs";
  const hotelInfo = JSON.parse(localStorage.getItem("storeInfo"));

  export default {
    name: 'housePriceSchemeLayoutForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
    },
    data () {
      return {
        columns: [
          {
            title: '房型',
            dataIndex: 'layoutName',
            scopedSlots: { customRender: 'layoutName' }
          }
        ],
        // 表格数据
        calendarData: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        url: {
          add: "/business/busHousePriceSchemeLayout/add",
          edit: "/business/busHousePriceSchemeLayout/edit",
          queryById: "/business/busHousePriceSchemeLayout/queryById",
          queryList: "/business/busSchemeLayoutDailyPrice/queryList",
          editDailyPrice: "/business/busSchemeLayoutDailyPrice/editDailyPrice",
          batchUpdatePrice: "/business/busSchemeLayoutDailyPrice/batchUpdatePrice",
          // list: "/business/busHousePriceSchemeLayout/layoutPricePage",
          queryListByCond: "/business/busSchemeLayoutDailyPrice/queryListByCond",
        },
        curDate :moment(new Date()).format('YYYY-MM-DD'),
        moneyDays:[],
        schemeLayoutId:'',
        visibleMoney:false,
        updateId:'',
        updateSchemeLayoutId:'',
        updateMoney:0,
        updateDate:'',
        selectDate:'',
        // 暂存数据
        oldList: []

      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      this.selectDate = moment(new Date()).format('YYYY-MM-DD 00:00:00')
      console.log(this.dataSource);

      //获取数据
      this.$nextTick(()=>{
        getAction(this.url.queryList, {
          schemeLayoutId: this.schemeLayoutId,
          realDate:this.selectDate
        }).then((res) => {
          if (res.success) {
            this.moneyDays = res.result;
          }
        });


        // var param = {
        //   schemeId:'1644273323440029697',
        //   layoutId:'1632671499640946690',
        //   startDate:'2023-04-10',
        //   endDate:'2023-04-16',
        // }
        // getAction(this.url.queryListByCond, param).then((res) => {
        //   if (res.success) {
        //     console.log(res.result);
        //   }
        // });


        var url = "/rooms/cesHousePriceScheme/listByLayout?hotelId=" + hotelInfo.id+"&layoutId="+'1632671499640946690'
        getAction(url, {}).then((res) => {
          if (res.success) {
            console.log(res.result);
          }
        });
      })
      // this.getDateList()
    },
    methods: {
      // 修改价格
      editPrice(record,item,val) {
        console.log(val);
        console.log(record);
        console.log(item);
        console.log(this.calendarData);
        let tempid = ''
        this.oldList.forEach(index => {
          console.log(index);
          if (record.layoutName == index.layoutName) {
            index.schemeLayoutDailyPriceList.forEach(cust => {
            if (item.dataIndex == cust.date) {
              console.log(111);
              tempid = cust.id
            }
          })
          }
        })
        console.log(tempid);
        var _time = moment(new Date(item.dataIndex)).format('YYYY-MM-DD 00:00:00')
        console.log(_time);
        this.updateDate = _time
        this.updateMoney = val
        this.updateId = tempid
        this.updateSchemeLayoutId = record.schemeLayoutId
        this.visibleMoney = true
      },
      // 获取数据
      async getDateList() {
        console.log(this.dataSource);
        await getAction('/business/busHousePriceSchemeLayout/layoutPricePage', {
          pageNo: 1,
          pageSize: 10,
          schemeId: this.model.schemeId
        }).then(res => {
          console.log(res);
          if (res.success) {
            this.oldList = res.result.records
            let tmeplist = res.result.records
            let tempcol = []
            tmeplist[0].schemeLayoutDailyPriceList.forEach(index => {
              let tempindex = {
                title: index.date,
                // schemeLayoutId: schemeLayoutId,
                dataIndex: index.date,
                align: 'center',
                // key: 'key',
                // customCell: (record) => {
                //   for (let item in record) {
                //     const d1 = new Date(item);
                //     let tempcolor = this.isWeekend(d1)
                //     console.log(tempcolor);
                //     if (tempcolor) {
                //       return {
                //         style:{
                //           color:'red'
                //         }
                //       }
                //     }
                //   }
                // }
                'scopedSlots': { 'customRender': index.date }
                // customRender(text, record) {
                //     // return record.layoutPrice
                //     record.forEach(item => {

                //     })
                // }
                // const d1 = new Date(item);
                  // let tempcolor = this.isWeekend(d1)
              }
              tempcol.push(tempindex)
            });
            // console.log(tempcol);
            this.columns = this.columns.concat(tempcol)
            // console.log(this.columns);
            let temprol = []
            tmeplist.forEach(item => {
              console.log(item);
              // let 
              let tempindex = {}
              item.schemeLayoutDailyPriceList.forEach(index => {
                // var tempdate = index.date
                // tempindex = {
                  tempindex[index.date] = index.money
                  tempindex['schemeLayoutId'] = index.schemeLayoutId
                  tempindex['layoutName'] = item.layoutName
                  tempindex['hotelId'] = item.hotelId
                  tempindex['id'] = item.id
                  // tempdate: index.money,
                  // dataIndex: ,
                  // schemeLayoutId: index.schemeLayoutId
                // }
              })
              temprol.push(tempindex)
            });
            console.log(temprol);
            console.log(this.columns);
            this.calendarData = temprol
            // temprol.forEach(cust => [
              
            // ])
          }
        })
      },
      // 处理周末
      isWeekend(date = new Date()) {
        return date.getDay() === 6 || date.getDay() === 0;
      },
      // // 处理周末
      // exitCustomRow(record, index) {
      //   console.log(record);
      //   for (let item in record) {
      //     console.log(item);
      //     const d1 = new Date(item);
      //     let tempcolor = this.isWeekend(d1)
      //     // console.log(this.isWeekend(d1));
      //     console.log(tempcolor);
      //     if (this.isWeekend(d1)) {
      //       // console.log(123);
      //       return 'table-color-dust'
      //     }
      //     // if (!this.isWeekend(d1)) {
      //     //   // console.log(123);
      //     //   return {
      //     //     style: {
      //     //       background: 'red',
      //     //     },
      //     //   }
      //     // }
      //   }
      //   console.log(index);
      // },
      edit (record) {
        console.log(record);
        this.model = Object.assign({}, record);
        this.visible = true;
        this.schemeLayoutId = record.id
        this.getDateList()
      },
      
      handleMoney(e,value,item){
        var _time = moment(new Date(value)).format('YYYY-MM-DD 00:00:00')
        this.visibleMoney = true
        this.updateMoney = item.content
        this.updateDate = _time
        this.updateId = item.id
        this.updateSchemeLayoutId = item.schemeLayoutId
        e.stopPropagation();//阻止事件冒泡
      },
      handleOk(e){
        //修改每日房价
        var that = this;
        that.confirmLoading = true;
        httpAction(this.url.editDailyPrice,{
          id:this.updateId,
          schemeLayoutId:this.updateSchemeLayoutId,
          hotelId:hotelInfo.id,
          date:this.updateDate,
          money:this.updateMoney,
        },"POST").then((res)=>{
          if(res.success){
            that.$message.success("操作成功");
            // that.$emit('ok');

            getAction(that.url.queryList, {
              schemeLayoutId: that.schemeLayoutId,
              realDate:that.selectDate
            }).then((res) => {
              if (res.success) {
                that.moneyDays = res.result;
                this.getDateList()
              }
            }).finally(()=>{

            });

          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
          that.visibleMoney = false
        })
      },
      getListData(value) {
        let listData = [];
        //获取到所有某个房型的每日房价
        //刚进入页面的时候，只显示今天以后的数据
        var _time = moment(new Date(value)).format('YYYY-MM-DD')
        var _cur = moment(new Date()).format('YYYY-MM-DD')

        if(this.selectDate != ""){
          for(let item of this.moneyDays){
            if (item.date == _time){
              listData = [
                { content: item.money ,id:item.id ,schemeLayoutId:item.schemeLayoutId },
              ];
            }
          }
        }else{
          if (_time >= _cur){
            for(let item of this.moneyDays){
              if (item.date == _time){
                listData = [
                  { content: item.money ,id:item.id ,schemeLayoutId:item.schemeLayoutId},
                ];
              }
            }
          }
        }


        // switch (value.date()) {
        //   case 8:
        //     listData = [
        //       { content: '218' },
        //     ];
        //     break;
        //   case 10:
        //     listData = [
        //       { content: '258' },
        //     ];
        //     break;
        //   default:
        // }
        return listData || [];
      },

      getMonthData(value) {
        if (value.month() === 8) {
          return 1394;
        }
      },

      // 点击某天
      handleSelecrt(value) {
        let selectDate = value.format('YYYY-MM-DD HH:mm:ss') // 当前选中的日历时间
        this.selectDateValue = selectDate
        this.visible = true; // 打开模态框
        this.selectDate = value.format('YYYY-MM-DD 00:00:00')
        var _this = this;
        getAction(this.url.queryList, {
          schemeLayoutId: this.schemeLayoutId,
          realDate:this.selectDate
        }).then((res) => {
          if (res.success) {
            _this.moneyDays = res.result;
          }
        }).finally(()=>{

        });
      },
      // 切换年月
      onPanelChange(val) {
        this.starT = dayjs(val).format('YYYY-MM-01 00:00:00')
        this.endT = dayjs(val).add(1, 'month').format('YYYY-MM-01 00:00:00')
        // this.loadData(this.starT, this.endT)//重新加载数据
      },
      // 获取日历的日期
      getCaledarDate(value){
        let str = value.format('YYYY-MM-DD').substring(5, 10);
        // if(str[0]=='0'){
        //   str = str.substring(1,2)
        // }
        return str
      },
      // 获取日历的日期
      getCaledarRealDate(value) {
        let str = value.format('YYYY-MM-DD');
        // if(str[0]=='0'){
        //   str = str.substring(1,2)
        // }
        return str
      },
      headerRender({ value, type, onChange, onTypeChange }) {
        const start = 0
        const end = 12
        const monthOptions = []

        const current = value.clone()
        const localeData = value.localeData()
        const months = []
        for (let i = 0; i < 12; i++) {
          current.month(i)
          months.push(localeData.monthsShort(current))
        }

        for (let index = start; index < end; index++) {
          monthOptions.push(
          <a-select-option class="month-item" key={`${index}`}>
          {months[index]}
        </a-select-option>
        )
        }
        const month = value.month()

        const year = value.year()
        const options = []
        for (let i = year - 10; i < year + 10; i += 1) {
          options.push(
          <a-select-option key={i} value={i} class="year-item">
                  {i + '年'}
                  </a-select-option>
        )
        }
        // 批量修改价格
        var batchStartDate = '';
        var batchEndDate = '';
        const batchUpdateMoney = () =>{
          var _money = document.getElementById("batchMoney").value;
          if(_money == '' || _money < 0){
            this.$message.warning("请输入正确房价！");
            return;
          }
          if (batchStartDate == '' || batchEndDate == ''){
            this.$message.warning("请选择正确时间！");
            return;
          }
          var param = {
            schemeLayoutId:this.schemeLayoutId,
            hotelId:hotelInfo.id,
            startDate:batchStartDate,
            endDate:batchEndDate,
            money:_money,
          }
          console.log(param)
          var that = this;
          that.confirmLoading = true;
          httpAction(this.url.batchUpdatePrice,param,"POST").then((res)=>{
            if(res.success){
              that.$message.success("操作成功");
              // that.$emit('ok');

              getAction(that.url.queryList, {
                schemeLayoutId: that.schemeLayoutId,
                realDate:that.selectDate
              }).then((res) => {
                if (res.success) {
                  that.moneyDays = res.result;
                }
              }).finally(()=>{

              });

            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
            that.visibleMoney = false
          })

        }
        const onBatchChange = (e, dateString) =>{
          // console.log("Selected Time: ", e);
          console.log("Formatted Selected Time: ", dateString);
          batchStartDate = dateString[0]
          batchEndDate = dateString[1]
        }
        /* 上个月 */
        const prevMonth = () => {
          let newMonth = moment(value).subtract(1, 'months');
          onChange(newMonth);
        };
        /* 下个月 */
        const nextMonth = () => {
          let newMonth = moment(value).add(1, 'months');
          onChange(newMonth);
        };
        // 返回今天
        const showTotay = () => {
          const today = moment(new Date())
          onChange(today)
        }
        return (
                <div style={{ padding: ' 15px 15px 40px 15px', textAlign: 'center', position: 'relative'}}>
      <div style={{display: 'inline-block', textAlign: 'center'}}>
      <a-select
        dropdownMatchSelectWidth={false}
      class="header-select"
        onChange={newYear => {
          const now = value.clone().year(newYear)
          onChange(now)
        }}
        value={Number(year)}
                >
                {options}
                </a-select>
                <a-select
        dropdownMatchSelectWidth={false}
      class="header-select"
        value={String(month)}
        onChange={selectedMonth => {
          const newValue = value.clone()
          newValue.month(parseInt(selectedMonth, 10))
          onChange(newValue)
        }}
      >
        {monthOptions}
      </a-select>
                </div>
                <div style={{position: 'absolute',right: '15px',top: '15px'}}>
      <a-button-group>
        <a-button type="primary" onClick={() => prevMonth()}><a-icon type="left" />上一月</a-button>
                <a-button type="primary" onClick={() => showTotay()}>返回今日</a-button>
        <a-button type="primary" onClick={() => nextMonth()}>下一月<a-icon type="right" /></a-button>
                </a-button-group>
                </div>
                <div class="header-title">
                <div class="header-title-content">
                  <a-range-picker class="margin-left-10" id="batchDate" onChange={(e,date)=>onBatchChange(e,date)} />
                  <a-input-number style={{width:'100px'}} class="margin-left-10" id="batchMoney" placeholder="请输入房价" min="0" precision='2'/>
                  <a-button class="margin-left-10" type="primary" onClick={() => batchUpdateMoney()}>
                    确定
                  </a-button>
                </div>
        </div>
                </div>
      )
      },
    }
  }
</script>
<style>
  /*日历头部*/
  .header-select{
    margin-right: 10px;
  }
  /deep/ .header-select .ant-select-selection-selected-value {
    color: #222;
    font-weight: bold;
    font-size: 16px;
  }
  .header-title{
    font-weight: bold;
    font-size: 17px;
    color: #222;
    padding-top: 10px;
  }
  .header-title-content{
    text-align: right;
  }
  .margin-left-10{
    margin-left: 10px;
  }
  /*日历单元格，存在内容时，背景为灰色*/
  /deep/ .ant-fullcalendar-date-has-content {
    background-color: #f3f3f3;
  }
  /*日历单元格-今天 背景*/
  /deep/ .ant-fullcalendar-fullscreen .ant-fullcalendar-today .ant-fullcalendar-date::after {
    content: '今天';
    font-size: 30px;
    position: absolute;
    width: 100%;
    text-align: right;
    right: 6px;
    bottom: 0;
    color: rgba(145, 211, 255, 0.65);
    letter-spacing: 5px;
    font-weight: bold;
  }
  .table-color-dust {
    background-color: #F5222D;
  }
  .cell_style {
    color: red !important;
    /* color: #f6de90; */
  }
  .cell_stylez {
    color: #000 !important;
  }

</style>
