<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="el-icon-plus f-s-20"></i>
              <i v-else class="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'">
              <!-- 添加关联初始账号 -->
              <div class="p-b-10">
                <el-divider content-position="left" v-if="pageState === 'add'">
                  <font class="fb f-s-18 normalFontColor">关联初始账号</font>
                </el-divider>
              </div>
              <el-form-item label="账号" v-if="pageState === 'add'">
                <el-input v-model="form.admin_name" placeholder="绑定店铺的初始账号。PS:此账号为管理员身份且不可变更" />
              </el-form-item>
              <el-form-item label="初始密码" class="m-b-20" v-if="pageState === 'add'">
                <el-input show-password v-model="form.pwd" placeholder="'密码'" />
              </el-form-item>
              <!-- 添加店铺 -->
              <div class="p-t-10 p-b-5" v-if="pageState === 'add'">
                <el-divider content-position="left">
                  <font class="fb f-s-18 normalFontColor">店铺参数</font>
                </el-divider>
              </div>
              <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-input v-model="form.default_transport_price" placeholder="送货运费缺省值">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="打包费缺省">
                <el-input v-model="form.default_pack_price" placeholder="打包服务费缺省值">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <!-- 下单备注预设 -->
              <el-form-item label="下单备注预设">
                <el-tag :key="index" v-for="(tag, index) in form.remark_presup" closable :disable-transitions="false"
                  @close="handleCloseTag(tag)">
                  {{ tag }}
                </el-tag>
                <span class="" v-if="inputTagVisible">
                  <el-input class="input-new-tag" v-model="inputTagValue" ref="saveTagInput">
                  </el-input>
                  <el-button type="primary" @click="handleInputConfirm" icon="el-icon-plus">添加</el-button>
                </span>
                <el-button v-else @click="showTagInput" icon="el-icon-plus">点击添加</el-button>
              </el-form-item>
              <!-- 退款订单备注预设 -->
              <el-form-item label="退款备注预设">
                <el-tag :key="index" v-for="(tag, index) in form.refund_remark_presup" closable
                  :disable-transitions="false" @close="handleCloseTagRefund(tag)">
                  {{ tag }}
                </el-tag>
                <span class="" v-if="inputTagVisibleRefund">
                  <el-input class="input-new-tag" v-model="inputTagValueRefund" ref="saveTagInputRefund">
                  </el-input>
                  <el-button type="primary" @click="handleInputConfirmRefund" icon="el-icon-plus">添加</el-button>
                </span>
                <el-button v-else @click="showTagInputRefund" icon="el-icon-plus">点击添加</el-button>
              </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: {
        admin_name: '', // 初始账号
        pwd: '', // 初始密码
        shop_id: '',
        name: '',
        waiter: '',
        service_wx: '',
        tel: '',
        email: '',
        price_min: '',
        weight_max: '',
        default_transport_price: '',
        default_pack_price: '',
        remark_presup: [],
        refund_remark_presup: [],
        desc: '',
        upFile: '',
        oldFile: '',
        intervalTime: [new Date(0, 0, 0, 8, 0), new Date(0, 0, 0, 20, 0)]
      },
      inputTagVisible: false, // 备注预设 添加按钮 输入框反向显示
      inputTagValue: '', // 备注预设 输入框值
      inputTagVisibleRefund: false, // 备注预设 添加按钮 输入框反向显示
      inputTagValueRefund: '', // 备注预设 输入框值
      pageState: 'add', // 页面状态
      shop: null
    }
  },
  components: {
    SelectionShopId
  },
  computed: {
    /**
     * @description: 获取商铺列表
     */
    shopList () {
      return this.$store.state.shopList
    },
    shop_id () {
      return this.form.shop_id
    }
  },
  methods: {
    // 备注预设 相关函数
    handleCloseTag (tag) { // 删除标签
      this.form.remark_presup.splice(this.form.remark_presup.indexOf(tag), 1)
    },
    showTagInput () { // 显示输入框
      this.inputTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () { // 添加新的标签
      const inputValue = this.inputTagValue
      if (inputValue) {
        this.form.remark_presup.push(inputValue)
      }
      this.inputTagVisible = false// 隐藏输入框 显示添加按钮
      this.inputTagValue = ''
    },
    handleCloseTagRefund (tag) { // 删除标签
      this.form.refund_remark_presup.splice(this.form.refund_remark_presup.indexOf(tag), 1)
    },
    showTagInputRefund () { // 显示输入框
      this.inputTagVisibleRefund = true
      this.$nextTick(_ => {
        this.$refs.saveTagInputRefund.$refs.input.focus()
      })
    },
    handleInputConfirmRefund () { // 添加新的标签
      const inputTagValueRefund = this.inputTagValueRefund
      if (inputTagValueRefund) {
        this.form.refund_remark_presup.push(inputTagValueRefund)
      }
      this.inputTagVisibleRefund = false// 隐藏输入框 显示添加按钮
      this.inputTagValueRefund = ''
    },
    /* 文件上传表单 */
    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.admin_name = data.admin_name || ''
      this.pwd = data.pwd || ''
      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.default_transport_price = data.default_transport_price
      this.form.default_pack_price = data.default_pack_price
      this.form.remark_presup = data.remark_presup || []
      this.form.refund_remark_presup = data.refund_remark_presup || []
      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,
            default_transport_price: this.shop.default_transport_price,
            default_pack_price: this.shop.default_pack_price,
            remark_presup: this.shop.remark_presup,
            refund_remark_presup: this.shop.refund_remark_presup,
            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)
      console.log(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;
}

.el-tag {
  margin-right: 10px;
}

.input-new-tag {
  margin-right: 10px;
  width: 20%;
  vertical-align: bottom;
}

.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>
