<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-input
                placeholder="姓名"
                v-model="queryParam.userName"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <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"
            >
              <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 -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" :disabled="!isAddOk" type="primary" icon="plus">新增</a-button>
    </div>

    <!-- table区域-begin -->
    <div class="table-remake">
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: 800, y: 350 }"
        style="height: 450px;"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <!-- <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> -->

        <template v-for="col in columns.map(item=> item.dataIndex )" :slot="col" slot-scope="text, record, index">
          <div :key="col">
            <a-input
              v-if="record.editable && (col == 'userName' || col == 'contentBody') "
              style="margin: -5px 0;width:100px;"
              :value="text"
              @change="e => handleChange(e.target.value, record.id, col)"
            />
            <template v-if="!record.editable && col != 'relay' ">
              <span style="text-overflow: ellipsis; max-width: 140px; overflow: hidden; display: inline-block;" :title="text">
                {{ text }}
              </span>
            </template>
            <template v-if="record.editable && col == 'createDate' ">
              {{ text }}
            </template>
            <template v-if="!record.editable && col == 'relay' ">
              {{ text==1? '是':'否' }}
            </template>
            <a-select v-if=" record.editable && col == 'roomNo' " v-model="record.livingOrderId" placeholder="请选择房号">
              <a-select-option
                :value="item.livingOrderId"
                v-for="(item, index) in roomsList"
                :key="item.id"
              >
                {{ item.roomName }}/{{ item.customerName }}
              </a-select-option>
            </a-select>

              <!--            <j-date-->
              <!--              v-if=" record.editable && col == 'remindDate' "-->
              <!--              placeholder="自动提醒时间"-->
              <!--              v-model="record.remindDate"-->
              <!--              style="width: 100%"-->
              <!--            />-->
              <a-date-picker
                  v-if=" record.editable && col == 'remindDate' "
                  style="width: 100%;"
                  v-model="record.remindDate"
                  placeholder="自动提醒时间"
                  :show-time="true"
                  format="YYYY-MM-DD HH:mm:ss"
                  :allowClear="false"
              />

            <a-date-picker
                v-if=" record.editable && col == 'validDate' "
                style="width: 100%;"
                v-model="record.validDate"
                placeholder="有效时间"
                :show-time="true"
                format="YYYY-MM-DD HH:mm:ss"
                :allowClear="false"
            />
            <a-select v-if=" record.editable && col == 'relay' " placeholder="请选择" v-model="record.relay">
              <a-select-option :value="1"> 是 </a-select-option>
              <a-select-option :value="2"> 否 </a-select-option>
            </a-select>
          </div>
        </template>

        <template slot="action" slot-scope="text, record, index">
          <!-- <div>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定删除吗?"
              @confirm="() => handleDelete(record.id)"
            >
              <a>删除</a>
            </a-popconfirm>
          </div> -->
          <span v-if="record.editable">
            <a @click="() => save(record.id, record)">保存</a>
            <a-divider :disabled="editingKey !== ''" type="vertical" />
            <!-- <a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.id)"> -->
            <a @click="() => cancel(record.id)">取消</a>
            <!-- </a-popconfirm> -->
          </span>
          <span v-else>
            <!-- <a :disabled="editingKey !== ''" @click="() => edit(record.id)">Edit</a> -->
            <a :disabled="editingKey !== ''" @click="edit(record.id)">编辑</a>
            <a-divider :disabled="editingKey !== ''" type="vertical" />
            <a-popconfirm
              :disabled="editingKey !== ''"
              title="确定删除吗?"
              @confirm="() => handleDelete(record.id)"
            >
              <a :disabled="editingKey !== ''">删除</a>
            </a-popconfirm>
          </span>

        </template>

        <!-- <span slot="action" slot-scope="text, record">

        </span> -->

      </a-table>
    </div>

    <bus-member-message-modal
      ref="modalForm"
      @ok="modalFormOk"
    ></bus-member-message-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import BusMemberMessageModal from './modules/membermessage/BusMemberMessageModal'
import { deleteAction, getAction, downFile, getFileAccessHttpUrl, httpAction } from '@/api/manage'
import moment from 'moment'

// const disabledDate = (current: Dayjs) => {
//   // Can not select days before today and today
//   return current && current < dayjs().endOf('day');
// };

const disabledDateTime = () => {
  return {
    disabledHours: () => range(0, 24).splice(4, 20),
    disabledMinutes: () => range(30, 60),
    disabledSeconds: () => [55, 56],
  };
};

export default {
  name: 'BusMemberMessageList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    BusMemberMessageModal
  },
  props: {
    livingOrderId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      editingKey: '',
      description: 'bus_member_message管理页面',
      // 表头
      columns: [
        {
          title: '房号',
          align: 'center',
          dataIndex: 'roomNo',
          width: 147,
          scopedSlots: { customRender: 'roomNo' }
        },
        {
          title: '留言人',
          align: 'center',
          dataIndex: 'userName',
          width: 147,
          scopedSlots: { customRender: 'userName' }
        },
        {
          title: '是否传达',
          align: 'center',
          dataIndex: 'relay',
          width: 147,
          scopedSlots: { customRender: 'relay' }
          // customRender: function (text) {
          //   return !text ? "否" : "是";
          // },
        },
        {
          title: '自动提醒时间',
          align: 'center',
          dataIndex: 'remindDate',
          // customRender: function (text) {
          //   return !text ? "" : text.length > 10 ? text.substr(0, 10) : text;
          // },
          width: 210,
          scopedSlots: { customRender: 'remindDate' }
        },
        {
          title: '有效时间',
          align: 'center',
          dataIndex: 'validDate',
          width: 210,
          scopedSlots: { customRender: 'validDate' }
          // customRender: function (text) {
          //   return !text ? "" : text.length > 10 ? text.substr(0, 10) : text;
          // },
        },
        {
          title: '留言内容',
          align: 'center',
          scopedSlots: { customRender: 'contentBody' },
          width: 147,
          dataIndex: 'contentBody'
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createDate',
          scopedSlots: { customRender: 'createDate' },
          width: 147
          // customRender: function (text) {
          //   return !text ? "" : text.length > 10 ? text.substr(0, 10) : text;
          // },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list:
          '/business/busMemberMessage/list?livingOrderId=' + this.livingOrderId,
        delete: '/business/busMemberMessage/delete',
        deleteBatch: '/business/busMemberMessage/deleteBatch',
        exportXlsUrl: '/business/busMemberMessage/exportXls',
        importExcelUrl: 'business/busMemberMessage/importExcel'
      },
      dictOptions: {},
      superFieldList: [],
      datetime: [],
      dataSourceCopy: [],
      roomsList: [],
      isAddOk: true
    }
  },
  created() {
    this.getSuperFieldList()
    getAction('/business/busRoomBookingOrders/living-orders?status=-1', {
      current: 1,
      size: 99999
    }).then((res) => {
      if (res.success) {
        this.roomsList = res.result.records
      }
    })
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {

    handleChange(value, key, column) {
      const newData = [...this.dataSource]
      const target = newData.find(item => key === item.id)
      if (target) {
        target[column] = value
        this.dataSource = newData
      }
    },

    edit(key) {
      const newData = [...this.dataSource]
      const target = newData.find(item => key === item.id)
      this.editingKey = key
      if (target) {
        target.editable = true
        this.dataSource = newData
      }
    },
    save(key) {
      console.log(key)
      console.log(this.dataSource)
      const that = this
      const newData = [...this.dataSource]
      const newCacheData = [...this.dataSourceCopy]
      const target = newData.find(item => key === item.id)
      const targetCache = newCacheData.find(item => key === item.id)
      if (target.relay === 1 && !target.remindDate) {
        that.$message.warning('自动提醒时间不能为空')
        return
      }
      if (target.relay === 1 && !target.validDate) {
        that.$message.warning('有效时间不能为空')
        return
      }
      console.log(target.remindDate)
      if (target.remindDate != null) {
        target.remindDate = moment(target.remindDate).format('YYYY-MM-DD HH:mm:ss')
        
      }
      if (target.validDate != null) {
        target.validDate = moment(target.validDate).format('YYYY-MM-DD HH:mm:ss')
      }
      if (target && targetCache) {
        delete target.editable
        this.dataSource = newData
        Object.assign(targetCache, target)
        this.dataSourceCopy = newCacheData
      }
      that.loading = true
      let httpurl = ''
      let method = ''
      if (!target.id || target.id == 9999) {
        httpurl += '/business/busMemberMessage/add'
        method = 'post'
      } else {
        httpurl += '/business/busMemberMessage/edit'
        method = 'put'
      }
      if (target.id == 9999) {
        delete target.id
      }
      httpAction(httpurl, target, method)
      .then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          // that.$emit("ok");
          // 新增/修改 成功时，重载列表
          this.loadData()
          // 清空列表选中
          this.onClearSelected()
        } else {
          that.$message.warning(res.message)
        }
      })
      .finally(() => {
        that.loading = false
        this.isAddOk = true
      })
      console.log('target', target)
      this.editingKey = ''
    },
    cancel(key) {
      const newData = [...this.dataSource]
      const target = newData.find(item => key === item.id)
      this.editingKey = ''
      if (target) {
        Object.assign(target, this.dataSourceCopy.find(item => key === item.id))
        delete target.editable
        this.dataSource = newData
      }
      if (target.id == 9999) {
        this.dataSource.pop()
        this.isAddOk = true
      }
      this.loadData()
    },
    submitForm() {
      this.$emit('ok')
    },
    handleAdd() {
      console.log(this.roomsList)
      // this.$refs.modalForm.add(this.livingOrderId);
      // this.$refs.modalForm.title = "新增";
      // this.$refs.modalForm.disableSubmit = false;
      let find = this.roomsList.find(
        (t) => t.livingOrderId === this.livingOrderId
      )
      let roomId = find.roomId
      this.dataSource.push({
        id: 9999,
        livingOrderId: this.livingOrderId,
        relay: 1,
        editable: true,
        hotelId: JSON.parse(localStorage.getItem('storeInfo')).id,
        roomId: roomId
      })
      this.isAddOk = false
      this.editingKey = 9999
    },
    onChange(e, dateString) {
      this.queryParam.startTime = dateString[0]
      this.queryParam.endTime = 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: 'roomId', text: '房号id' })
      fieldList.push({
        type: 'string',
        value: 'livingOrderId',
        text: '入住订单id'
      })
      fieldList.push({ type: 'string', value: 'userName', text: '留言人' })
      fieldList.push({
        type: 'date',
        value: 'remindDate',
        text: '自动提醒时间'
      })
      fieldList.push({ type: 'date', value: 'validDate', text: '有效时间' })
      fieldList.push({ type: 'int', value: 'relay', text: '是否传达' })
      fieldList.push({
        type: 'string',
        value: 'contentBody',
        text: '留言内容'
      })
      fieldList.push({ type: 'date', value: 'createDate', text: '创建时间' })
      this.superFieldList = fieldList
    },
    loadData(arg) {
      if (this.url.list == 2) {
        return
      }
      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
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result
          this.dataSourceCopy = res.result.records || res.result
          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
      })
    }
  }
}
</script>
<style scoped>
@import "~@assets/less/common.less";
.table-remake /deep/.ant-table-body {
  min-height: 352px !important;
  }
.table-remake /deep/ .ant-empty-normal {
  margin: 140px 0 !important;
}
.table-remake /deep/.ant-table-placeholder{
  margin-top: -320px;
}
</style>
