<template>
  <div class="formDetailList_box">
    <a-spin :spinning="loading" :delay="100" tip="加载中" size="large">
      <div class="formDetailList_header">
        <a-card :bordered="false">
          <a-row type="flex" align="middle">
            <a-icon style="fontSize:30px;marginTop:5px" type="left" size="large" @click="goBack" />
            <span class="formDetailList_header_title">{{ title }}</span>
          </a-row>
        </a-card>
        <a-card :bordered="false">
          <a-form layout="inline">
            <a-row type="flex" align="middle">
              <a-col :span="16">
                <a-form-item>
                  <KDatePicker
                    :parentDisabled="false"
                    :record="record"
                    :value="range"
                    @change="handleChange"
                    @handleOk="handleOk"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <div class="ele-text-right">
                  <a-button type="primary" @click="changeDownloadModalStatus()">下载报告</a-button>
                </div>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
      </div>

      <!-- 表格 -->

      <a-card :bordered="false">
        <s-table
          ref="table"
          :pagination="false"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="false"
          :rowKey="record => record.id"
          :rowSelection="null"
        >
          <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>
          <span slot="uploadImg" slot-scope="text">
            <span slot="uploadImg">
              <div
                style="height: 100px; display: flex; justify-content: flex-start; align-items: center;cursor:pointer"
                @click="previewImgUrl(text)"
              >
                <span v-for="(val, index) in text" :key="index">
                  <img :width="100" :src="val.url" />
                </span>
              </div>
            </span>
          </span>
        </s-table>
      </a-card>
    </a-spin>

    <!-- 新建弹窗 -->
    <PageDownload :showDownloadModal="showDownloadModal" @changeDownloadModalStatus="changeDownloadModalStatus" />
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <Carousel arrows>
        <div slot="prevArrow" class="custom-slick-arrow" style="left: 10px;zIndex: 1">
          <a-icon type="left-circle" />
        </div>
        <div slot="nextArrow" class="custom-slick-arrow" style="right: 10px">
          <a-icon type="right-circle" />
        </div>
        <img
          alt="example"
          style="width: 100%;background-size:contain"
          v-for="(val, index) in previewImageArr"
          :key="index"
          :src="val.url"
        />
      </Carousel>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import PageDownload from './pageDownload.vue'
import { getFormDataList, getFormDetailPage } from '@/api/common.js'
import KDatePicker from '../../components/k-form-design/packages/KDatePicker'

import dayjs from 'dayjs'
import { merge, map } from 'lodash'
import { Carousel } from 'ant-design-vue'

export default {
  name: 'FormDetailList',
  components: {
    STable,
    KDatePicker,
    PageDownload,
    Carousel
  },
  props: {
    record: {
      type: Object,
      default: () => ({
        type: 'date',
        label: '日期选择框',
        options: {
          width: '100%',
          defaultValue: '',
          range: true,
          showTime: { format: 'HH:mm', defaultValue: [moment('00:00', 'HH:mm'), moment('00:00', 'HH:mm')] },
          disabled: false,
          hidden: false,
          clearable: true,
          placeholder: '选择日期时间',
          format: 'YYYY-MM-DD HH:mm'
        },
        model: 'date_1655275578666',
        key: 'date_1655275578666'
      })
    }
  },
  data() {
    return {
      // 表格数据接口
      url: '/teDetailPage/page',
      // 表格列配置
      columns: [],
      isFormfields: [
        //所有的表单数据字段
        'input',
        'textarea',
        'number',
        'select',
        'checkbox',
        'radio',
        'date',
        'time',
        'rate',
        'slider',
        'uploadFile',
        'uploadImg',
        'cascader',
        'treeSelect',
        'batch',
        'editor',
        'switch',
        'button',
        'distinct',
        'phone'
      ],
      needTransformValues: ['select', 'checkbox', 'radio', 'switch', 'uploadImg', 'distinct'], //需要根据options转换value为label的字段
      needSplitValues: ['distinct'], //value为数组，需要用、分割的字段
      loadData: parameter => {
        const pid = this.$route.params.id
        const filterArr = [] //筛选数组
        let needFilter = false //判断是否有筛选字段
        parameter.filters &&
          Object.values(parameter.filters).forEach(v => {
            if (v.length) {
              needFilter = true
              filterArr.push({
                form_data: {
                  _contains: v[0]
                }
              })
            }
          })
        return getFormDataList(
          merge(
            {
              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: { pid: { _eq: pid } } }, //pid搜索条件
            {
              filter: needFilter //筛选搜索条件
                ? {
                    _and: filterArr
                  }
                : {}
            }
          )
        ).then(res => {
          const filteredArr = res.data.map(v => {
            const form_data = JSON.parse(v.form_data)
            return {
              create_time: v.create_time,
              ...form_data
            }
          })
          return { data: filteredArr, meta: res.meta }
        })
      },
      // 表格搜索条件
      queryParam: {
        fields: '*',
        meta: 'filter_count'
      },
      pid: '',
      loading: true,
      title: '',
      range: [],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      showDownloadModal: false, //显示下载弹窗
      previewVisible: false, //图片预览弹窗
      previewImageArr: [] //预览图片数组
    }
  },
  async created() {
    this.pid = this.$route.params.id
    try {
      this.loading = true
      const result = await getFormDetailPage({}, this.pid)
      if (result.data && result.data.conf_content) {
        //已经编辑过
        const cloneData = JSON.parse(result.data.conf_content)
        const columns = this.handleColumnsData(cloneData.list)
        columns.push({
          title: '提交时间',
          // width: 200,
          type: 'create_time',
          key: 'create_time',
          dataIndex: 'create_time',
          ellipsis: true,
          customRender: function(text) {
            if (!text) return '--'
            return dayjs(text).format('YYYY-MM-DD HH:mm')
          },
          sorter: true
        })
        this.columns = columns
      }
      this.title = result.data.title
      this.loading = false
    } catch (error) {
      this.loading = false
    }
  },
  methods: {
    reload() {
      this.$nextTick(() => {
        this.$refs.table.refresh()
      })
    },

    handleCancel() {
      // 取消操作
      this.previewVisible = false
    },

    previewImgUrl(text) {
      this.previewImageArr = text
      this.previewVisible = true
    },

    //处理table的columns数组
    handleColumnsData(data) {
      let columns = []
      if (data.length) {
        data.forEach(v => {
          if (this.isFormfields.includes(v.type)) {
            //表单字段
            const columnsCols = {
              title: v.label,
              width: 'auto',
              key: v.key,
              type: v.type,
              dataIndex: v.key,
              ellipsis: true
            }
            if (this.needTransformValues.includes(v.type)) {
              //需要对值进行处理的字段
              if (v.type === 'uploadImg') {
                //展示图片
                columnsCols.scopedSlots = { customRender: 'uploadImg' }
              } else if (this.needSplitValues.includes(v.type)) {
                //不需要使用options字段进行转换，但是需要对值进行处理（省市区）
                columnsCols.customRender = function(text) {
                  if (!text && text !== false) return '--'
                  return text.join('\\')
                }
              } else {
                //处理需要转换的字段，使用JSON中的options字段转换
                columnsCols.customRender = function(text) {
                  const optionList = v.options.options
                  if (!text && text !== false) return '--'
                  const labelArr = []
                  optionList
                    .filter(v => {
                      if (Array.isArray(text)) {
                        return text.includes(v.value)
                      } else {
                        return v.value === text
                      }
                    })
                    .forEach(v => {
                      labelArr.push(v.label)
                    })
                  return labelArr.join('、')
                }
              }
            } else {
              //处理普通字段，给普通字段添加筛选
              columnsCols.customRender = function(text) {
                if (!text && text !== false) return '--'
                return text
              }
              columnsCols.scopedSlots = {
                filterDropdown: 'filterDropdown',
                filterIcon: 'filterIcon',
                customRender: 'customRender'
              }
            }
            columns.push(columnsCols)
          } else if (v.columns && v.columns.length) {
            //对布局中的数据进行处理，在columns属性中
            v.columns.forEach(items => {
              const col = this.handleColumnsData(items.list)
              columns = [...columns, ...col]
            })
          }
        })
      }
      return columns
    },

    //处理生成csv数据
    handleCsvData(filteredArr) {
      let titleStr = '' //表头字符串
      let content = '' //内容字符串
      this.columns.forEach((v, i) => {
        titleStr += v.title
        if (i === this.columns.length - 1) {
          titleStr += '\n'
        } else {
          titleStr += ','
        }
      })
      filteredArr.forEach(row => {
        this.columns.forEach(col => {
          if (col.customRender && typeof col.customRender === 'function') {
            //处理需要转换数据的字段
            content += `${col.customRender(row[col['key']]) + '\t'},`
          } else if (col.type === 'uploadImg') {
            //处理图片
            content += `"${map(row[col['key']], 'url').join('\n') + '"' + '\t'},`
          } else {
            content += `${row[col['key']] + '\t'},`
          }
        })
        content += '\n'
      })
      titleStr += content
      return titleStr
    },

    //下载报告
    async downloadReport(arr) {
      const transValue = arr.map(v => {
        return dayjs(v).toISOString()
      })
      const res = await getFormDataList(
        merge(
          this.queryParam,
          { filter: { pid: { _eq: this.pid }, create_time: { _between: transValue } } } //pid搜索条件
        )
      )
      const filteredArr = res.data.map(v => {
        const form_data = JSON.parse(v.form_data)
        return {
          create_time: v.create_time,
          ...form_data
        }
      })
      const csvData = this.handleCsvData(filteredArr)
      // encodeURIComponent解决中文乱码
      const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(csvData)
      // 通过创建a标签实现
      const link = document.createElement('a')
      link.href = uri
      // 对下载的文件命名
      link.download = `${this.title}.csv`
      link.click()
    },

    //点击filter的搜索按钮
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },

    //点击filter的重置按钮
    handleReset(clearFilters) {
      clearFilters()
      this.searchText = ''
    },

    handleChange(value) {
      if (!value) {
        this.handleOk()
      }
      this.range = value
    },

    //按照输入日期筛选
    handleOk(value) {
      if (value) {
        const transValue = value.map(v => {
          return dayjs(v).toISOString()
        })
        this.queryParam = { ...this.queryParam, filter: { create_time: { _between: transValue } } }
      } else {
        this.queryParam = { ...this.queryParam, filter: {} }
      }
      this.reload()
    },
    goBack() {
      this.$router.go(-1)
    },

    changeDownloadModalStatus(arr) {
      this.showDownloadModal = !this.showDownloadModal
      if (arr) {
        this.downloadReport(arr)
      }
    }
  }
}
</script>
<style scoped lang="less">
.formDetailList_box {
  padding: 40px 30px 20px;
}
.formDetailList_header {
  &_title {
    display: inline-block;
    font-size: 34px;
    font-weight: 600;
    color: @primary-color;
    margin-left: 30px;
    line-height: 42px;
    height: 42px;
    max-width: 440px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
}
.ele-text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.ant-carousel .slick-slide {
  text-align: center;
  height: 160px;
  line-height: 160px;
  background: #364d79;
  overflow: hidden;
}

.ant-carousel .custom-slick-arrow {
  width: 25px;
  height: 25px;
  font-size: 25px;
  color: #fff;
  background-color: rgba(31, 45, 61, 0.11);
  opacity: 0.3;
}
.ant-carousel .custom-slick-arrow:before {
  display: none;
}
.ant-carousel .custom-slick-arrow:hover {
  opacity: 0.5;
}

.ant-carousel .slick-slide h3 {
  color: #fff;
}
</style>
