<template>
  <div class="home_box">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" >
          <a-row type="flex" align="middle">
            <a-col :span="16">
              <span class="home_title">表单</span>
            </a-col>
            <a-col :span="8">
              <div class="ele-text-right">
                <a-button type="primary" @click="openAdd">创建表单</a-button>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <s-table
          ref="table"
          :pagination="false"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="false"
          :rowKey="record => record.key"
          :rowSelection="null"
        >
          <!--筛选输入框 start-->
          <div
            slot="filterDropdown"
            slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
            style="padding: 8px"
          >
            <a-input
              v-ant-ref="c => (searchInput = c)"
              placeholder="输入您想要搜索的内容"
              :value="selectedKeys[0]"
              style="width: 188px; margin-bottom: 8px; display: block;"
              @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
              @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
              type="primary"
              icon="search"
              size="small"
              style="width: 90px; margin-right: 8px"
              @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              Search
            </a-button>
            <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
              Reset
            </a-button>
          </div>
          <a-icon
            slot="filterIcon"
            slot-scope="filtered"
            type="search"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
          <template slot="customRender" slot-scope="text, record, index, column">
            <span v-if="searchText && searchedColumn === column.dataIndex">
              <template
                v-for="(fragment, i) in text.toString().split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
              >
                <mark v-if="fragment.toLowerCase() === searchText.toLowerCase()" :key="i" class="highlight">{{
                  fragment
                }}</mark>
                <template v-else>{{ fragment }}</template>
              </template>
            </span>
            <template v-else>
              {{ text }}
            </template>
          </template>
          <!--筛选输入框 end-->

          <!--操作选项 start-->
          <span slot="action" slot-scope="text, record">
            <span slot="action">
              <a-dropdown-button :trigger="['click']" @click="handleButtonClick(record)">
                编辑
                <a-menu slot="overlay">
                  <a-menu-item key="0" @click="shareForm(record)"> <a-icon type="share-alt" />分享表单 </a-menu-item>
                  <a-menu-item key="1" @click="toDetailPage(record)"> <a-icon type="user" />数据分析 </a-menu-item>
                  <a-menu-item key="2" @click="copyForm(record)"> <a-icon type="copy" />复制 </a-menu-item>
                  <a-menu-item key="3">
                    <a-popconfirm
                      placement="topRight"
                      title="确认删除？"
                      @confirm="
                        () => {
                          removeData(record)
                        }
                      "
                    >
                      <a-icon type="delete" />删除
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
                <a-icon slot="icon" type="down" />
              </a-dropdown-button>
            </span>
          </span>
          <!--操作选项 end-->
        </s-table>
      </a-card>
    </div>
    <!-- 新建弹窗 -->
    <PageAdd :addVisible="showAdd" @closeAddModal="closeAddModal" />
    <!-- 分享弹窗 -->
    <ShareModal ref="shareModal" :pid="pid" />
  </div>
</template>

<script>
import PageAdd from './pageAdd'
import { STable } from '@/components'
import ShareModal from '../../components/k-form-design/packages/KFormDesign/module/shareModal.vue'
import { getFormDetailPageList, deleteFormDetailPage, createFormDetailPage } from '@/api/common.js'

import dayjs from 'dayjs'

export default {
  name: 'FormList',
  components: {
    STable,
    PageAdd,
    ShareModal
  },
  data() {
    return {
      // 表格数据接口
      url: '/teDetailPage/page',
      // 表格列配置
      columns: [
        {
          title: '名称',
          width: 200,
          key: 'title',
          dataIndex: 'title',
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          }
        },
        {
          title: '外部名称',
          width: 200,
          key: 'sub_title',
          dataIndex: 'sub_title',
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          }
        },
        {
          title: '提交次数',
          width: 120,
          key: 'submit_num',
          dataIndex: 'submit_num'
        },

        {
          title: '开始时间',
          dataIndex: 'begin_time',
          width: 120,
          key: 'begin_time',
          customRender: function(text) {
            if (!text) return '--'
            return dayjs(text).format('YYYY-MM-DD HH:mm')
          },
          sorter: true
        },
        {
          title: '到期时间',
          dataIndex: 'end_time',
          width: 120,
          key: 'end_time',
          customRender: function(text) {
            if (!text) return '--'
            return dayjs(text).format('YYYY-MM-DD HH:mm')
          },
          sorter: true
        },
        {
          title: '创建时间',
          width: 120,
          dataIndex: 'create_time',
          key: 'create_time',
          customRender: function(text) {
            if (!text) return '--'
            return dayjs(text).format('YYYY-MM-DD HH:mm')
          },
          sorter: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          fixed: 'right',
          width: 280,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      loadData: parameter => {
        const filterArr = []
        let needFilter = false
        if (parameter.filters) {
          for (const key in parameter.filters) {
            if (parameter.filters[key].length) {
              needFilter = true
              filterArr.push({
                [key]: {
                  _contains: parameter.filters[key][0]
                }
              })
            }
          }
        }
        return getFormDetailPageList(
          Object.assign(
            {
              limit: parameter.pageSize,
              offset: parameter.pageNo * parameter.pageSize - parameter.pageSize,
              'sort[]': parameter.sortOrder
                ? parameter.sortOrder === 'descend'
                  ? `-${parameter.sortField}`
                  : parameter.sortField
                : '-create_time'
            },
            this.queryParam,

            {
              filter: needFilter
                ? {
                    _and: filterArr
                  }
                : {}
            }
          )
        ).then(res => {
          return res
        })
      },
      // 表格搜索条件
      queryParam: { fields: '*', meta: '*' },
      // 是否显示新建弹窗
      showAdd: false,
      // 是否显示其他配置弹窗 （时间，链接等配置）
      showShareModal: false,
      // 详情下拉框选项
      detailTypeOptions: [],
      pid: '',
      searchText: '',
      searchInput: null,
      searchedColumn: ''
    }
  },
  created() {},
  methods: {
    handleButtonClick(record) {
      this.$router.push(`/formDesign/${record.pid}`)
    },
    toDetailPage(record) {
      this.$router.push(`/formDetailList/${record.pid}`)
    },

    async removeData(record) {
      try {
        const res = await deleteFormDetailPage({}, record.pid)
        this.$message.success('删除成功！')
        this.reload()
      } catch (error) {}
    },

    shareForm(record) {
      this.pid = record.pid
      this.$refs.shareModal.visible = true
    },
    async copyForm(record) {
      const result = await createFormDetailPage({
        title: `${record.title}_copy`,
        sub_title: record.sub_title,
        end_time: record.end_time,
        begin_time: record.begin_time,
        conf_content: record.conf_content
      })
      this.$message.success('复制成功！')
      this.reload()
    },

    closeAddModal() {
      this.showAdd = false
    },

    reload() {
      this.$nextTick(() => {
        this.$refs.table.refresh()
      })
    },

    openAdd() {
      this.showAdd = true
    },

    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },

    handleReset(clearFilters) {
      clearFilters()
      this.searchText = ''
    }
  }
}
</script>
<style scoped lang="less">
.home_box {
  padding: 70px 30px 2px;
}
.home_title {
  display: inline-block;
  font-size: 34px;
  font-weight: 600;
  color: @primary-color;
  line-height: 42px;
  height: 42px;
  max-width: 440px;
}
.ele-text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
