<template>
  <div class="app-container">
    <div class="form-content">
      <div class="formHeader">基础信息</div>

      <el-form :model="queryParams" ref="queryRef" label-position="top">
        <el-row>
          <el-col :span="12">
            <div class="commonHeader">产品标题</div>
            <el-select
              v-model="queryParams.productName"
              filterable
              remote
              allow-create
              default-first-option
              :reserve-keyword="false"
              placeholder="请选择产品名称"
              @blur="handleSelectChange"
              :remote-method="searchProduct"
              clearable
              remote-show-suffix
            >
              <el-option
                v-for="item in productList"
                :key="item.productBizId"
                :label="item.productName"
                :value="item.productBizId"
              />
            </el-select>
          </el-col>
          <el-col :span="24">
            <div class="nameTip">
              <span style="color: #ccc">标题需包含产品名称。</span>

              <el-tooltip placement="bottom" effect="light" trigger="click">
                <template #content>
                  <div style="width: 300px">
                    <div v-for="item in nameRequireList" :key="item.key" style="margin-bottom: 8px">
                      <span style="font-size: 13px">•</span>
                      <span style="margin-left: 5px">{{ item.label }}</span>
                    </div>
                  </div>
                </template>
                <span style="color: #576b95; cursor: pointer">查看命名要求</span>
              </el-tooltip>
            </div>
          </el-col>
          <el-col :span="24" v-if="showNameTip">
            <div class="tipCon">
              <el-icon color="red" :size="20" style="margin-right: 5px"><Warning /></el-icon>
              <span>标题信息过少，请至少输入5个有效字数（含中文、英文、数字）</span>
            </div>
          </el-col>
          <el-col :span="24" style="margin: 20px 0">
            <div class="commonHeader">
              图片和视频
              <span style="color: rgb(111, 111, 111); font-size: 15px"
                >({{ imageInfo.count }}/9)</span
              >
            </div>

            <image-upload
              v-model="queryParams.picture"
              :action="'/oss/api/oss/upload'"
              :limit="9"
              :image-size="10"
              :video-size="500"
              :file-type="['png', 'jpg', 'jpeg', 'mp4']"
              :is-show-tip="false"
              @change="handleImageChange"
              @file-change="handleFileChange"
            />
          </el-col>
          <el-col :span="24">
            <div v-for="(item, index) in imageRequireList" :key="item.key" class="imgTip">
              <span>{{ index + 1 }}.</span>
              <span>{{ item.label }}</span>
              <el-tooltip placement="bottom" effect="light" trigger="click" v-if="item.showTip">
                <template #content>
                  <div style="width: 300px">
                    <div v-for="item in imageTipList" :key="item.key" style="margin-bottom: 8px">
                      <span style="font-size: 13px">•</span>
                      <span style="margin-left: 5px">{{ item.label }}</span>
                    </div>
                  </div>
                </template>
                <span style="color: #576b95; cursor: pointer">{{ item.tipContent }}</span>
              </el-tooltip>
            </div>
          </el-col>
          <el-col :span="24" v-if="imageInfo.count > 0 && imageInfo.count < 3">
            <div class="tipCon">
              <el-icon color="red" :size="20" style="margin-right: 5px"><Warning /></el-icon>
              <span>请上传至少3张产品主图</span>
            </div>
          </el-col>
          <el-col :span="24" style="margin: 20px 0">
            <div class="commonHeader">产品类目</div>

            <!-- <div class="classTip" v-if="!queryParams.productName || imageInfo.count < 3">
            填写标题及上传主图后，即可选择类目
          </div> -->

            <CategoryTable style="height: 300px" type="add" ref="categoryData" />
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bottomBtn">
      <el-button type="primary" size="large" @click="submitProduct">下一步</el-button>
    </div>
  </div>
</template>
<script setup name="InsuranceProduct">
import { getProductList, addProduct } from '@/api/product/index'
import useUserStore from '@/store/modules/user'
import { computed, ref } from 'vue'
import ImageUpload from '@/components/ImageUpload/index.vue' //图片上传组件
import CategoryTable from '@/components/CategoryTable/index.vue' //图片上传组件
const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
// const { bx_product_type, sys_scope, bx_product_status, bx_smoking_allowed, bx_currency_type } =
//   proxy.useDict(
//     'bx_product_type',
//     'sys_scope',
//     'bx_product_status',
//     'bx_smoking_allowed',
//     'bx_currency_type'
//   )
const showNameTip = ref(false)
const imageInfo = ref({ count: 0, fileList: [] })
const productList = ref([])
const categoryData = ref(null)
const nameRequireList = ref([
  {
    label: '标题中必须包含产品名称',
    key: '1'
  },
  {
    label: '标题禁止出现连续重复的关键词',
    key: '2'
  },
  {
    label: '标题字数不少于5个字，包括中文、 英文、数字',
    key: '3'
  },
  {
    label: '标题为非中文时需要附带与产品对应一致的中文翻译',
    key: '4'
  },
  {
    label: '标题中需避免填写错别字',
    key: '5'
  }
])
const imageRequireList = ref([
  {
    label: '商品主图须符合平台要求，否则将无法通过审核。',
    key: '1',
    showTip: true,
    tipContent: '查看主图要求'
  },
  {
    label: '最少上传3个素材，最多上传9个素材，其中最多上传1个视频(mp4格式)，拖拽图片可排序。',
    key: '2'
  },
  {
    label: '视频时长不超过180秒，视频大小不超过500M；单张图片需限制在10M以内。',
    key: '3'
  }
])
const imageTipList = ref([
  {
    label: '全类目的产品主图要求提供不少于3张产品相关图片',
    key: '1'
  },
  {
    label: '主图第一张需为产品实物图',
    key: '2'
  },
  {
    label: '产品主图中不可包含相同的图片',
    key: '3'
  },
  {
    label: '产品图片不允许为手机截图、空白图',
    key: '4'
  },
  {
    label: '图片需清晰，不允许打码、遮挡/ps',
    key: '5'
  }
])
const data = reactive({
  form: {},
  queryParams: {},
  rules: {
    productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
    scope: [{ required: true, message: '作用域不能为空', trigger: 'blur' }],
    productType: [{ required: true, message: '产品类型不能为空', trigger: 'blur' }],
    currency: [{ required: true, message: '货币不能为空', trigger: 'blur' }],
    premiumRate: [
      { required: true, message: '基础费率不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value === '' || value === null) {
            callback(new Error('基础费率不能为空'))
            return
          }

          const numValue = Number(value)
          if (isNaN(numValue)) {
            callback(new Error('请输入有效的数字'))
          } else if (numValue < 0) {
            callback(new Error('基础费率不能小于0'))
          } else if (numValue > 100) {
            callback(new Error('基础费率不能大于100'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    smokingAllowed: [{ required: true, message: '是否区分吸烟不能为空', trigger: 'blur' }],
    productStatus: [{ required: true, message: '产品状态不能为空', trigger: 'blur' }],
    startAge: [
      { required: true, message: '起保年龄不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!Number.isInteger(Number(value)) || value <= 0) {
            callback(new Error('请输入正整数'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    endAge: [
      { required: true, message: '终保年龄不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!Number.isInteger(Number(value)) || value <= 0) {
            callback(new Error('请输入正整数'))
          } else if (Number(value) <= Number(form.value.startAge)) {
            callback(new Error('终保必须大于起保'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    tenantBizId: [{ required: true, message: '所属租户不能为空', trigger: 'blur' }],
    ssDeptBizIdList: [
      {
        required: true,
        message: '所属保险公司不能为空',
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error('请至少选择一个所属保险公司'))
          } else {
            callback()
          }
        }
      }
    ],
    picture: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!value || value.trim() === '') {
            callback(new Error('请上传产品图片'))
          } else {
            callback()
          }
        },
        trigger: 'change'
      }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)
function handleImageChange(value) {
  console.log('图片', value)
}
const handleFileChange = info => {
  imageInfo.value = JSON.parse(JSON.stringify(info))
  console.log('图片信息', imageInfo.value)
}
const handleSelectChange = () => {
  if (queryParams.value.productName && queryParams.value.productName.length < 5) {
    showNameTip.value = true
  } else if (!queryParams.value.productName) {
    showNameTip.value = true
  } else {
    showNameTip.value = false
  }
}
/** 查询产品列表 */
function searchProduct(query) {
  let productName = query ? query.trim() : ''

  let data = {
    productName: productName,
    pageSize: 10,
    pageNo: 1
  }
  getProductList(data).then(response => {
    if (response.code === 200) {
      productList.value = response.data.records
    } else {
      productList.value = []
      proxy.$modal.msgError(response.msg)
    }
  })
}
/** 新增产品 */
function submitProduct() {
  let productBizId = ''
  let categoryBizIdList = []
  let mainUrlsList = []
  let productName = queryParams.value.productName
  if (!productName) {
    proxy.$modal.msgError('产品名称不能为空或长度小于5')
    showNameTip.value = true
    return
  } else {
    productList.value.forEach(item => {
      if (item.productBizId === productName) {
        productBizId = item.productBizId
        productName = item.productName
      }
    })
  }
  if (imageInfo.value.fileList && imageInfo.value.fileList.length > 0) {
    imageInfo.value.fileList.forEach(item => {
      mainUrlsList.push(item.url)
    })
  } else {
    proxy.$modal.msgError('请上传产品图片')
    return
  }
  if (categoryData.value) {
    categoryData.value.categoryList.forEach(item => {
      item.data.forEach(item2 => {
        if (item2.isSelected) {
          categoryBizIdList.push(item2.categoryBizId)
        }
      })
    })
  }
  
  if (categoryBizIdList.length === 0) {
    proxy.$modal.msgError('请选择产品类目')
    return
  }

  let data = {
    productBizId: productBizId,
    productName: productName,
    mainUrlsList: mainUrlsList,
    categoryBizIdList: categoryBizIdList
  }

  // return
  addProduct(data).then(response => {
    if (response.code === 200) {
      router.push({
        path: '/merchandise/putOnSale',
        query: {
          productBizId: response.data.productBizId,
          productLaunchBizId: response.data.productLaunchBizId
        }
      })
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}

searchProduct()
</script>
<style lang="scss" scoped>
.app-container {
  width: 100%;
  box-sizing: border-box;
  /* background-color: rgb(247 247 247) !important; */
  /* padding: 0 !important; */
  /* height: 500px !important;
  overflow: hidden;
  overflow-y: scroll; */
}
.form-content {
  width: 100%;
  box-sizing: border-box;
  height: 72.5vh;
  overflow: hidden;
  overflow-y: scroll;
  /* padding: 20px; */
  /* background-color: #fff; */
}
.formHeader {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: 600;
}
.nameTip {
  font-size: 13px;
  margin-top: 10px;
}
.tipCon {
  /* width: 450px; */
  width: fit-content;
  /* 为了更好的兼容性，可以加上带前缀的版本 */
  width: -moz-fit-content;
  width: -webkit-fit-content;
  margin: 5px 0;
  padding: 10px 10px;
  border-radius: 5px;
  background-color: rgb(247 247 247);
  font-size: 14px;
  display: flex;
  align-items: center;
  span {
    color: rgb(111 111 111);
  }
}
.commonHeader {
  font-size: 16px;
  margin-bottom: 15px;
}
.imgTip {
  color: #ccc;
  font-size: 14px;
  margin-bottom: 10px;
}
.classTip {
  color: #ccc;
  font-size: 14px;
}
.bottomBtn {
  border-top: 1px solid rgb(247 247 247);
  width: 100%;
  padding: 30px 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background-color: #fff;
}
</style>
