<template>
  <SpRouterView>
    <SpPlatformTip h5 app alipay />
    <div class="action-container">
      <el-button type="primary" icon="iconfont icon-xinzengcaozuo-01" @click="addElement">
        活动添加
      </el-button>
    </div>

    <SpFilterForm :model="params" @onSearch="onSearch" @onReset="onReset">
      <SpFilterFormItem prop="field_title" label="标题:">
        <el-input v-model="params.field_title" placeholder="标题" />
      </SpFilterFormItem>
      <SpFilterFormItem prop="状态" label="标题:">
        <el-select v-model="params.status" placeholder="状态">
          <el-option key="waiting" label="未开始" value="waiting" />
          <el-option key="ongoing" label="进行中" value="ongoing" />
          <el-option key="end" label="已结束" value="end" />
        </el-select>
      </SpFilterFormItem>
      <SpFilterFormItem prop="create_time" label="时间:">
        <el-date-picker
          v-model="params.create_time"
          type="daterange"
          value-format="yyyy/MM/dd"
          placeholder="根据添加时间筛选"
        />
      </SpFilterFormItem>
    </SpFilterForm>

    <el-table v-loading="loading" border :data="tableList">
      <el-table-column prop="activity_id" label="编号" width="50" />
      <el-table-column prop="activity_name" label="活动名称" min-width="300" />
      <el-table-column prop="start_time" label="活动有效期" min-width="300">
        <template slot-scope="scope">
          {{ scope.row.start_date }} ~ {{ scope.row.end_date }}
        </template>
      </el-table-column>
      <el-table-column prop="total_join_num" label="报名人数" width="100">
        <template slot-scope="scope">
          {{ scope.row.total_join_num || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="130">
        <template slot-scope="scope">
          <router-link
            class="iconfont icon-edit1"
            :to="{ path: matchHidePage('editor'), query: { id: scope.row.activity_id } }"
          />
          <i class="iconfont icon-search-plus" @click="preview(scope.$index, scope.row)" />
          <!-- v-if="scope.row.status == 1" -->
          <i class="mark iconfont icon-trash-alt1" @click="deleteAction(scope.$index, scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <div class="content-center content-top-padded">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="page.pageIndex"
        :page-sizes="[10, 20, 50]"
        :total="page.total"
        :page-size="page.pageSize"
        @current-change="onCurrentChange"
        @size-change="onSizeChange"
      />
    </div>

    <sideBar width="50" :visible.sync="showSideBar" :title="'活动场次'">
      <div class="action-container">
        <el-button
          type="primary"
          icon="iconfont icon-xinzengcaozuo-01"
          @click="
            sessDialog = true
            sessForm = {}
            selRow = {}
          "
        >
          添加场次
        </el-button>
      </div>
      <el-table
        :header-cell-style="{ height: '40px', padding: '8px' }"
        empty-text="暂无场次"
        :data="tableData"
        style="width: 100%"
        stripe
      >
        <el-table-column align="center" type="index" width="50"> </el-table-column>
        <el-table-column align="center" prop="start_time" label="开始时间" width="180">
        </el-table-column>
        <el-table-column align="center" prop="end_time" label="结束时间" width="180">
        </el-table-column>
        <el-table-column align="center" prop="join_limit" label="可报名人数"> </el-table-column>
        <el-table-column align="center" width="160" label="操作">
          <template slot-scope="scope">
            <el-button style="margin-right: 20px" size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              @confirm="handleDelete(scope.row)"
              title="确定删除该场次吗？"
              confirm-button-type="danger"
            >
              <el-button slot="reference" size="mini" type="danger">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </sideBar>

    <SpDialog
      ref="sessDialogRef"
      v-model="sessDialog"
      :title="sessForm.registration_session_id > 0 ? '编辑场次' : '添加场次'"
      :modal="false"
      :form="sessForm"
      :form-list="sessFormList"
      @onSubmit="onSessFormSubmit"
      @input="sessForm = {}"
    />

    <el-dialog :visible.sync="dialogVisible" title="活动详情">
      <el-descriptions :column="1">
        <el-descriptions-item label="活动名称">{{ dataInfo.activity_name }}</el-descriptions-item>
        <el-descriptions-item label="活动有效时间"
          >{{ dataInfo.start_date }}-{{ dataInfo.end_date }}</el-descriptions-item
        >
        <el-descriptions-item label="活动地址">
          {{ dataInfo.address }}
        </el-descriptions-item>
        <el-descriptions-item label="封面">
          <div v-if="dataInfo.pics" style="display: flex; flex-wrap: wrap">
            <!-- <img
              v-for="item in JSON.parse(dataInfo.pics)"
              :src="item"
              style="width: 100px; height: 100px"
            /> -->
            <el-image
              v-for="item in JSON.parse(dataInfo.pics)"
              :key="item"
              class="img-content"
              style="width: 100px; height: 100px"
              :src="item"
              fit="cover"
            />
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="活动介绍">
          <div class="content-padded" v-html="dataInfo.intro"></div>
        </el-descriptions-item>
        <el-descriptions-item label="报名问卷模板">
          {{ dataInfo.temp_id | formatterLable(temp_options) }}
        </el-descriptions-item>
        <el-descriptions-item label="提交报名次数">
          {{ dataInfo.join_limit }}
        </el-descriptions-item>
        <el-descriptions-item label="是否开启短信通知">{{
          dataInfo.is_sms_notice == 1 ? '是' : '否'
        }}</el-descriptions-item>
        <el-descriptions-item label="是否开启小程序通知">{{
          dataInfo.is_wxapp_notice == 1 ? '是' : '否'
        }}</el-descriptions-item>
      </el-descriptions>
      <!-- <el-form ref="dataInfo" label-width="200px" label-position="left" class="demo-ruleForm">
        <el-form-item :label="dataInfo.field_title">
          <el-col v-if="dataInfo.form_element == 'text'" :span="12">
            <el-input placeholder="text预览" />
          </el-col>
          <el-col v-if="dataInfo.form_element == 'textarea'" :span="12">
            <el-input type="textarea" placeholder="textarea预览" />
          </el-col>
          <el-col v-if="dataInfo.form_element == 'number'" :span="12">
            <el-input-number type="textarea" placeholder="55.55" />
          </el-col>
          <el-col v-if="dataInfo.form_element == 'image'" :span="12">
            <el-upload class="avatar-uploader" action="" :show-file-list="false">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-col>
          <el-col v-if="dataInfo.form_element == 'radio'" :span="12">
            <el-radio-group>
              <el-radio v-for="(item, index) in dataInfo.options" :key="index" :label="3">
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </el-col>
          <el-col v-if="dataInfo.form_element == 'checkbox'" :span="12">
            <el-checkbox-group>
              <el-checkbox
                v-for="(item, index) in dataInfo.options"
                :key="index"
                label="item.value"
              >
                {{ item.value }}
              </el-checkbox>
            </el-checkbox-group>
          </el-col>
          <el-col v-if="dataInfo.form_element == 'select'" :span="12">
            <el-select placeholder="请选择">
              <el-option
                v-for="item in dataInfo.options"
                :key="item.value"
                :label="item.value"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col v-if="dataInfo.form_element == 'date'" :span="12">
            <el-date-picker v-model="value1" type="date" placeholder="选择日期" />
          </el-col>
          <el-col v-if="dataInfo.form_element == 'time'" :span="12">
            <el-time-picker
              v-model="value2"
              arrow-control
              :picker-options="{
                selectableRange: '18:30:00 - 20:30:00'
              }"
              placeholder="任意时间点"
            />
          </el-col>
          <el-col v-if="dataInfo.form_element == 'area'" :span="12">
            <el-cascader
              v-model="value"
              :options="options"
              :props="{ expandTrigger: 'hover' }"
              @change="handleChange"
            />
          </el-col>
        </el-form-item>
      </el-form> -->
    </el-dialog>
  </SpRouterView>
</template>
<script>
import sideBar from '@/components/element/sideBar'
import {
  regActivityDel,
  regActivityInvalid,
  getTemplateList,
  registrationActivitySessionList,
  registrationActivitySessionUpdate,
  registrationActivitySessionDel,
  registrationActivitySessionAdd
} from '@/api/selfhelpform'
import mixin, { pageMixin } from '@/mixins'
import dayjs from 'dayjs'
export default {
  filters: {
    formatterLable(value, options) {
      return options.find((item) => item.value == value)?.label
    }
  },
  components: {
    sideBar
  },
  mixins: [mixin, pageMixin],
  provide() {
    return {
      refresh: this.fetchList
    }
  },
  data() {
    const initialParams = {
      field_title: undefined,
      status: 'ongoing',
      create_time: []
    }
    return {
      initialParams,
      params: {
        ...initialParams
      },
      showSideBar: false,
      tableData: [],
      sessDialog: false,
      sessForm: {
        start_time: '',
        end_time: '',
        join_limit: null
      },
      sessFormList: [
        {
          label: '日期',
          key: 'day',
          required: true,
          message: '不能为空',
          component: ({ key }, value) => (
            <el-date-picker
              v-model={value[key]}
              type='date'
              placeholder='选择日期'
              value-format='yyyy-MM-dd'
              style={{ width: '260px' }}
              disabledDate={(time) => time < Date.now()}
            ></el-date-picker>
          )
        },
        {
          label: '开始时间',
          key: 'start_time',
          type: 'input',
          placeholder: '请输入开始时间',
          required: true,
          message: '不能为空',
          component: ({ key }, value) => (
            <el-time-select
              placeholder='开始时间'
              v-model={value[key]}
              picker-options={{
                start: '05:00',
                step: '00:10',
                end: '23:45'
              }}
              // onBlur={() => {
              //   value['end_time'] = ''
              // }}
              value-format='HH:mm:ss'
              style={{ width: '260px' }}
            ></el-time-select>
          )
        },
        {
          label: '结束时间',
          key: 'end_time',
          type: 'input',
          placeholder: '请输入结束时间',
          required: true,
          message: '不能为空',
          component: ({ key }, value) => (
            <el-time-select
              placeholder='结束时间'
              v-model={value[key]}
              picker-options={{
                start: '05:00',
                step: '00:10',
                end: '23:45',
                minTime: value['start_time']
              }}
              value-format='HH:mm:ss'
              style={{ width: '260px' }}
            ></el-time-select>
          )
        },
        {
          label: '可报名人数',
          key: 'join_limit',
          type: 'number',
          required: true,
          message: '不能为空'
        }
      ],
      templateParams: {
        page: 1,
        pageSize: 10,
        tem_name: '',
        // tem_type: 'ask_answer_paper',
        is_valid: 1
      },
      temp_options: [],
      imageUrl: '',
      loading: false,
      dialogVisible: false,
      dataInfo: {},
      options: [
        {
          value: 'ziyuan',
          label: '资源',
          children: [
            {
              value: 'axure',
              label: 'Axure Components'
            },
            {
              value: 'sketch',
              label: 'Sketch Templates'
            },
            {
              value: 'jiaohu',
              label: '组件交互文档'
            }
          ]
        }
      ],
      activity_id: null,
      selRow: {}
    }
  },
  watch: {
    getStatus(val) {
      if (val) {
        this.fetchList()
      }
    }
  },
  mounted() {
    this.getTemplateList()
    this.fetchList()
  },
  methods: {
    fetchTableList() {
      registrationActivitySessionList({
        activity_id: this.activity_id,
        page: 1,
        pageSize: 100
      }).then((res) => {
        this.tableData = res.data?.data?.list || []
      })
    },
    onSessFormSubmit() {
      console.log(this.sessForm)
      const { sessForm, activity_id, selRow } = this
      const req = { ...sessForm }
      req.activity_id = activity_id
      const { start_time, end_time, day } = sessForm
      req.start_time = `${day} ${start_time}:00`
      req.end_time = `${day} ${end_time}:00`
      !selRow?.registration_session_id
        ? registrationActivitySessionAdd(req).then((res) => {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
          })
        : registrationActivitySessionUpdate(req).then((res) => {
            this.$message({
              message: '更新成功',
              type: 'success'
            })
          })
      this.sessDialog = false
      setTimeout(() => {
        this.fetchTableList()
      }, 200)
    },
    handleEdit(row) {
      this.selRow = row
      const { start_time, end_time, join_limit } = row
      this.sessForm = {
        day: dayjs(start_time).format('YYYY-MM-DD'),
        start_time: dayjs(start_time).format('HH:mm'),
        end_time: dayjs(end_time).format('HH:mm'),
        registration_session_id: row.registration_session_id,
        join_limit
      }
      this.sessDialog = true
    },
    handleDelete(row) {
      this.selRow = row
      const { registration_session_id } = row
      registrationActivitySessionDel({ registration_session_id }).then((res) => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.fetchTableList()
      })
    },
    getTemplateList() {
      this.loading = true
      getTemplateList(this.templateParams).then((response) => {
        response.data.data.list.map((item) => {
          this.temp_options.push({
            label: item.tem_name,
            value: item.id
          })
        })
        // this.temp_options = response.data.data.list
        this.total_count = response.data.data.total_count
        this.loading = false
      })
    },
    addElement() {
      // 添加商品
      this.$router.push({ path: this.matchHidePage('editor') })
    },
    delData(index, row) {
      var msg = '此操作将删除该活动, 是否继续?'
      this.$confirm(msg, '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            regActivityDel({ activity_id: row.activity_id }).then((response) => {
              this.getDataList()
              this.$message({
                message: '删除完成',
                type: 'success',
                duration: 5 * 1000
              })
            })
          }
          done()
        }
      })
    },
    invalidData(index, row) {
      var msg = '此操作将永久终止该活动, 是否继续?'
      this.$confirm(msg, '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            regActivityInvalid({ activity_id: row.activity_id }).then((response) => {
              this.getDataList()
              this.$message({
                message: '终止该活动成功',
                type: 'success',
                duration: 5 * 1000
              })
            })
          }
          done()
        }
      })
    },
    preview(index, row) {
      // 预览弹框
      this.showSideBar = true
      this.activity_id = row.activity_id
      this.fetchTableList()
      // this.dialogVisible = true
      this.selRow = row
      this.dataInfo = row
    },
    onSearch() {
      this.page.pageIndex = 1
      this.$nextTick(() => {
        this.fetchList()
      })
    },
    onReset() {
      this.params = { ...this.initialParams }
      this.onSearch()
    },
    getParams() {
      const time = {}
      const create_time = this.params.create_time
      if (create_time.length) {
        time.start_time = this.dateStrToTimeStamp(create_time[0] + ' 00:00:00')
        time.end_time = this.dateStrToTimeStamp(create_time[1] + ' 00:00:00')
      }
      let params = {
        ...this.params,
        create_time: [],
        ...time
      }
      return params
    },
    async fetchList() {
      this.loading = true
      const { pageIndex: page, pageSize } = this.page
      let params = {
        page,
        pageSize,
        ...this.getParams()
      }
      const { list, total_count } = await this.$api.selfhelpform.regActivityList(params)
      this.tableList = list
      this.page.total = total_count
      this.loading = false
    },
    deleteAction(index, row) {
      this.$confirm('此操废弃该元素, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteSetting(row.activity_id)
            .then((response) => {
              this.tableList.splice(index, 1)
              this.$message({
                message: '废弃成功',
                type: 'success',
                duration: 5 * 1000
              })
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '废弃失败'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    getTaskTime(strDate) {
      let date = new Date(strDate)
      let y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let str = y + '-' + m + '-' + d
      return str
    },
    getTimeStr(date) {
      return this.getTaskTime(new Date(parseInt(date) * 1000))
    },
    dateStrToTimeStamp(str) {
      return Date.parse(new Date(str)) / 1000
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep {
  .cell {
    .iconfont {
      padding: 0 10px;
    }
  }
  .el-descriptions-item__label {
    min-width: 100px;
  }
  .content-padded {
    padding: 0 10px;
    width: 100%;
    img {
      width: 90%;
    }
    p {
      margin: 0;
    }
  }
}
.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }

  img {
    width: 90%;
  }
}

.sp-filter-form {
  margin-bottom: 16px;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 10px;

  img {
    width: 90%;
  }
}

.row-bg {
  padding: 10px 20px;
  background-color: #f9fafc;
}

.service-label .el-checkbox:first-child {
  margin-left: 15px;
}

.service-label .el-input:first-child {
  margin-left: 15px;
}

.grid-detail {
  max-height: 300px;
  overflow-y: scroll;
  margin-bottom: 20px;
}

.el-carousel {
  width: 375px;
}
</style>
<style lang="scss">
.grid-detail {
  table,
  .detail-content-wrap,
  .detail-content-item {
    width: 100% !important;
  }

  img {
    width: 100%;
  }
}

.grid-attribute {
  table {
    width: 100% !important;
  }
}
</style>
