<template>
  <div>
    <xy-dialog :is-show.sync="isShow" type="form" :title="type === 'add' ? '新增广告' : '编辑广告'" :form="form" :rules="rules"
      ref="dialog" @submit="submit">
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>活动名称：
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写活动名称" v-model="form.name" style="width: 300px;" />
          </div>
        </div>
      </template>
      <template v-slot:type>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>类型：
          </div>
          <div class="xy-table-item-content">
            <el-select clearable placeholder="请选择类型" v-model="form.type" style="width: 300px;">
              <el-option v-for="item in types" :value="item.value" :key="item.value" :label="item.label"></el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:system>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>发布系统：
          </div>
          <div class="xy-table-item-content">
            <el-select clearable placeholder="请选择发布系统" v-model="form.system" style="width: 300px;">
              <el-option v-for="item in systems" :key="item.value" :value="item.value" :label="item.label"></el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:to>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>跳转方向：
          </div>
          <div class="xy-table-item-content">
            <el-input clearable :placeholder="toType === 1 ? '请填写跳转方向' : '跳转商品选择'" v-model="form.to"
              style="width: 300px;" :readonly="toType === 2 ? true :false">
              <el-select v-model="toType" slot="prepend" placeholder="方式选择" style="width: 110px;"
                @change="showToProductSelect">
                <el-option label="指定地址" :value="1"></el-option>
                <el-option label="指定商品" :value="2"></el-option>
              </el-select>
            </el-input>
          </div>
        </div>
      </template>
      <template v-slot:state>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>状态：
          </div>
          <div class="xy-table-item-content">
            <el-select clearable placeholder="请选择状态" v-model="form.state" style="width: 300px;">
              <el-option v-for="item in states" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:sort>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>排序：
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写排序" v-model="form.sort" style="width: 300px;" />
          </div>
        </div>
      </template>
      <template v-slot:effectDate>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>有效期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker :editable="false" type="daterange" append-to-body clearable placeholder="请选择有效期"
              v-model="form.effectDate" style="width: 300px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
          </div>
        </div>
      </template>
      <template v-slot:img>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>图片：
          </div>
          <div class="xy-table-item-content">
            <div v-if="form.img" style="position: relative;">
              <img :src="form.img" class="avatar">
              <Button shape="circle" icon="md-close" type="error" size="small" class="img__delete"
                @click="form.img = ''"></Button>
            </div>
            <el-upload v-else accept="picture" :limit="1" class="avatar-uploader" list-type="picture-card"
              :action="action" :show-file-list="true" :on-error="uploadFail" :on-success="uploadSuccess"
              :before-upload="uploadBefore">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div style="font-size: 10px;white-space: nowrap;word-break: keep-all">建议尺寸： 690*300</div>
          </div>
        </div>
      </template>
    </xy-dialog>

    <!--    跳转商品选择-->
    <Modal v-model="isShowProductSelect" title="跳转商品选择">
      <Input clearable v-model="nameKeywords" search enter-button placeholder="商品搜索.." @on-search="getProducts"
        style="margin-bottom: 10px;" />
      <Table highlight-row ref="currentRowTable" :columns="productColumns" :data="productData"
        @on-current-change="productSelect" />
      <Page :current="productPageIndex" :total="productTotal" simple
        style="padding-top: 14px;display: flex;justify-content: center;" @on-change="productPageChange" />
    </Modal>
  </div>
</template>

<script>
  import {
    store,
    show,
    update
  } from '@/api/ad'
  import {
    getparameter
  } from '@/api/system/dictionary'
  import {
    index
  } from '@/api/product'
  import {
    Message
  } from 'element-ui'
  import axios from 'axios'
  export default {
    props: {
      systems: {
        type: Array
      }
    },
    data() {
      return {
        id: '',
        type: 'add',
        isShow: false,
        action: `${process.env.VUE_APP_BASE_API}api/admin/upload-file`,

        types: [{
          label: '首页轮播图',
          value: 0
        }, {
          label: '商品轮播图',
          value: 1
        }],
        states: [{
            label: '禁用',
            value: 0
          },
          {
            label: '启动',
            value: 1
          }
        ],

        form: {
          name: '',
          type: '',
          system: '',
          to: '',
          state: '',
          sort: '',
          effectDate: [],
          img: ''
        },
        rules: {
          name: [{
            required: true,
            message: "请填写活动名称"
          }],
          type: [{
            required: true,
            message: "请选择类型"
          }],
          system: [{
            required: true,
            message: "请选择发布系统"
          }],
          to: [{
            required: true,
            message: "请填写跳转方向"
          }],
          state: [{
            required: true,
            message: "请选择状态"
          }],
          sort: [{
              required: true,
              message: "请填写排序"
            },
            {
              pattern: /^[0-9]+/,
              message: "手机号格式错误"
            }
          ],
          effectDate: [{
            required: true,
            message: "请选择日期"
          }],
          img: [{
            required: true,
            message: "请选择图片"
          }]
        },


        //跳转选择
        toType: '', //跳转输入类型
        isShowProductSelect: false,
        productTotal: 0,
        productPageIndex: 1,
        nameKeywords: '',
        productColumns: [{
            title: '编号',
            key: 'id',
            width: 80
          },
          {
            title: '商品名称',
            key: 'name'
          },
          {
            title: '单价',
            key: 'price',
            width: 120,
            align: 'right'
          }
        ],
        productData: [],
      }
    },
    methods: {

      async getToUrl() {
        let res = await getparameter({
          number: 'toUrl'
        })
        this.toUrls = res.detail.map(item => {
          return {
            label: item.value,
            value: item.id
          }
        })
      },

      //上传
      uploadFail(err) {
        console.log(err)
      },
      uploadSuccess(response) {
        console.log(response)
        this.form.img = response.url
      },
      uploadBefore(file) {
        console.log(file)
        if ((file.size / 1000) > 2024) {
          Message({
            type: 'warning',
            message: '上传图片大小超过2M！'
          })
          return false
        }
      },

      submit() {
        console.log(this.form)

        if (this.type === 'add') {
          store({
            pic: this.form.img,
            name: this.form.name,
            action: this.form.to,
            origin_system: this.form.system,
            type: this.form.type,
            sort: this.form.sort,
            state: this.form.state,
            valid_time_begin: this.form.effectDate[0],
            valid_time_over: this.form.effectDate[1]
          }).then(res => {
            Message({
              type: 'success',
              message: '添加广告成功'
            })
            this.isShow = false
            this.$emit('refresh')
            this.form = {
              name: '',
              type: '',
              system: '',
              to: '',
              state: '',
              sort: '',
              effectDate: [],
              img: ''
            }
            this.id = ''
          })
          return
        }
        if (this.type === 'editor') {
          update({
            id: this.id,
            pic: this.form.img,
            name: this.form.name,
            action: this.form.to,
            origin_system: this.form.system,
            type: this.form.type,
            sort: this.form.sort,
            state: this.form.state,
            valid_time_begin: this.form.effectDate[0],
            valid_time_over: this.form.effectDate[1]
          }).then(res => {
            Message({
              type: 'success',
              message: '编辑广告成功'
            })
            this.isShow = false
            this.$emit('refresh')
            this.form = {
              name: '',
              type: '',
              system: '',
              to: '',
              state: '',
              sort: '',
              effectDate: [],
              img: ''
            }
            this.id = ''
          })
          return
        }
      },

      //获取详情
      async getDetailAd() {
        const res = await show({
          id: this.id
        })
        this.form.name = res?.name
        this.form.state = res?.state
        this.form.system = res?.origin_system
        this.form.to = res?.action
        this.form.sort = res?.sort
        this.form.type = res?.type
        this.form.img = res?.pic
        this.form.effectDate = [res?.valid_time_begin, res?.valid_time_over]
      },


      //跳转指定商品
      productPageChange(e) {
        this.productPageIndex = e
        this.getProducts()
      },
      showToProductSelect() {
        if (this.toType == 2) {
          this.getProducts()
          this.isShowProductSelect = true
          this.toType = ''
        }
      },
      async getProducts() {
        const res = await index({
          rows: 5,
          page: this.productPageIndex,
          name: this.nameKeywords
        })
        this.productData = res.rows
        this.productTotal = res.total
      },
      productSelect(row) {
        this.form.to = `/packages/packageBuy/pages/shopDetail/shopDetail?id=${row.id}`
      }
    },
    watch: {
      isShow(val) {
        if (val) {

          if (this.type === 'editor') {
            this.getDetailAd()
          }
        } else {
          this.$refs['dialog'].reset()
          this.id = ''
          this.toType = ''
        }
      }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    width: 110px;
    height: 110px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }

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

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

  .avatar {
    width: 110px;
    display: block;
    border-radius: 6px;
  }

  .img__delete {
    transform: scale(0.7, 0.7);

    position: absolute;
    top: 1px;
    left: 2%;
  }
</style>
