<template>
  <div class="app-container">
    <el-row class="m-t-0">
      <el-col :span="24">
        <el-container>
          <el-header height="42px" class="l-h-42 p-l-10 p-r-10 border border-b-n">
            <div class="l">
              <i v-if="pageState === 'add'" class="iconfont el-icon-plus f-s-20"></i>
              <i v-else class="iconfont el-icon-edit f-s-20"></i>
              <font class="m-l-10 f-s-18 fb">{{ $route.meta.title }}</font>
            </div>
          </el-header>
          <el-main class="border p-20 m-b-20">
            <el-form ref="form" :model="form" label-width="120px" :label-position="$store.state.app.isWideScreen?'top':'right'">
              <!-- 用户select选项 -->
              <el-form-item v-if="pageState === 'edit'" label="商铺选择">
                <SelectionShopId v-model="form.shop_id" />
              </el-form-item>
              <el-form-item label="店铺名称">
                <el-input v-model="form.name" placeholder="推荐使用景区名称" />
              </el-form-item>
              <el-form-item label="负责人">
                <el-input v-model="form.waiter" placeholder="店铺负责人，填写其姓名或昵称" />
              </el-form-item>
              <el-form-item label="微信账号">
                <el-input v-model="form.service_wx" placeholder="微信账号绑定" />
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input v-model="form.tel" placeholder="联系电话，既客服电话" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="form.email" placeholder="用来接收验证信息等" />
              </el-form-item>
              <el-form-item label="最低消费">
                <el-input v-model="form.price_min" placeholder="游客扫码下单最低消费值">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="运载极限重量">
                <el-input v-model="form.weight_max" placeholder="无人机每单运载的重量上限，通常以店铺内飞机的载重上限为准">
                  <template slot="append">克</template>
                </el-input>
              </el-form-item>
              <el-form-item label="营业时间">
                <el-time-picker is-range v-model="form.intervalTime" range-separator="至" start-placeholder="开始时间"
                  end-placeholder="结束时间" placeholder="选择时间范围">
                </el-time-picker>
              </el-form-item>
              <el-form-item label="商铺LOGO">
                <el-upload class="avatar-uploader" drag name="file" :action="action" :headers="myheader"
                  :show-file-list="false" :on-success="handleUpSuccess" :on-error="handleUpErr"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="form.upFile != ''"
                    :src="$store.state.settings.tempPath + form.upFile" class="avatar" />
                  <img v-else-if="form.oldFile != [] && form.upFile == ''"
                    :src="form.oldFile[0]" class="avatar" />
                  <template v-else>
                    <i class="el-icon-plus f-s-30 m-t-70 seatFontColor"></i>
                    <div class="el-upload__text"><em>建议200*200像素 <br> jpg png gif svg</em></div>
                  </template>
                </el-upload>
              </el-form-item>
              <el-form-item label="描述">
                <el-input v-model="form.desc" type="textarea" placeholder="商铺小程序介绍说明或景区的描述等,会显示在小程序的介绍里面" />
              </el-form-item>
              <el-form-item v-if="pageState == 'add' ? true : false">
                <el-button type="primary" icon="el-icon-plus" @click="addShop">创建</el-button>
                <el-button @click="setForm({ oldFile: '' }); form.upFile = ''" class="iconfont icon-qingchu">
                  <font class="m-l-5">重填</font>
                </el-button>
              </el-form-item>
              <el-form-item v-else>
                <el-button type="primary" icon="el-icon-edit" @click="saveShop">更新</el-button>
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>
      </el-col>
    </el-row>
  </div>
</template>

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

export default {
  name: 'ShopEdit',
  data () {
    return {
      action: this.$store.state.settings.baseURL + this.$store.state.settings.apiAdminPath + 'upImgFile',
      myheader: { token: this.$store.state.user.token },
      form: {
        shop_id: '',
        name: '',
        waiter: '',
        service_wx: '',
        tel: '',
        email: '',
        price_min: '',
        weight_max: '',
        desc: '',
        upFile: '',
        oldFile: '',
        intervalTime: [new Date(0, 0, 0, 8, 0), new Date(0, 0, 0, 20, 0)]
      },
      pageState: 'add', // 页面状态
      shop: null
    }
  },
  components: {
    SelectionShopId
  },
  computed: {
    /**
     * @description: 获取商铺列表
     */
    shopList () {
      return this.$store.state.shopList
    },
    shop_id () {
      return this.form.shop_id
    }
  },
  methods: {
    /* 文件上传表单 */
    handleUpSuccess (res) {
      console.log(res)
      if (res.status === 0) {
        this.$message.error(res.msg)
      } else {
        this.form.upFile = res.data
        this.$message.success(res.msg)
      }
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isJPG) {
        this.$message.error('上传图片只能是JPG|PNG|GIF格式!')
      }
      return isJPG
    },
    handleUpErr () {
      // this.$message.error('接口访问失败')
      this.$message.error(this.action)
    },
    // 将时间字符串转换为Date对象
    parseTimeString (timeString) {
      const [hours, minutes, seconds] = timeString.split(':')
      return new Date(0, 0, 0, parseInt(hours), parseInt(minutes), parseInt(seconds))
    },
    // 将Date对象转换为时间字符串 'HH:mm:ss'
    formatDateToString (date) {
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      return `${hours}:${minutes}:${seconds}`
    },
    // 设置表单
    setForm (data) {
      if (data.desc == null) {
        data.desc = ''
      }
      this.form.name = data.name
      this.form.waiter = data.waiter
      this.form.service_wx = data.service_wx
      this.form.tel = data.tel
      this.form.email = data.email
      this.form.price_min = data.price_min
      this.form.weight_max = data.weight_max
      this.form.oldFile = data.oldFile
      this.form.upFile = data.upFile
      this.form.desc = data.desc
      this.form.intervalTime = data.intervalTime
      if (Object.keys(data).length === 0) {
        this.$message.warning('清空表单')
      }
    },
    // 初始化页面 添加or编辑
    initPage () {
      if (this.$route.path.indexOf('add') > -1) {
        this.pageState = 'add'
      } else {
        this.pageState = 'edit'
        this.shop = this.shopList.find((item) => item.shop_id === this.shop_id)
        if (this.shop) {
          const data = {
            name: this.shop.name,
            waiter: this.shop.waiter,
            service_wx: this.shop.service_wx,
            tel: this.shop.tel,
            email: this.shop.email,
            price_min: this.shop.price_min,
            weight_max: this.shop.weight_max,
            oldFile: this.shop.logo,
            upFile: '',
            intervalTime: [this.parseTimeString(this.shop.opening_time), this.parseTimeString(this.shop.closeing_time)]
          }
          this.setForm(data)
        }
      }
    },
    /**
     * @description: 创建新商铺
     */
    async addShop () {
      this.form.opening_time = this.formatDateToString(this.form.intervalTime[0])
      this.form.closeing_time = this.formatDateToString(this.form.intervalTime[1])
      const res = await this.$store.dispatch('fetchAddShop', this.form)
      if (res.data.status === 1) {
        this.$router.push({ path: '/shop/add', query: { refresh: Date.now() } })
      }
    },
    /**
     * @description: 更新商铺
     */
    async saveShop () {
      this.form.opening_time = this.formatDateToString(this.form.intervalTime[0])
      this.form.closeing_time = this.formatDateToString(this.form.intervalTime[1])
      const res = await this.$store.dispatch('fetchSaveShop', this.form)
      if (res.data.status === 1) {
        this.$router.push({ path: '/shop/edit', query: { refresh: Date.now() } })
      }
    }
  },
  watch: {
    shop_id (val) {
      this.initPage()// 初始化页面
    }
  },
  created () {
    this.initPage()// 初始化页面
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-upload__text {
  line-height: 1.2em !important;
}
</style>
