<template>
  <el-dialog :title="$t(titleLabel)" :visible="show" @close="close" width="80%">
    <el-form :model="queryParams" ref="queryForm" size="small" :rules="rules" label-width="120px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item :label="$t('中文礼品名称')" prop="titleZh">
            <el-input v-model="queryParams.titleZh" :placeholder="$t('请输入')" :disabled="isDisable" clearable v-trim />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('英文礼品名称')" prop="titleEn">
            <el-input v-model="queryParams.titleEn" :disabled="isDisable" :placeholder="$t('请输入')" clearable v-trim />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item :label="$t('中文礼品图片')" prop="number">
            <image-upload :fileType="['png', 'jpg', 'jpeg']" v-model="queryParams.imgZh" :isShowEditButton="!isDisable" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('英文礼品图片')" prop="number">
            <image-upload v-model="queryParams.imgEn" :fileType="['png', 'jpg', 'jpeg']" :isShowEditButton="!isDisable" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-for="(item, index) in queryParams.nodeIds" :key="item.id">
        <el-col :span="6">
          <el-form-item v-if="title == 3" :label="$t('提货点')" :prop="`nodeIds[${index}].wareHouses`" :rules="rules.nodeIds.wareHouses">
            <el-select v-model="item.wareHouses" :placeholder="$t('请选择提货点')" :disabled="isDisable" clearable multiple filterable remote reserve-keyword :remote-method="handleWarehouseList" @visible-change="changeWarehouseList" :loading="loading" size="small">
              <el-option v-for="nodeItem in warehouseList" :key="nodeItem.id" :label="isChinese ? nodeItem.titleZh : nodeItem.titleEn" :value="nodeItem.id" />
            </el-select>
          </el-form-item>
          <!-- 编辑对应单个提货点 逻辑显示-->
          <el-form-item v-else :label="$t('提货点')" :prop="`nodeId`">
            <el-select v-model="queryParams.nodeId" :placeholder="$t('请选择提货点')" :disabled="isDisable" clearable filterable remote reserve-keyword :remote-method="handleWarehouseList" @visible-change="changeWarehouseList" :loading="loading" size="small">
              <el-option v-for="nodeItem in warehouseList" :key="nodeItem.id" :label="isChinese ? nodeItem.titleZh : nodeItem.titleEn" :value="nodeItem.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('兑换积分')" :prop="`nodeIds[${index}].points`" :rules="rules.nodeIds.points"> <el-input v-model.trim.number="item.points" :placeholder="$t('请输入')" :disabled="isDisable" /> </el-form-item
        ></el-col>
        <el-col :span="6" class="giftNum">
          <el-form-item :label="$t('剩余数量')" :prop="`nodeIds[${index}].quantityRemain`" :rules="rules.nodeIds.quantityRemain">
            <el-input class="input-item-width" :disabled="isDisable && disabelEnableStatus" v-model.trim="item.quantityRemain" :placeholder="$t('请输入')" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" :disabled="isDisable" v-if="title == 3" :icon="index == '0' ? 'el-icon-plus' : 'el-icon-minus'" @click="handleOrderVRule(item, index)"></el-button>
        </el-col>
      </el-row>

      <el-form-item :label="$t('活动时间')" prop="dateRangeCreateTime">
        <el-date-picker :disabled="isDisable" type="daterange" clearable placement="bottom-start" @change="dataTimeFunc" v-model="queryParams.dateRangeCreateTime" style="width: 400px" value-format="yyyy-MM-dd HH:mm:ss" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" />
      </el-form-item>
      <el-form-item :label="$t('领取方式')" prop="pickMethod">
        <dict-selector clearable multiple :disabled="isDisable" :type="DICT_TYPE.WAY_OF_RECEIVING" v-model="queryParams.pickMethod"> </dict-selector>
      </el-form-item>
      <el-form-item :label="$t('允许兑换次数')" prop="allowCount">
        <el-input class="input-item-width" v-model.trim.number="queryParams.allowCount" :placeholder="$t('请输入')" clearable :disabled="isDisable" />
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item :label="$t('中文备注')" prop="remarkZh">
            <el-input type="textarea" :disabled="isDisable && disabelEnableStatus" height="100" v-model="queryParams.remarkZh" :placeholder="$t('请输入')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('英文备注')" prop="remarkEn">
            <el-input type="textarea" :disabled="isDisable && disabelEnableStatus" v-model="queryParams.remarkEn" :placeholder="$t('请输入')"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <el-form-item :label="$t('是否启用')" prop="status" v-if="title == '3'">
          <el-radio-group v-model="queryParams.status" :disabled="isDisable">
            <el-radio v-for="dict in getDictDatas(DICT_TYPE.GIFT_ENABLE_STATUS)" :key="dict.value" :label="dict.value">{{ $l(dict, "label") }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('状态')" prop="status" v-else>
          <el-radio-group v-model="queryParams.status" :disabled="isDisable">
            <el-radio v-for="dict in getDictDatas(DICT_TYPE.GIFT_STATUS)" :key="dict.value" :label="Number(dict.value)">{{ $l(dict, "label") }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" v-if="!isDisable || !disabelEnableStatus">
      <el-button @click="close">{{ $t("取 消") }}</el-button>
      <el-button type="primary" @click="submit">{{ $t("确 定") }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { editRewards, addRewards, getWarehouseList } from "@/api/ecw/giftManagement"
import { getDictDatas, DICT_TYPE } from "@/utils/dict"
import imageUpload from "@/components/ImageUpload"
import { parseTime, resetForm } from "../../../../utils/ruoyi"
import { deepClone, titleCase } from "@/utils"
export default {
  name: "operatingGift",
  props: {
    title: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    rewardsDetails: {
      type: Object,
      default: () => {
        return this.queryParams
      }
    },
    nodeList: {
      type: Array,
      default: () => []
    }
  },
  components: {
    imageUpload
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN"
    },
    isDisable() {
      let disableStatus = false
      switch (this.title) {
        case "1":
          disableStatus = true
          this.disabelEnableStatus = true
          break
        case "2":
          if (this.queryParams.status == "2") {
            disableStatus = false
            this.disabelEnableStatus = true
          } else if (this.queryParams.status == "1") {
            disableStatus = true
            this.disabelEnableStatus = false
          } else {
            disableStatus = true
            this.disabelEnableStatus = true
          }
          break
        case "3":
          disableStatus = false
          break
      }
      return disableStatus
    },
    titleLabel() {
      let titleLabelText = ""
      switch (this.title) {
        case "1":
          titleLabelText = this.$t("查看礼品")
          break
        case "2":
          titleLabelText = this.$t("编辑礼品")
          break
        case "3":
          this.resetFormQuery()
          titleLabelText = this.$t("新增礼品")
          break
      }
      return titleLabelText
    }
  },
  watch: {
    rewardsDetails(newVal, oldVal) {
      if (JSON.stringify(newVal) != "{}") {
        this.queryParams = deepClone(newVal)
        this.$set(this.queryParams, "dateRangeCreateTime", [parseTime(newVal.startTime), parseTime(newVal.endTime)])
        this.queryParams.pickMethod = newVal.pickMethod.split(",")
        this.$nextTick(() => {
          this.$refs["queryForm"].clearValidate()
        })
      } else {
        this.resetFormQuery()
        this.$nextTick(() => {
          this.$refs["queryForm"].resetFields()
          this.$refs["queryForm"].clearValidate()
        })

        console.log("Prop is empty")
      }
    }
  },
  data() {
    return {
      loading: false,
      queryParams: {
        allowCount: null,
        endTime: null,
        imgEn: null,
        imgZh: null,
        nodeIds: [{ wareHouses: [], points: "", quantityRemain: null, id: 0 }],
        nodeId: null,
        pickMethod: [],
        pointsRequire: null,
        remarkEn: null,
        remarkFr: null,
        remarkZh: null,
        startTime: null,
        status: null,
        titleEn: null,
        titleZh: null,
        dateRangeCreateTime: []
      },
      disabelEnableStatus: false,
      warehouseList: [],
      rules: {
        titleZh: [
          {
            required: true,
            message: this.$t("请输入中文礼品名称"),
            trigger: "blur"
          },
          {
            min: 0,
            max: 50,
            message: this.$t("长度在 0 到 50 个字符"),
            trigger: "blur"
          }
        ],
        titleEn: [
          {
            required: true,
            message: this.$t("请输入英文礼品名称"),
            trigger: "blur"
          },
          {
            min: 0,
            max: 50,
            message: this.$t("长度在 0 到 50 个字符"),
            trigger: "blur"
          }
        ],
        nodeId: [
          {
            required: true,
            message: this.$t("请选择提货点"),
            trigger: "change"
          }
        ],
        nodeIds: {
          wareHouses: [
            {
              required: true,
              message: this.$t("请选择提货点"),
              trigger: "change"
            }
          ],
          points: [
            {
              required: true,
              message: this.$t("请输入兑换积分"),
              trigger: "blur"
            },
            { type: "number", message: "输入数字", trigger: "blur" }
          ],
          quantityRemain: [
            {
              required: true,
              message: this.$t("请输入剩余数量"),
              trigger: "blur"
            }
          ]
        },

        pickMethod: [
          {
            required: true,
            message: this.$t("请选择领取方式"),
            trigger: "change"
          }
        ],
        allowCount: [
          {
            required: true,
            message: this.$t("请输入允许兑换次数"),
            trigger: "blur"
          },
          { type: "number", message: "输入数字", trigger: "blur" }
        ],
        remarkZh: [
          {
            min: 0,
            max: 500,
            message: this.$t("长度在 0 到 500 个字符"),
            trigger: "blur"
          }
        ],
        remarkEn: [
          {
            min: 0,
            max: 500,
            message: this.$t("长度在 0 到 500 个字符"),
            trigger: "blur"
          }
        ],
        status: [
          {
            required: true,
            message: this.$t("请选择是否启用"),
            trigger: "change"
          }
        ]
      }
    }
  },
  created() {
    this.handleWarehouseList()
  },
  methods: {
    dataTimeFunc(e) {},
    changeWarehouseList(e) {
      if (e) {
        this.handleWarehouseList()
      }
    },
    handleWarehouseList(val = "") {
      let params = { title: val }
      getWarehouseList(params).then((res) => {
        this.warehouseList = res.data
      })
    },
    handleOrderVRule(item, index) {
      if (index == "0") {
        this.queryParams.nodeIds.push({ wareHouses: [], quantityRemain: null, points: "", id: index + 1 })
      } else {
        this.queryParams.nodeIds.splice(index, 1)
      }
    },
    submit() {
      let params = { ...this.queryParams }
      params.startTime = this.queryParams?.dateRangeCreateTime?.[0]
      params.endTime = this.queryParams?.dateRangeCreateTime?.[1]
      params.pickMethod = this.queryParams.pickMethod.toString()
      if (this.title != 3) {
        params.nodeIds[0].wareHouses[0] = params.nodeId
      }
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          if (this.title == "2") {
            editRewards(params).then((res) => {
              this.$emit("update:show", false)
              this.$message.success(this.$t("编辑成功"))
              this.$refs["queryForm"].resetFields()
              this.$parent.getList()
            })
          } else {
            //Add
            addRewards(params).then((res) => {
              this.$emit("update:show", false)
              this.$message.success(this.$t("成功"))
              this.$refs["queryForm"].resetFields()
            })
          }
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    close() {
      this.$emit("update:show", false)
    },
    resetFormQuery() {
      this.queryParams = {
        allowCount: null,
        endTime: null,
        nodeIds: [{ wareHouses: [], points: "", quantityRemain: null, id: 0 }],
        imgEn: null,
        imgZh: null,
        nodeId: null,
        pickMethod: [],
        pointsRequire: null,
        remarkEn: null,
        remarkFr: null,
        remarkZh: null,
        startTime: null,
        status: null,
        titleEn: null,
        titleZh: null,
        dateRangeCreateTime: []
      }
    }
  }
}
</script>
<style>
.input-item-width {
  width: 194px;
}
.giftNum .input-item-width {
  width: auto;
}
</style>
