<template>
  <div class="apaas_detail_container banner_detail_container">
    <div class="apass_breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/message' }">
          {{ $t("lang.message") }}
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/message/banner' }">
          {{ "banner管理" }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          {{ pageName }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="main_contaner banner_contaner">
      <el-form
        ref="detail_form"
        class="apaas_detail_form"
        label-position="top"
        :model="detail"
        :rules="detail_rules"
      >
        <el-form-item label="banner名称：" prop="name">
          <el-input
            v-model="detail.name"
            placeholder="请输入banner名称"
            :disabled="disabled"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态：" prop="state">
          <el-select
            v-model="detail.state"
            placeholder="请选择状态"
            :disabled="disabled1"
          >
            <el-option
              v-for="item in types"
              :label="item.name"
              :value="item.value"
              :key="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="链接地址（选填）：" prop="url">
          <el-input
            v-model="detail.url"
            placeholder="请输入链接地址"
            :disabled="disabled"
          ></el-input>
        </el-form-item>

        <el-form-item label="排序：" prop="rank">
          <el-input
            v-model="detail.rank"
            placeholder="请输入排序"
            :disabled="disabled"
          ></el-input>
        </el-form-item>

        <el-form-item label="上架时间：" prop="up_time">
          <el-date-picker
            v-model="detail.up_time"
            type="datetime"
            :disabled="disabled"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="下架时间：" prop="down_time">
          <el-date-picker
            v-model="detail.down_time"
            type="datetime"
            :disabled="disabled"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="上传banner图片：" prop="fileList">
          <upload-file
            :multiple="false"
            :max="1"
            type="picture"
            :readOnly="false"
            fit="fill"
            :list="imgList"
            @getNewList="getNewList"
            ref="servicepic"
            directory="manage"
            :disabled="disabled"
          ></upload-file>
        </el-form-item>
      </el-form>

      <div class="apaas_button detail_action">
        <el-button
          type="default"
          @click="cancelAction"
          :loading="submitLoading"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          @click="primaryAction"
          :loading="submitLoading"
          v-if="pageType !== 2"
        >
          确定
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
var user_name_pass = (rule, value, callback) => {
  var reg = /^[a-zA-Z0-9|\-|_|\.]+$/;
  setTimeout(() => {
    if (reg.test(value)) {
      callback();
    } else {
      callback(new Error("只支持字母、数字、-、_、."));
    }
  }, 100);
};
var rank_rule = (rule, value, callback)=>{
  var reg = /^[1-9][0-9]{0,1}$/;
  setTimeout(() => {
    if (reg.test(value)) {
      callback();
    } else {
      callback(new Error("请输入2位内正整数"));
    }
  }, 100);
}
import helper from "@/services/helper.js";
import uploadFile from "@/components/general/upload_file";
export default {
  components: {
    uploadFile,
  },
  data(){ 
    var validateup = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择上架时间'));
        } else {
          if (this.detail.down_time !== '') {
            this.$refs.detail_form.validateField('down_time');
          }
          callback();
        }
      };
var validatedown = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请选择下架时间'));
  } else if (value.getTime() <= this.detail.up_time.getTime()) {
    callback(new Error('下架时间应在上架时间之后'));
  } else {
    callback();
  }
};
    return{
    pageType: 0, // 0：新增，1：编辑，2：详情
    detail: {
      name: "",
      state: "",
      url: "",
      rank: "",
      up_time: "",
      down_time: "",
      fileList: "",
      size: "",
      id: "",
    },
    imgList: [],
    detail_rules: {
      name: [
        {
          required: true,
          message: "请输入banner名称",
          trigger: "blur",
        },
        {
          max: 16,
          message: "长度小于16个字符",
          trigger: "blur",
        },
        // { validator: user_name_pass, trigger: 'blur' }
      ],
      state: [
        {
          required: true,
          message: "请选择状态",
          trigger: "change",
        },
      ],
      rank: [
        {
          required: true,
          message: "请输入排序",
          trigger: "blur",
        },
        { 
          validator: rank_rule, 
          trigger: 'blur' 
        }
      ],
      up_time: [
        {
          required: true,
          message: "请选择上架时间",
          trigger: "change",
        },
        {
          validator:validateup,
          trigger: "change",
        },
      ],
      fileList: [
        {
          required: true,
          message: "请选择上传图片",
          trigger: "change",
        },
      ],
      down_time: [
        {
          required: true,
          message: "请选择下架时间",
          trigger: "change",
        },
        {
          validator:validatedown,
          trigger: "change",
        },
      ],
      url: [],
    },
    types: [
      {
        name: "已上架",
        value: 1,
      },
      {
        name: "已下架",
        value: 0,
      },
    ],
    submitLoading: false,
  }
  },
  computed: {
    pageName() {
      return ["新增", "编辑", "详情"][this.pageType];
    },
    disabled() {
      return this.pageType === 2;
    },
    disabled1() {
      return this.pageType !== 1;
    },
  },
  created() {
    if (this.$route.name === "banner_edit") {
      this.pageType = 1;
    } else if (this.$route.name === "banner_detail") {
      this.pageType = 2;
    } else {
      this.detail.state = 1;
    }

    if (this.pageType !== 0) {
      this.getDetail();
    }
  },
  methods: {
    getNewList(val) {
      this.detail.fileList = val[0].url;
      this.detail.size = val[0].size;
      console.log(this.detail.fileList);
      this.$refs.detail_form.validateField('fileList')
    },
    getDetail() {
      this.$http
        .get(
          "/apaas/service/v3/recommend/manage/banners/info/" +
            this.$route.query.id
        )
        .then(({ data }) => {
          if (data.success == 1) {
            var detail = data.data;
            this.detail = {
              name: detail.name,
              state: detail.state,
              url: detail.url,
              rank: detail.ordid,
              up_time: detail.up_time,
              down_time: detail.down_time,
              fileList: detail.image_url,
              size: detail.image_size,
              id: detail.serial_num,
            };
            this.imgList = [detail.image_url];
          } else {
            this.$message({
              message: data.errMsg || "获取详情失败",
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.log(error);

          this.$message({
            message: "获取详情失败",
            type: "warning",
          });
        });
    },
    addTemplate() {
      this.$http
        .post("/apaas/service/v3/recommend/manage/banners/add", {
          name: this.detail.name,
          url: this.detail.url,
          image_size: this.detail.size,
          image_url: this.detail.fileList,
          up_time: this.detail.up_time,
          down_time: this.detail.down_time,
          state: this.detail.state,
          ordid: parseInt(this.detail.rank),
        })
        .then(({ data }) => {
          if (data.success == 1) {
            this.$message({
              message: "新增banner成功",
              type: "success",
            });

            setTimeout(() => {
              this.$router.push("/message/banner");
            }, 500);
          } else {
            this.$message({
              message: data.errMsg || "新增banner失败",
              type: "warning",
            });
          }

          this.submitLoading = true;
        })
        .catch((error) => {
          console.log(error);

          this.$message({
            message: "新增banner失败",
            type: "warning",
          });

          this.submitLoading = true;
        });
    },
    editTemplate() {
      this.$http
        .post("/apaas/service/v3/recommend/manage/banners/update", {
          serial_num: this.detail.id,
          name: this.detail.name,
          url: this.detail.url,
          image_size: this.detail.size,
          image_url: this.detail.fileList,
          up_time: this.detail.up_time,
          down_time: this.detail.down_time,
          state: this.detail.state,
          ordid: parseInt(this.detail.rank),
        })
        .then(({ data }) => {
          if (data.success == 1) {
            this.$message({
              message: "编辑banner成功",
              type: "success",
            });

            setTimeout(() => {
              this.$router.push("/message/banner");
            }, 200);
          } else {
            this.$message({
              message: data.errMsg || "编辑banner失败",
              type: "warning",
            });
          }

          this.submitLoading = true;
        })
        .catch((error) => {
          console.log(error);

          this.$message({
            message: "编辑banner失败",
            type: "warning",
          });

          this.submitLoading = true;
        });
    },
    cancelAction() {
      this.$router.push("/message/banner");
    },
    primaryAction() {
      if (this.pageType === 2) {
        this.$router.push("/message/banner");
      } else {
        this.$refs.detail_form.validate((valid) => {
          if (valid) {
            this.submitLoading = true;

            this.pageType === 1 ? this.editTemplate() : this.addTemplate();
          } else {
            return false;
          }
        });
      }
    },
  },
};
</script>

<style>
.banner_detail_container .banner_contaner .el-input__inner {
  width: 970px;
}
.banner_detail_container .el-upload--picture-card {
  width: 526px;
  height: 174px;
  line-height: 174px;
}
.banner_detail_container .el-upload-list--picture-card .el-upload-list__item {
  width: 526px;
  height: 174px;
}
</style>
