<template>
  <div class="page">
    <div class="topbox">
      <div
        v-for="(item, index) in topList"
        :key="index"
        class="levelList_i"
        :class="tabActive == item.id ? 'act' : ''"
        @click.prevent="handleLink(item.id)"
      >
        {{ item.name }}
      </div>
    </div>

    <!-- <div class="main_a"> -->
    <div class="main">
      <div v-show="tabActive == 0">
        <div class="tit">{{ '基本信息' }}</div>
        <div class="xian" />
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item :label="'活动名称'" prop="actName">
                <el-input
                  v-model="ruleForm.actName"
                  clearable
                  :disabled="lookOver"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="隶属体系" prop="pkVertex">
                <!-- <imageUpload v-model="ruleForm.pkVertex" /> -->
                <el-select v-model="ruleForm.pkVertex" placeholder="全部" clearable multiple>
                  <el-option
                    v-for="item in vertexList"
                    :key="item.pkId"
                    :label="item.vertexName"
                    :value="item.pkId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item :label="'活动说明'" prop="actExplain">
                <el-input
                  v-model="ruleForm.actExplain"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入活动说明"
                  :disabled="lookOver"
                />
                <!-- <editor
                  ref="sptwEditor"
                  v-model="ruleForm.actExplain"
                  :read-only="lookOver"
                  :min-height="196"
                  :upload-url="uploadImgUrl"
                /> -->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="'活动封面'" prop="actCover">
                <imageUpload v-model="ruleForm.actCover" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('门票金额')" required>
                <el-input
                  v-model="ruleForm.payMoney"
                  :disabled="lookOver"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('数量')" required>
                <el-input
                  v-model="ruleForm.quantity"
                  :disabled="lookOver"
                  clearable
                  type="number"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('限购数量')" required>
                <el-input
                  v-model="ruleForm.limitQuantity"
                  :disabled="lookOver"
                  clearable
                  type="number"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="'活动时间'" prop="ruleFormTime">
                <el-date-picker
                  v-model="ruleForm.ruleFormTime"
                  :disabled="lookOver"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  :range-separator="'至'"
                  :start-placeholder="'开始日期'"
                  :end-placeholder="'结束日期'"
                  @change="changeTime"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="'展示时间'" prop="ruleFormTime1">
                <el-date-picker
                  v-model="ruleForm.ruleFormTime1"
                  :disabled="lookOver"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  :range-separator="'至'"
                  :start-placeholder="'开始日期'"
                  :end-placeholder="'结束日期'"
                  @change="changeTime1"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- <directUpdata v-show="tabActive==2"
                    ref="directUpdata"></directUpdata> -->
    </div>
    <div v-show="controlType != 4" class="footer">
      <el-button size="small" class="cancelBtn" @click="cancel">
        {{ '取消' }}
      </el-button>
      <el-button size="small" class="sureBtn" @click="submit('ruleForm')">
        {{ '确认' }}
      </el-button>
    </div>
    <!-- </div> -->
  </div>
</template>

<script>
import Editor from '@/components/Editor'

import * as api from '@/api/ticket.js'
import ImageUpload from '@/components/ImageUpload'
import { vertexList } from '@/api/settle.js'
// import directUpdata from '@/views/marketing/benefitsGift/directUpdata'
export default {
  name: 'AddTicket',
  components: {
    ImageUpload,
    // directUpdata,
    Editor
  },
  data() {
    return {
      tabActive: 0,
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/system/upload',
      ruleForm: {
        payMoney: '',
        quantity: '',
        pkVertex: '',
        limitQuantity: '',
        ruleFormTime: [],
        ruleFormTime1: []
      },
      vertexList: [],
      rules: {
        actName: [
          { required: true, message: this.$t('请输入活动名称'), trigger: 'blur' }
        ],
        actExplain: [
          { required: true, message: this.$t('请输入活动说明'), trigger: 'blur' }
        ],
        actCover: [
          { required: true, message: this.$t('请上传活动封面'), trigger: 'change' }
        ],
        payMoney: [
          { required: true, message: this.$t('请输入金额'), trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: this.$t('请输入数量'), trigger: 'blur' },
          { type: 'number', min: 1, max: 999999, message: this.$t('数量必须在1~999999之间'), trigger: 'blur' }
        ],
        limitQuantity: [
          { required: true, message: this.$t('请输入限购数量'), trigger: 'blur' },
          { type: 'number', min: 1, max: 999999, message: this.$t('限购数量必须在1~999999之间'), trigger: 'blur' }
        ],
        ruleFormTime: [
          { required: true, message: this.$t('请输入活动时间'), trigger: 'change' }
        ],
        ruleFormTime1: [
          { required: true, message: this.$t('请输入展示时间'), trigger: 'change' }
        ]
      },
      lookOver: false,
      pkId: '',
      controlType: '',
      addData: {}
    }
  },
  mounted() {
    // （1=新增,2=修改,3=删除）4查看
    if (
      this.$route.query.controlType == 4 ||
      this.$route.query.controlType == 3
    ) {
      this.lookOver = true
    } else {
      this.lookOver = false
    }
    this.controlType = this.$route.query.controlType
    this.pkId = this.$route.query.pkId || ''
    this.getVertexList()
    if (this.pkId) {
      this.getDetails()
    }
  },
  methods: {
    getVertexList() {
      vertexList().then((res) => {
        this.vertexList = res.data
      })
    },
    cancel() {
      this.$router.go(-1)
    },
    getDetails() {
      api.getOneTicket(this.pkId).then((res) => {
        this.addData = res.data
        this.$set(this.ruleForm, 'actName', res.data.actName)
        this.$set(this.ruleForm, 'actExplain', res.data.actExplain)
        this.$set(this.ruleForm, 'actCover', res.data.actCover)
        this.ruleForm.pkId = res.data.pkId

        // 处理时间字段，去掉时分秒部分，只保留日期
        const formatDateOnly = (datetime) => {
          if (!datetime) return ''
          return datetime.split(' ')[0] // 去掉时分秒，只保留日期部分
        }

        this.ruleForm.actStartDate = formatDateOnly(res.data.actStartDate)
        this.ruleForm.actEndDate = formatDateOnly(res.data.actEndDate)
        this.ruleForm.disStartDate = formatDateOnly(res.data.disStartDate)
        this.ruleForm.disEndDate = formatDateOnly(res.data.disEndDate)

        this.ruleForm.payMoney = res.data.payMoney
        this.ruleForm.quantity = res.data.quantity
        this.ruleForm.limitQuantity = res.data.limitQuantity
        this.ruleForm.pkVertex = res.data.pkVertex ? res.data.pkVertex.split(',').map(item => Number(item)) : []
        this.$set(this.ruleForm, 'ruleFormTime', [
          this.ruleForm.actStartDate,
          this.ruleForm.actEndDate
        ])
        this.$set(this.ruleForm, 'ruleFormTime1', [
          this.ruleForm.disStartDate,
          this.ruleForm.disEndDate
        ])
        // let that = this;
        // setTimeout(() => {
        //   that.getCheck();
        // }, 50);
      })
    },
    // 切换tab
    handleLink(id) {
      this.tabActive = id
    },
    changeTime(val) {
      this.ruleForm.actStartDate = val[0]
      this.ruleForm.actEndDate = val[1]
    },
    changeTime1(val) {
      this.ruleForm.disStartDate = val[0]
      this.ruleForm.disEndDate = val[1]
    },

    submit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let params = {}

          // 处理时间格式，补充时分秒
          const formatDateTime = (date, isEndTime = false) => {
            if (!date) return ''
            const timeStr = isEndTime ? ' 23:59:59' : ' 00:00:00'
            return date + timeStr
          }

          params = {
            ...this.ruleForm,
            pkVertex: this.ruleForm.pkVertex ? this.ruleForm.pkVertex.join(',') : '',
            // 处理活动时间，补充时分秒
            actStartDate: formatDateTime(this.ruleForm.actStartDate, false),
            actEndDate: formatDateTime(this.ruleForm.actEndDate, true),
            // 处理展示时间，补充时分秒
            disStartDate: formatDateTime(this.ruleForm.disStartDate, false),
            disEndDate: formatDateTime(this.ruleForm.disEndDate, true)
          }

          if (this.controlType == 1) {
            api.ticketSave(params).then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.$router.push({
                  path: 'TicketList'
                })
              }
            })
          } else {
            api.ticketUpdate(params).then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.$router.push({
                  path: 'TicketList'
                })
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  padding: 20px;
  background: #f9f9f9;
  font-size: 14px;

  .main_a {
    height: calc(100vh - 144px);
    display: flex;
    flex-direction: column;
  }

  .main {
    background: #ffffff;
    border-radius: 8px;
    // height: calc(100vh - 124px);
    box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);
  }

  ::v-deep .el-select {
    width: 100%;
  }
}

.footer {
  height: 68px;
  background: #ffffff;
  box-shadow: 0px -3px 20px 0px rgba(204, 204, 204, 0.5);
  // margin: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;

  .thebtn1 {
    background: #3181e5;
    color: #ffffff;
    padding: 9px 45px;
  }

  .thebtn2 {
    background: #cccccc;
    color: #ffffff;
    padding: 9px 45px;
  }
}

.tit {
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  padding: 0 20px;
  border-left: 5px solid #c8161d;
  margin: 20px 0 10px 0;
}

.xian {
  height: 1px;
  background: rgba(0, 0, 0, 0.1);
}

.demo-ruleForm {
  padding: 20px 0;
}

::v-deep .el-date-editor--datetimerange {
  width: auto !important;
}

.flexed {
  display: flex;
}

.flexed_l {
  margin-right: 20px;
}

.topbox {
  align-items: center;
  padding: 0px 0 5px 0;
  display: flex;
  //   background: skyblue;
  .levelList_i {
    padding: 4px 15px;
    margin-left: 20px;
    position: relative;
    cursor: pointer;
    min-width: 88px;
    // height: 28px;
    border-radius: 17px;
    border: 1px solid #cccccc;
    font-size: 12px;
    font-family: MicrosoftYaHei;
    text-align: center;
    // line-height: 28px;
  }

  .act {
    color: #ffffff;
    background: #c8161d;
  }
}

::v-deep .el-form-item {
  margin-bottom: 20px !important;
}
</style>
