<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-card id="box-card-form-1">
          <div>
            <el-form
              ref="form"
              label-width="100px"
              :model="form"
              :rules="rules"
              size="medium"
            >
              <el-form-item
                :label="__('商品是否需要审核')"
                label-width="200px"
                prop="product_verify_flag"
              >
                <el-radio-group
                  v-model="form.product_verify_flag"
                  size="medium"
                >
                  <el-radio
                    v-for="(item, index) in product_verify_flagOptions"
                    :key="index"
                    :disabled="item.disabled"
                    :label="__(item.value)"
                  >
                    {{ __(item.label) }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                :label="__('未支付订单取消时长/小时')"
                label-width="200px"
                prop="order_autocancel_time"
              >
                <el-input
                  v-model="form.order_autocancel_time"
                  clearable
                  :placeholder="__('请输入未支付订单取消时长/小时')"
                  :style="{ width: '100%' }"
                />
              </el-form-item>
              <el-form-item
                :label="__('商品是否显示订单剩余时间')"
                label-width="200px"
                prop="show_cancel_time"
              >
                <el-radio-group v-model="form.show_cancel_time" size="medium">
                  <el-radio
                    v-for="(item, index) in show_cancel_timeOptions"
                    :key="index"
                    :disabled="item.disabled"
                    :label="__(item.value)"
                  >
                    {{ __(item.label) }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                :label="__('订单自动确认收货时长/天')"
                label-width="200px"
                prop="order_autofinish_time"
              >
                <el-input
                  v-model="form.order_autofinish_time"
                  clearable
                  :placeholder="__('请输入订单自动确认收货时长/天')"
                  :style="{ width: '100%' }"
                />
              </el-form-item>
              <el-form-item
                :label="__('默认配送区域')"
                label-width="200px"
                prop="default_shipping_district"
              >
                <Area v-model="address" :clearable="true" width="350" />
              </el-form-item>

              <el-form-item
                :label="__('是否显示销量')"
                label-width="200px"
                prop="product_salenum_flag"
              >
                <el-radio-group
                  v-model="form.product_salenum_flag"
                  size="medium"
                >
                  <el-radio
                    v-for="(item, index) in product_salenum_flagOptions"
                    :key="index"
                    :disabled="item.disabled"
                    :label="__(item.value)"
                  >
                    {{ __(item.label) }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item
                :label="__('虚拟销量')"
                label-width="200px"
                prop="product_virtual_salenum"
              >
                <el-input
                  v-model="form.product_virtual_salenum"
                  clearable
                  :placeholder="__('请输入虚拟销量')"
                  :style="{ width: '100%' }"
                />
              </el-form-item>

              <el-form-item
                :label="__('是否显示自提')"
                label-width="200px"
                prop="product_ziti_flag"
              >
                <el-radio-group v-model="form.product_ziti_flag" size="medium">
                  <el-radio
                    v-for="(item, index) in product_ziti_flagOptions"
                    :key="index"
                    :disabled="item.disabled"
                    :label="__(item.value)"
                  >
                    {{ __(item.label) }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                :label="__('用户单日可参与帮砍次数')"
                label-width="200px"
                prop="user_cutprice_num"
              >
                <el-input-number
                  v-model="form.user_cutprice_num"
                  :max="100"
                  :min="1"
                />
              </el-form-item>
              <el-form-item
                :label="__('砍价订单有效期时长/天')"
                label-width="200px"
                prop="order_cutprice_time"
              >
                <el-input
                  v-model="form.order_cutprice_time"
                  clearable
                  :placeholder="__('砍价订单有效期时长/天')"
                  :style="{ width: '100%' }"
                />
              </el-form-item>
              <el-form-item
                :label="__('库存预警')"
                label-width="200px"
                prop="product_inventory_warning"
              >
                <el-input
                  v-model="form.product_inventory_warning"
                  clearable
                  :placeholder="__('库存预警')"
                  :style="{ width: '100%' }"
                />
              </el-form-item>
            </el-form>
          </div>
          <div>
            <el-button
              class="form-sub-btn"
              icon="el-icon-s-tools"
              type="primary"
              @click="handleEdit"
            >
              {{ __('修改') }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div>
          <el-card class="box-card">
            <div>
              <el-form
                ref="promoteForm"
                label-width="100px"
                :model="promoteForm"
                size="medium"
              >
                <el-form-item
                  :label="__('平台推广海报')"
                  label-width="150px"
                  prop="plantform_poster_bg"
                >
                  <upload
                    height="267px"
                    :image="promoteForm.plantform_poster_bg"
                    width="150px"
                    @upImage="
                      (image) => {
                        promoteForm.plantform_poster_bg = image
                      }
                    "
                  />
                  <div class="image_font">750 * 1335, 移动端使用</div>
                </el-form-item>
                <el-form-item
                  :label="__('商品推广海报')"
                  label-width="150px"
                  prop="product_poster_bg"
                >
                  <upload
                    height="267px"
                    :image="promoteForm.product_poster_bg"
                    width="150px"
                    @upImage="
                      (image) => {
                        promoteForm.product_poster_bg = image
                      }
                    "
                  />
                  <div class="image_font">750 * 1335, 移动端使用</div>
                </el-form-item>
              </el-form>
            </div>
            <div>
              <el-button
                class="form-sub-btn"
                icon="el-icon-s-tools"
                type="primary"
                @click="promoteEdit"
              >
                {{ __('修改') }}
              </el-button>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div>
          <el-card class="box-card">
            <div>
              <el-button
                class="form-sub-btn"
                icon="el-icon-s-tools"
                :loading="buttonLoading"
                type="danger"
                @click="cleanCache"
              >
                {{ buttonLoading ? `请等待 ${countdown} 秒` : __('清理缓存') }}
              </el-button>
              <span>
                {{
                  __(
                    '谨慎操作：此缓存接口为系统性能提供重要支持，请确保在清理前已确认无误，以避免不必要的数据丢失和性能下降'
                  )
                }}
              </span>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { getList, doEdit, cleanCache } from '@/api/base/config'
  import Area from '@/components/VabArea/area'
  import Upload from '@/components/upload'

  export default {
    name: 'Index',
    components: { Upload, Area },
    data() {
      return {
        address: {
          province: {},
          city: {},
          district: {},
        },
        buttonLoading: false,
        countdown: 10,
        form: {
          product_verify_flag: null,
          order_autocancel_time: null,
          order_autofinish_time: null,
          product_ziti_flag: null,
          product_virtual_salenum: null,
          user_cutprice_num: null,
          order_cutprice_time: null,
          product_inventory_warning: null,
          product_salenum_flag: null,
        },
        promoteForm: {
          plantform_poster_bg: null,
          product_poster_bg: null,
        },
        rules: {
          product_verify_flag: [
            {
              required: true,
              message: this.__('商品是否需要审核不能为空'),
              trigger: 'change',
            },
          ],
          order_autocancel_time: [
            {
              required: true,
              message: this.__('请输入未支付订单取消时长/小时'),
              trigger: 'blur',
            },
          ],
          show_cancel_time: [
            {
              required: true,
              message: this.__('商品是否显示订单剩余时间不能为空'),
              trigger: 'change',
            },
          ],
        },
        show_cancel_timeOptions: [
          {
            label: this.__('是'),
            value: '1',
          },
          {
            label: this.__('否'),
            value: '0',
          },
        ],
        product_salenum_flagOptions: [
          {
            label: this.__('是'),
            value: '1',
          },
          {
            label: this.__('否'),
            value: '0',
          },
        ],
        product_ziti_flagOptions: [
          {
            label: this.__('是'),
            value: '1',
          },
          {
            label: this.__('否'),
            value: '0',
          },
        ],
        product_verify_flagOptions: [
          {
            label: this.__('是'),
            value: '1',
          },
          {
            label: this.__('否'),
            value: '0',
          },
        ],
        default_shipping_districtOptions: [],
        default_shipping_districtProps: {
          multiple: false,
          label: 'label',
          value: 'value',
          children: 'children',
        },
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      __,
      async fetchData() {
        const { data } = await getList()
        this.form = {
          product_verify_flag: data.product_verify_flag,
          order_autocancel_time: data.order_autocancel_time,
          order_autofinish_time: data.order_autofinish_time,
          show_cancel_time: data.show_cancel_time,
          product_salenum_flag: data.product_salenum_flag,
          product_virtual_salenum: data.product_virtual_salenum
            ? data.product_virtual_salenum
            : 0,
          user_cutprice_num: data.user_cutprice_num,
          order_cutprice_time: data.order_cutprice_time,
          product_inventory_warning: data.product_inventory_warning,
          product_ziti_flag: data.product_ziti_flag,
        }
        this.promoteForm = {
          plantform_poster_bg: data.plantform_poster_bg,
          product_poster_bg: data.product_poster_bg,
        }
        this.setAddress(
          data.default_shipping_district,
          data.default_shipping_district_ids
        )
      },
      setAddress(default_shipping_district, default_shipping_district_ids) {
        if (default_shipping_district && default_shipping_district_ids) {
          let names = default_shipping_district.split(',')
          let codes = default_shipping_district_ids.split(',')
          if (codes[0] && names[0]) {
            this.address.province = { code: codes[0], name: names[0] }
          }
          if (codes[1] && names[1]) {
            this.address.city = { code: codes[1], name: names[1] }
          }
          if (codes[2] && names[2]) {
            this.address.district = { code: codes[2], name: names[2] }
          }
        }
      },
      addAddressToForm() {
        let address = this.address
        let default_shipping_district = ''
        let default_shipping_district_ids = ''

        let province = address.province
        if (province.name && province.code) {
          default_shipping_district += province.name
          default_shipping_district_ids += province.code

          let city = address.city
          if (city.name && city.code) {
            default_shipping_district += '/' + city.name
            default_shipping_district_ids += '/' + city.code

            let district = address.district
            if (district.name && district.code) {
              default_shipping_district += '/' + district.name
              default_shipping_district_ids += '/' + district.code
            }
          }
          this.form.default_shipping_district = default_shipping_district
          this.form.default_shipping_district_ids =
            default_shipping_district_ids
        }
      },
      handleEdit() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.addAddressToForm()
            const { msg, status } = await doEdit({
              param: JSON.stringify(this.form),
            })

            if (status == 200) {
              this.$baseMessage(msg, 'success')
            } else {
              this.$baseMessage(msg, 'error')
            }
          } else {
            return false
          }
        })
      },
      promoteEdit() {
        this.$refs['promoteForm'].validate(async (valid) => {
          if (valid) {
            const { msg, status } = await doEdit({
              param: JSON.stringify(this.promoteForm),
            })

            if (status == 200) {
              this.$baseMessage(msg, 'success')
            } else {
              this.$baseMessage(msg, 'error')
            }
          } else {
            return false
          }
        })
      },
      async cleanCache() {
        // 如果按钮已禁用，直接返回
        if (this.buttonLoading) {
          return
        }
        this.buttonLoading = true
        // 启动倒计时
        this.startCountdown()
        const { msg, status } = await cleanCache()
        if (200 == status) {
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
      },
      startCountdown() {
        const timer = setInterval(() => {
          this.countdown--
          if (this.countdown === 0) {
            clearInterval(timer)
            this.buttonLoading = false // 倒计时结束后恢复按钮可点击
            this.countdown = 10 // 重置倒计时
          }
        }, 1000)
      },
    },
  }
</script>
<style>
  #box-card-form-1 {
    overflow: unset;
  }
  .image_font {
    color: #979898;
    font-size: 14px;
  }
</style>
