<template>
<!--  <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>-->
  <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>
          <!--        <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>
      </div>
    </a-calendar>

    <a-modal v-model="visibleMoney" title="修改房价" @ok="handleOk" :width="300">
      <a-input-number style="width: 100%;margin: auto" v-model="updateMoney" :min="0" :precision="2" />
    </a-modal>
  </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 {
        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",

          queryListByCond: "/business/busSchemeLayoutDailyPrice/queryListByCond",
        },
        curDate :moment(new Date()).format('YYYY-MM-DD'),
        moneyDays:[],
        schemeLayoutId:'',
        visibleMoney:false,
        updateId:'',
        updateSchemeLayoutId:'',
        updateMoney:0,
        updateDate:'',
        selectDate:'',
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      this.selectDate = moment(new Date()).format('YYYY-MM-DD 00:00:00')
      //获取数据
      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);
          }
        });
      })

    },
    methods: {
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
        this.schemeLayoutId = record.id
      },
      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;
              }
            }).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;
  }
</style>
