<template>
  <!-- #ifdef H5 -->
  <view>
    <!-- ---须知--- -->
    <view>
      <u-popup :show="show" :overlay="false">
        <view class="pop">
          <view class="contentXZ"> <u-parse :content="content"></u-parse> </view><br /><br /><br /><br /><br />
          <view class="bottom-container">
            <u-button @click="handleAgree" text="我已知晓" color="#5298ff" shape="circle"></u-button>
          </view>
        </view>
      </u-popup>
    </view>
    <!-- ---------- -->
    <view v-if="!show" class="content">
      <u--form labelPosition="top" labelWidth="150" :model="form" :rules="rules" ref="form">
        <u-form-item label="商品名称" prop="title" required borderBottom ref="title">
          <u--input v-model="form.title" placeholder="请输入商品名称" border="none"></u--input>
        </u-form-item>
        <u-form-item label="商品描述" prop="content" required borderBottom ref="item1">
          <u--input v-model="form.content" placeholder="请输入" border="none"></u--input>
        </u-form-item>
        <u-form-item label="商品图片" prop="" required borderBottom ref="item1">
          <zj-upload key="cp" @getFiles="getFiles" :fileList="fileList" :count="9" />
        </u-form-item>
        <u-form-item style="" labelPosition="left" required label="商品分类" prop="categoryId" borderBottom ref="item1">
          <view style="flex: 1; display: flex; justify-content: flex-end">
            <view>
              <u-radio-group iconPlacement="left" v-model="form.categoryId" placement="column">
                <u-radio
                  v-for="(v, i) in categoryList"
                  :key="i"
                  :customStyle="{ marginBottom: '8px' }"
                  :label="v.categoryName"
                  :name="v.categoryId"
                >
                </u-radio>
              </u-radio-group>
            </view>
          </view>
        </u-form-item>
        <u-form-item label="所在位置" labelPosition="left" prop="address" required borderBottom ref="item1">
          <view @click="handleDW" class="letText">
            <text v-if="form.address">{{ form.address }}</text>
            <text v-if="!form.address">请选择定位</text>
            <u-icon name="arrow-right"></u-icon>
          </view>
        </u-form-item>
        <u-form-item label="商品价格（含运费） " labelPosition="left" required prop="amount" borderBottom ref="item1">
          <u--input v-model="form.amount" inputAlign="right" placeholder="请输入数字" border="none"></u--input>
        </u-form-item>
        <u-form-item label="上架数量" labelPosition="left" required prop="num" borderBottom ref="item1">
          <u--input v-model="form.num" inputAlign="right" placeholder="请输入" border="none"></u--input>
        </u-form-item>
        <u-form-item label="商品品牌" labelPosition="left" prop="brand" borderBottom ref="item1">
          <u--input
            v-model="form.brand"
            inputAlign="right"
            placeholder="请输入（如格力、美的）"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item label="功率（W）" labelPosition="left" prop="power" borderBottom ref="item1">
          <u--input v-model="form.power" inputAlign="right" placeholder="请输入" border="none"></u--input>
        </u-form-item>
        <u-form-item labelPosition="left" label="能效标识" prop="energy" borderBottom ref="item1">
          <view style="flex: 1; display: flex; justify-content: flex-end">
            <view>
              <u-radio-group v-model="form.energy" placement="column">
                <u-radio
                  v-for="(v, i) in dictList"
                  :key="i"
                  :customStyle="{ marginBottom: '8px' }"
                  :label="v.dictValue"
                  :name="v.dictValue"
                >
                </u-radio>
              </u-radio-group>
            </view>
          </view>
        </u-form-item>
        <u-form-item label="制造日期" labelPosition="left" prop="goodsCreateTime" borderBottom ref="item1">
          <view class="letText" @click="handleTime">
            <text v-if="form.goodsCreateTime">{{
              form.goodsCreateTime.split('-')[0] + '-' + form.goodsCreateTime.split('-')[1] || ''
            }}</text>
            <text v-if="!form.goodsCreateTime">请选择</text>
            <u-icon name="arrow-right"></u-icon>
          </view>
        </u-form-item>
      </u--form>

      <view class="" style="padding: 50rpx 0">
        <u-button :disabled="disabled" @click="submin" text="发布" color="#5298ff" shape="circle"></u-button>
      </view>
    </view>
    <u-datetime-picker
      @cancel="handleCancelTime"
      @confirm="handleConfirmTime"
      :show="showTime"
      v-model="time"
      mode="year-month"
    ></u-datetime-picker>
  </view>
  <!-- #endif -->
  <!-- #ifndef H5 -->
  <view>
    <web-view
      v-if="isShow"
      :src="webViewHref('/pages/issue/index', pam, crossPagePam)"
      @message="crossPage.$listener"
    ></web-view>
  </view>
  <!-- #endif -->
</template>

<script>
import zjUpload from '@/components/zj-upload/index.vue'
export default {
  // #ifndef H5
  data() {
    return {
      isShow: false,
      pam: {},
      init: true
    }
  },
  onLoad(pam) {
    this.pam = pam
  },
  onShow() {
    this.pam = uni.getStorageSync('issuePageParam')
    uni.removeStorageSync('issuePageParam');

    if (this.pam.isLoad || this.init) {
      this.init = false
      delete this.pam.isLoad
      this.isShow = false
      this.$nextTick(() => {
        this.isShow = true
      })
    }

  }
  // #endif


  // #ifdef H5
  components: {
    zjUpload
  },
  data() {
    return {
      disabled: false,
      showTime: false,
      show: false,
      form: {
        title: '',
        content: '',
        categoryName: '',
        categoryId: '',
        lng: '',
        lat: '',
        address: '',
        amount: '',
        num: '',
        brand: '',
        power: '',
        energy: '',
        province: '',
        city: '',
        area: '',
        street: '',
        goodsCreateTime: ''
      },
      rules: {
        title: [{
          required: true,
          message: '必传',
          trigger: ['change', 'blur']
        }],
        content: [{
          required: true,
          message: '必传',
          trigger: ['change', 'blur']
        }],
        categoryId: [{
          required: true,
          message: '必传',
          trigger: ['change', 'blur']
        }],
        address: [{
          required: true,
          message: '必传',
          trigger: ['change', 'blur']
        }],
        amount: [{
            required: true,
            message: '必传',
            trigger: ['change', 'blur']
          },
          {
            pattern: /^\d+\.?\d*$/g,
            // 正则检验前先将值转为字符串
            transform(value) {
              return String(value)
            },
            message: '格式不正确',
            trigger: ['change', 'blur']
          }
        ],
        num: [{
            required: true,
            message: '必传',
            trigger: ['change', 'blur']
          },
          {
            pattern: /^\d+$/g,
            // 正则检验前先将值转为字符串
            transform(value) {
              return String(value)
            },
            message: '格式不正确',
            trigger: ['change', 'blur']
          }
        ]
      },
      time: Number(new Date()),
      categoryList: [],
      dictList: [],
      fileList: [],
      fileurl: [],
      content: '',
      type: '',
      goodsId: ''
    }
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    // this.$refs.form.setRules(this.rules)
  },
  onLoad() {
    this.crossPage.$on("issuePageParam",this.getParams)
    setTimeout(()=>{
      this.show = this.goodsId?false:true
    },300)
  },
  unOnLoad(){
    this.crossPage.$off("issuePageParam",this.getParams)
  },
  onShow() {
    this.getConfig()
    this.getList()
    this.getDictList()
  },
  watch: {
    'form.address': {
      handler(nl) {
        this.$refs.form.clearValidate('address')
      }
    }
  },
  methods: {
    getParams(value){
     this.type = value.type
     this.goodsId = value.goodsId
     if (value.goodsId) {
      this.getDetail()
     }
    },
    //
    getDetail() {
      this.$api
        .postJson('/goods/detail', {
          id: this.goodsId
        })
        .then(res => {
          console.log(res)
          this.form = {
            title: res.data.title,
            content: res.data.content,
            categoryName: res.data.categoryName,
            categoryId: res.data.categoryId,
            lng: res.data.lng,
            lat: res.data.lat,
            address: res.data.address,
            amount: String(res.data.amount),
            num: String(res.data.num),
            brand: res.data.brand,
            power: res.data.power,
            energy: res.data.energy,
            province: res.data.province,
            city: res.data.city,
            area: res.data.area,
            street: res.data.street,
            goodsCreateTime: res.data.goodsCreateTime
          }
          this.fileList = res.data.goodsFiles.map(v => v.imgUrl)
          this.fileurl = []
          res.data.goodsFiles.forEach(v => {
            this.fileurl.push({
              imgUrl: v.imgUrl
            })
          })
        })
        .catch(() => {})
    },
    getConfig() {
      this.$api
        .get('/app/config/detail-by-type', {
          configType: '4'
        })
        .then(res => {
          this.content = res.data.content
        })
        .catch(() => {})
    },
    getFiles(value) {
      this.fileurl = []
      value.forEach(v => {
        this.fileurl.push({
          imgUrl: v
        })
      })
    },
    submin() {
      this.$refs.form
        .validate()
        .then(valid => {
          if (valid) {
            this.disabled = true
            this.form.categoryName =
              this.categoryList.find(v => v.categoryId === this.form.categoryId)?.categoryName ?? ''
            let params = {
              ...this.form,
              goodsFiles: this.fileurl
            }
            this.$toast('正在发布中，请稍后')
            setTimeout(() => {
              let path = '/goods/add'
              if (this.goodsId && this.type == 1) {
                path = '/goods/updateUp'
                params.id = this.goodsId
              }
              if (this.goodsId && this.type == 2) {
                path = '/goods/update'
                params.id = this.goodsId
              }
              this.$api
                .post(path, params)
                .then(res => {
                  this.form = {
                    title: '',
                    content: '',
                    categoryName: '',
                    categoryId: '',
                    lng: '',
                    lat: '',
                    address: '',
                    amount: '',
                    num: '',
                    brand: '',
                    power: '',
                    province: '',
                    city: '',
                    area: '',
                    street: '',
                    energy: '',
                    goodsCreateTime: ''
                  }
                  this.fileList = []
                  this.$refs.form.clearValidate()
                  this.disabled = false
                  this.crossPage.$emit('reloadHomePage');
                  this.$navToPage({
                      url: '/pages/index/index'
                    },
                    'switchTab'
                  )
                })
                .catch(err => {
                  this.disabled = false
                  // this.$toast(err)
                })
            }, 1000)
          }
        })
        .catch(err => {
          this.$toast('缺少必要参数，请检查')
        })

      return
    },
    //获取商品分类数据
    async getList() {
      this.$api
        .get('/goods/category/list')
        .then(res => {
          this.categoryList = res.data
        })
        .catch(() => {})
    },
    //获取能效数据
    async getDictList() {
      this.$api
        .get('/goods/dict', {
          dictCode: '能效'
        })
        .then(res => {
          this.dictList = res.data
        })
        .catch(() => {})
    },
    handleDW() {
      uni.chooseLocation({
        success: res => {
          this.form.lng = res.longitude
          this.form.lat = res.latitude
          this.form.address = res.address
          this.$api
            .post(`/lbs/amap/region/query?lng=${res.longitude}&lat=${res.latitude}`)
            .then(res => {
              console.log(res)
              this.form.province = res.data.provinceName
              this.form.city = res.data.cityName
              this.form.area = res.data.areaName
              this.form.street = res.data.name
            })
            .catch(() => {})
        }
      })
    },
    handleConfirmTime(value) {
      const date = new Date(value.value) // JavaScript的Date对象使用的是毫秒时间戳，因此需要将Unix时间戳乘以1000
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0') // getMonth()返回的月份是从0开始的，因此需要加1，然后使用padStart()添加前导零
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      let res = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      let res2 = `${year}-${month}`
      this.form.goodsCreateTime = res
      this.time = res2
      this.showTime = false
    },
    handleCancelTime() {
      this.showTime = false
    },
    handleTime() {
      this.showTime = true
    },
    handleAgree() {
      this.show = false
    }
  }
  // #endif
}
</script>

<style lang="scss" scoped>
.contentXZ {
  padding: 20px;
}

::v-deep .rig {
  .u-form-item__body {
    justify-content: space-between;
    .u-form-item__body {
      flex: none;
    }
  }
}

.pop {
  overflow: auto;
  //   padding: 0 20rpx;
  /* #ifdef H5 */
  // height: calc(100vh - 44px);
  height: 100vh;
  /* #endif */
  /* #ifndef H5 */
  height: 100vh;
  /* #endif */
}

.content {
  padding: 0 40rpx;
  margin: 20rpx 0;
  //   height: calc(100vh - 44px);
  background-color: #fff;
}

.bottom-container {
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #f1f1f1;
  padding: 18px 0;
}

.letText {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

::v-deep .u-radio-label--undefined {
  justify-content: flex-end;
}
</style>
