<template>
  <el-dialog
    width="1200px"
    title="创建商品"
    :before-close="handleClose"
    :visible.sync="visible"
  >
    <el-form
      inline
      :model="form"
      ref="form"
      label-width="180px">
      <div class="dialog-info">
        <div class="block-title">
          基本属性
        </div>
        <el-form-item
          verify
          prop="product_name"
          label="商品名称"
        >
          <el-input v-model="form.product_name"></el-input>
        </el-form-item>
        <el-form-item
          verify
          prop="out_id"
          label="商家商品ID"
        >
          <el-input
            v-model="form.out_id"
            disabled></el-input>
        </el-form-item>
        <el-form-item
          verify
          prop="poiId"
          label="商家ID"
        >
          <el-input
            v-model="form.poiId"
            @blur="getCategory();propsConfig.poi_id=form.poiId"></el-input>
        </el-form-item>
        <el-form-item
          verify
          prop="poi_ids[0]"
          label="门店ID"
        >
          <el-input
            v-model="form.poi_ids[0]"
          ></el-input>
        </el-form-item>
        <el-form-item
          verify
          prop="category_leaf_id"
          label="商品类目"
        >
          <el-cascader
            placeholder="请先输入商家ID"
            :options="categoryList"
            :props="propsConfig"
            v-model="form.category_leaf_id"></el-cascader>
        </el-form-item>
        <el-form-item
          verify
          label="凭证发送方式"
          prop="attr_key_value_map.code_sending_info">
          <el-select
            multiple
            v-model="form.attr_key_value_map.code_sending_info">
            <el-option
              :value="1"
              label="身份证"></el-option>
            <el-option
              :value="2"
              label="券码"></el-option>
            <el-option
              :value="3"
              label="纸质凭证"></el-option>
            <el-option
              :value="4"
              label="电子凭证"></el-option>
            <el-option
              :value="5"
              label="证件"></el-option>
            <el-option
              :value="6"
              label="实物票"></el-option>
            <el-option
              :value="7"
              label="纸质凭证或电子凭证"></el-option>
            <el-option
              :value="8"
              label="纸质凭证及电子凭证"></el-option>
            <el-option
              :value="9"
              label="证件及电子凭证"></el-option>
            <el-option
              :value="10"
              label="证件及纸质凭证"></el-option>
            <el-option
              :value="11"
              label="预留姓名"></el-option>
            <el-option
              :value="12"
              label="手机号"></el-option>
            <el-option
              :value="14"
              label="手机号及姓名"></el-option>
            <el-option
              :value="15"
              label="手机号及电子凭证"></el-option>
            <el-option
              :value="16"
              label="证件或电子凭证"></el-option>
            <el-option
              :value="17"
              label="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          verify
          label="退款规则"
          prop="attr_key_value_map.refund_rule">
          <el-select
            v-model="form.attr_key_value_map.refund_rule">
            <el-option
              value="2"
              label="不可退"></el-option>
            <el-option
              value="5"
              label="未使用时随时可退、过期自动退（不支持部分退）"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          verify
          label="票种类型"
          prop="attr_key_value_map.ticket_classification">
          <el-select
            v-model="form.attr_key_value_map.ticket_classification">
            <el-option
              value="1"
              label="门票"></el-option>
            <el-option
              value="2"
              label="门票套餐"></el-option>
            <el-option
              value="3"
              label="项目服务"></el-option>
            <el-option
              value="4"
              label="景区联票"></el-option>
            <el-option
              value="5"
              label="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          verify
          label="是否需要换票"
          prop="attr_key_value_map.need_ticket.val_data">
          <el-select
            v-model="form.attr_key_value_map.need_ticket.val_data">
            <el-option
              :value="1"
              label="不需要"></el-option>
            <el-option
              :value="2"
              label="需要"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.attr_key_value_map.need_ticket.val_data===2"
          prop="attr_key_value_map.need_ticket.data_desc"
          label="换票说明"
        >
          <el-input
            v-model="form.attr_key_value_map.need_ticket.data_desc"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="visible"
          verify
          prop="img_urls"
          label="商品头图"
          style="width:100%"
        >
          <el-upload
            :disabled="!form.poiId"
            list-type="picture-card"
            :action="uploadUrl"
            :auto-upload="true"
            :on-change="handleChange"
            :on-remove="handleChange"
            :file-list="fileList1"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          v-if="visible"
          prop="detail_image_url"
          label="图文详情"
          style="width:100%"
        >
          <el-upload
            :disabled="!form.poiId"
            list-type="picture-card"
            :action="uploadUrl"
            :auto-upload="true"
            :on-change="handleChange2"
            :on-remove="handleChange2"
            :file-list="fileList2"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <div class="block-title">
          sku信息
        </div>
        <el-form-item
          prop="ticket_specifications[0].sku_name"
          label="sku名称"
        >
          <el-input v-model="form.ticket_specifications[0].sku_name"></el-input>
        </el-form-item>
        <el-form-item
          v-if="form.ticket_specifications[0].sku_id"
          prop="ticket_specifications[0].sku_id"
          label="快手skuld"
        >
          <el-input
            v-model="form.ticket_specifications[0].sku_id"
            disabled></el-input>
        </el-form-item>
        <el-form-item
          prop="ticket_specifications[0].attr_key_value_map.traveler_reserved_info.val_data"
          label="游玩人留资"
        >
          <el-select
            v-model="form.ticket_specifications[0].attr_key_value_map.traveler_reserved_info.val_data">
            <el-option
              :value="1"
              label="无需填写"></el-option>
            <el-option
              :value="2"
              label="一单需要一个"></el-option>
            <el-option
              :value="3"
              label="按游玩人数填写"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.ticket_specifications[0].attr_key_value_map.traveler_reserved_info.val_data==2||form.ticket_specifications[0].attr_key_value_map.traveler_reserved_info.val_data==3"
          prop="ticket_specifications[0].attr_key_value_map.traveler_reserved_info.data_params"
          label="游玩人留资字段"
        >
          <el-select
            multiple
            v-model="form.ticket_specifications[0].attr_key_value_map.traveler_reserved_info.data_params">
            <el-option
              :value="1"
              label="姓名"></el-option>
            <el-option
              :value="2"
              label="手机号"></el-option>
            <el-option
              :value="3"
              label="身份证"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          verify
          prop="ticket_specifications[0].attr_key_value_map.contact_info"
          label="联系人信息"
        >
          <el-select
            multiple
            v-model="form.ticket_specifications[0].attr_key_value_map.contact_info">
            <el-option
              :value="1"
              label="姓名"></el-option>
            <el-option
              :value="2"
              label="手机号"></el-option>
            <el-option
              :value="3"
              label="身份证"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          verify
          prop="ticket_specifications[0].attr_key_value_map.buy_limit_type.val_data"
          label="是否限购"
        >
          <el-select
            v-model="form.ticket_specifications[0].attr_key_value_map.buy_limit_type.val_data">
            <el-option
              :value="1"
              label="不限购"></el-option>
            <el-option
              :value="2"
              label="限购"></el-option>
          </el-select>
        </el-form-item>
        <div
          style="width:100%"
          v-if="form.ticket_specifications[0].attr_key_value_map.buy_limit_type.val_data===2">
          <el-button
            @click="handleAdd2"
            style="margin:5px 0">添加限购类型</el-button>
          <el-table :data="form.ticket_specifications[0].attr_key_value_map.buy_limit_type.buy_limit_list">
            <el-table-column
              prop="type"
              label="限购类型">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.type">
                  <el-option
                    :value="2"
                    label="单订单限购"></el-option>
                  <el-option
                    :value="6"
                    label="每人每日限购"></el-option>
                  <el-option
                    :value="7"
                    label="手机号限购"></el-option>
                  <el-option
                    :value="10"
                    label="单账号限购"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="num"
              label="限购数量">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.num"
                  :min="0"
                  :precision="0" />
              </template>
            </el-table-column>
            <el-table-column
              prop="action"
              label="操作"
              width="100">
              <template slot-scope="scope">
                <el-button @click="handleDelete2(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="width:100%">
          <el-button
            @click="handleAdd"
            style="margin:5px 0">添加日历计划</el-button>
          <el-table :data="form.ticket_specifications[0].calendars">
            <el-table-column
              prop="origin_amount"
              label="原价(单位:分)">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.origin_amount"
                  :min="0"
                  :precision="0" />
              </template>
            </el-table-column>
            <el-table-column
              prop="actual_amount"
              label="实际售价(单位:分)">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.actual_amount"
                  :min="0"
                  :precision="0" />
              </template>
            </el-table-column>
            <el-table-column
              prop="stock_qty"
              label="库存">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.stock_qty"
                  :min="0"
                  :precision="0" />
              </template>
            </el-table-column>
            <el-table-column
              prop="value_list"
              label="日期范围"
              width="300"
            >
              <template slot-scope="scope">
                <el-date-picker
                  style="width:270px"
                  v-model="scope.row.value_list"
                  value-format="yyyyMMdd"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column
              prop="action"
              label="操作"
              width="100">
              <template slot-scope="scope">
                <el-button @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="dialog-btn-wrap">
        <el-button
          @click="submit"
          type="primary">同步</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import { ksSaveProduct, ksCategoryQuery, picUpload } from '@/api/otaTicketSale'
import moment from 'moment'
export default {
  data () {
    return {
      visible: false,
      uploadUrl: '',
      inputVisible: false,
      inputValue: '',
      categoryId: 0,
      categoryList: [],
      form: {
        attr_key_value_map: {
          code_sending_info: [],
          refund_rule: '5',
          ticket_classification: '1',
          need_ticket: {
            val_data: 1,
            data_desc: ''
          }
        },
        category_leaf_id: '',
        detail_image_urls: [],
        img_urls: [],
        img: '',
        out_id: '',
        poiId: '',
        poi_ids: [],
        product_name: '',
        ticket_specifications: [{
          attr_key_value_map: {
            traveler_reserved_info: {
              val_data: 1,
              data_params: []
            },
            pre_order_time: 0,
            buy_limit_type: {
              val_data: 1,
              buy_limit_list: []
            },
            contact_info: [],
            crowds: [
              {
                crowd_num: 1, // 人群数量
                crowd_type: 10, // 人群类型  1儿童 2成人 3老人 4学生 6优待人群 10不限 20其他
                age_condition: { //
                  lower_bound: 1, // 下限
                  lower_bound_type: 1, // 是否包含 1：包含 2:不含
                  upper_bound: 100, // 上限
                  upper_bound_type: 1 // 是否包含 1：包含 2:不含
                },
                height_condition: {
                  lower_bound: 1,
                  lower_bound_type: 1,
                  upper_bound: 240,
                  upper_bound_type: 1
                },
                op_type: 1, // 年龄和身高关系 1：and  2：or
                note: '人群特殊说明', // 人群特殊说明
                is_check: 2 // 是否校验 1：校验：2：不校验   本期默认传2
              }
            ]
          },
          calendars: [],
          out_sku_id: '',
          sale_property: [],
          sku_id: '',
          sku_name: ''
        }]
      },
      product_id: 0,
      propsConfig: {
        poi_id: 0,
        label: 'name',
        value: 'category_id',
        checkStrictly: true,
        lazy: true,
        async lazyLoad (node, resolve) {
          if (!this.poi_id) return
          const {extraInfo} = await ksCategoryQuery(this.poi_id, node.value)
          if (extraInfo && extraInfo.data && extraInfo.data.category_infos && extraInfo.data.category_infos.length) {
            extraInfo.data.category_infos.forEach(v => {
              v.leaf = (v.level === 3)
            })
            resolve(extraInfo.data.category_infos)
          } else {
            resolve([])
          }
        }
      },
      fileList1: [],
      fileList2: [],
      calendars_value_list: []
    }
  },
  methods: {
    show (data) {
      this.visible = true
      this.form.out_id = data.id
      this.form.ticket_specifications[0].out_sku_id = data.id
      let startDate = moment().format('YYYY-MM-DD HH:mm:ss')
      let endDate = moment().add(179, 'days').format('YYYY-MM-DD HH:mm:ss')
      startDate = startDate.split(' ')[0].replaceAll('-', '')
      endDate = endDate.split(' ')[0].replaceAll('-', '')
      this.calendars_value_list = [startDate, endDate]
      this.categoryId = 0
      this.categoryList = []
      this.form.product_name = data.ticketTypeName
      if (data.ksProductId) {
        this.product_id = data.ksProductId
      } else {
        this.product_id = 0
      }
      if (data.ks_sku_id) {
        this.form.ticket_specifications[0].sku_id = data.ks_sku_id
      } else {
        this.form.ticket_specifications[0].sku_id = ''
      }
    },
    handleClose () {
      this.visible = false
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))
          params.category_leaf_id = params.category_leaf_id[params.category_leaf_id.length - 1]
          params.attr_key_value_map.code_sending_info = JSON.stringify(params.attr_key_value_map.code_sending_info)
          params.attr_key_value_map.need_ticket = JSON.stringify(params.attr_key_value_map.need_ticket)
          params.ticket_specifications[0].attr_key_value_map.traveler_reserved_info = JSON.stringify(params.ticket_specifications[0].attr_key_value_map.traveler_reserved_info)
          params.ticket_specifications[0].attr_key_value_map.buy_limit_type = JSON.stringify(params.ticket_specifications[0].attr_key_value_map.buy_limit_type)
          params.ticket_specifications[0].attr_key_value_map.contact_info = JSON.stringify(params.ticket_specifications[0].attr_key_value_map.contact_info)
          params.ticket_specifications[0].attr_key_value_map.crowds = JSON.stringify(params.ticket_specifications[0].attr_key_value_map.crowds)
          if (this.product_id) {
            params.product_id = this.product_id
          }
          ksSaveProduct(params, this.form.poiId).then(res => {
            if (res.extraInfo.data.error_code) {
              this.$message.error(res.extraInfo.data.description)
            } else {
              this.$message.success('同步成功')
              this.handleClose()
              this.$emit('update')
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleChange (file, fileList) {
      let arr = []
      fileList.forEach(v => {
        if (v.response && v.response.link) {
          arr.push({
            image_id: v.response.link,
            url: v.response.link
          })
          picUpload(this.form.poiId, arr).then(res => {
            if (res.extraInfo.data && res.extraInfo.data.success_list && res.extraInfo.data.success_list.length) {
              this.form.img_urls = res.extraInfo.data.success_list.map(v => v.pic_url)
            } else {
              this.$message.error('上传失败')
              this.fileList1 = []
            }
          }).catch(e => {
            this.$message.error('上传失败')
            this.fileList1 = []
          })
        }
      })
    },
    handleChange2 (file, fileList) {
      let arr = []
      fileList.forEach(v => {
        if (v.response && v.response.link) {
          arr.push({
            image_id: v.response.link,
            url: v.response.link
          })
        }
      })
      picUpload(this.form.poiId, arr).then(res => {
        if (res.extraInfo.data && res.extraInfo.data.success_list && res.extraInfo.data.success_list.length) {
          this.form.detail_image_urls = res.extraInfo.data.success_list.map(v => {
            return {image_url: v.pic_url, desc: ''}
          })
        } else {
          this.$message.error('上传失败')
          this.fileList2 = []
        }
      }).catch(e => {
        this.$message.error('上传失败')
        this.fileList2 = []
      })
    },
    handleAvatarSuccess (res, file) {
      const isJPG = res.raw.type === 'image/jpeg' || res.raw.type === 'image/png'
      // const isLt2M = res.raw.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('图片只能是 JPG或PNG 格式!')
        return
      }
      // if (!isLt2M) {
      //   this.$message.error('图片大小不能超过 2MB!')
      //   return
      // }
      let reader = new FileReader()
      reader.readAsDataURL(res.raw)
      reader.onload = (e) => {
        this.form.img = e.target.result.split(',')[1]
        picUpload(this.form.poiId, {third_img_byte: this.form.img}).then(res => {
          console.log(res)
        })
      }
    },
    handleAdd () {
      this.form.ticket_specifications[0].calendars.push(
        {
          actual_amount: 0,
          calendar_type: 1,
          exclude_date_list: [],
          origin_amount: 0,
          status: 1,
          stock_qty: 0,
          value_list: this.calendars_value_list || []
        }
      )
    },
    handleDelete (index) {
      this.form.ticket_specifications[0].calendars.splice(index, 1)
    },
    handleAdd2 () {
      this.form.ticket_specifications[0].attr_key_value_map.buy_limit_type.buy_limit_list.push(
        {
          type: 2,
          num: 100
        }
      )
    },
    handleDelete2 (index) {
      this.form.ticket_specifications[0].attr_key_value_map.buy_limit_type.buy_limit_list.splice(index, 1)
    },
    handleClose1 (tag) {
      this.form.poi_ids.splice(this.form.poi_ids.indexOf(tag), 1)
    },
    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () {
      let inputValue = this.inputValue
      if (inputValue) {
        this.form.poi_ids.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    async getCategory () {
      if (!this.form.poiId) return
      const {extraInfo} = await ksCategoryQuery(this.form.poiId, this.categoryId)
      if (extraInfo && extraInfo.data && extraInfo.data.category_infos && extraInfo.data.category_infos.length) {
        this.categoryList = extraInfo.data.category_infos
      } else {
        this.categoryList = []
        this.$message.error('未查到符合的数据')
      }
    }
  },
  created () {
    if (window.config && window.config.uploadUrl) {
      this.uploadUrl = window.config.uploadUrl
    } else {
      this.uploadUrl = 'https://pres.cleartv.cn/upload'
    }
  }
}
</script>

  <style scoped>
 .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  ::v-deep .el-cascader-node {
    position: relative;
    display: flex;
    align-items: center;
    padding: 0 30px 0 20px;
    height: 34px;
    line-height: 34px;
    outline: none;
  }
  </style>
