<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'">
              <el-form-item v-if="pageState === 'add'" label="所属商铺">
                <SelectionShopId v-model="form.shop_id" />
              </el-form-item>
              <el-form-item label="站点名称">
                <el-input v-model="form.sitename" placeholder="取餐站点的名字" />
              </el-form-item>
              <el-form-item label="二维码尺寸">
                <el-slider v-model="form.size" :format-tooltip="formatTooltip"></el-slider>
              </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="defaultQr != '' && form.upFile == ''" :src="defaultQr" class="avatar" />
                  <template v-else>
                    <i class="el-icon-plus f-s-30 m-t-70 seatFontColor"></i>
                    <div class="el-upload__text"><em>空为默认LOGO</em></div>
                  </template>
                </el-upload>
              </el-form-item>
              <el-form-item label="绑定航线">
                <el-transfer v-model="form.bindroute" :data="routeData" :titles="['可绑定航线', '已绑定航线']"></el-transfer>
              </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="addSite">创建</el-button>
              </el-form-item>
              <el-form-item v-else>
                <el-button type="primary" icon="el-icon-edit" @click="saveSite">更新</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: 'SiteAdd',
  data () {
    return {
      action: this.$store.state.settings.baseURL + this.$store.state.settings.apiPlanePath + 'upImgFile',
      myheader: { token: this.$store.state.user.token },
      form: {
        shop_id: '',
        sitename: '',
        desc: '',
        upFile: '',
        size: 100,
        bindroute: []
      },
      siteId: this.$route.params.id,
      pageState: 'add', // 页面状态
      site: null,
      defaultQr: ''
    }
  },
  components: {
    SelectionShopId
  },
  computed: {
    /**
     * @description: 获取管理员列表
     */
    adminList () {
      return this.$store.state.adminList
    },
    /**
     * @description: 获取站点列表
     */
    siteList () {
      return this.$store.state.siteList
    },
    /**
     * @description: 获取航线列表
     */
    routeList () {
      return this.$store.state.routeList
    },
    /**
     * @description: 根据用户过滤出 对应的航线列表信息 ps:妈的估计只有三天之内的我才能看懂
     */
    routeData () {
      // 过滤匹配 shop_id 的项，并重组数组
      const filteredRoutes = this.routeList.filter(item => item.shop_id === this.form.shop_id)
        .map(item => ({ key: item.id, label: item.name }))
      // 将 siteList 中的 bind_route 字段拆分为数组 新建的话把所有已绑定的航线 push到一个数组 更新的话除了自身绑定的航线 其余的push到一个数组
      const bindRouteArray = []
      this.siteList.forEach(element => {
        if (this.pageState === 'edit') {
          if (element.id !== this.siteId && element.bind_route !== null) {
            element.bind_route.split(',').forEach(ele => {
              bindRouteArray.push(ele)
            })
          }
        } else {
          if (element.bind_route !== null) {
            element.bind_route.split(',').forEach(ele => {
              bindRouteArray.push(ele)
            })
          }
        }
      })
      // 使用 bindRouteArray 过滤 filteredRoutes
      const finalFilteredRoutes = filteredRoutes.filter((item) =>
        !bindRouteArray.includes(item.key.toString())
      )
      return finalFilteredRoutes
    }
  },
  methods: {
    /**
     * @description: 设置滑动条值
     * @param {*} 值
     */
    formatTooltip (val) {
      return val * 10 + 280 + '像素'
    },
    /* 文件上传表单 */
    handleUpSuccess (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'
      if (!isJPG) {
        this.$message.error('上传图片只能是JPG格式!')
      }
      return isJPG
    },
    handleUpErr () {
      this.$message.error('接口访问失败')
    },
    // 设置表单
    setForm (data) {
      if (data.desc == null) {
        data.desc = ''
      }
      this.form.shop_id = data.shop_id
      this.form.sitename = data.sitename
      this.form.desc = data.desc
      this.form.bindroute = data.bindroute
      this.defaultQr = data.defaultQr
      if (Object.keys(data).length === 0) {
        this.$message.warning('清空表单')
      }
    },
    // 初始化页面 添加or编辑
    initPage () {
      if (this.siteId === undefined) {
        this.pageState = 'add'
      } else {
        this.pageState = 'edit'
        this.site = this.siteList.find((item) => item.id === this.siteId)
        if (this.site) {
          const data = {
            shop_id: this.site.shop_id,
            sitename: this.site.sitename,
            desc: this.site.describe,
            bindroute: this.site.bind_route !== null ? this.site.bind_route.split(',') : [], // 此数据库字段为字符串 分割成数组
            defaultQr: this.site.qr
          }
          this.setForm(data)
        }
      }
    },
    /**
     * @description: 创建新站点
     */
    async addSite () {
      const res = await this.$store.dispatch('fetchAddSite', this.form)
      if (res.data.status === 1) {
        this.$router.push('/site/index')
      }
    },
    /**
     * @description: 更新站点
     */
    async saveSite () {
      this.form.id = this.siteId
      const res = await this.$store.dispatch('fetchSaveSite', this.form)
      if (res.data.status === 1) {
        this.$router.push('/site/index')
      }
    }
  },
  watch: {
    siteList () {
      this.initPage()// 初始化页面
    },
    routeList () {
    }
  },
  created () {
    if (this.siteList.length > 0) {
      this.initPage()// 初始化页面
    }
  }
}
</script>

<style lang="scss" 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;
}
</style>
