<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item el-button el-button--primary el-button--mini"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
        >添加资讯</el-button
      >
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="ID" prop="id" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.news_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.static | getStaticName(statics) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="封面图" align="center">
        <template slot-scope="{ row }">
          <img :src="row.image" height="100" />
        </template>
      </el-table-column>
      <el-table-column label="外链" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 添加或修改分类对话框 -->
    <el-drawer
      ref="drawer"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      direction="rtl"
      custom-class="drawer"
      size="950px"
    >
      <div class="drawer__content">
        <el-form
          ref="dataForm"
          :model="temp"
          label-position="left"
          label-width="70px"
          style
        >
          <el-form-item label="类型">
            <el-select v-model="temp.static" placeholder="选择类型">
              <el-option
                v-for="(item, index) in statics"
                :key="index"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关联文章">
            <el-select
              v-model="temp.article_id"
              remote
              :loading="searchArticleLoading"
              :remote-method="remoteMethod"
              reserve-keyword
              placeholder="请输入关键字搜索"
              filterable
              :clearable="true"
              @change="handleSelectBranch"
            >
              <el-option
                v-for="(item, index) in articles"
                :key="index"
                :label="item.title"
                :value="item.article_id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input v-model="temp.title" />
          </el-form-item>
          <el-form-item label="外链" prop="url">
            <el-input v-model="temp.url" />
          </el-form-item>
          <el-form-item label="封面" prop="image" required>
            <img
              v-if="temp.image"
              :src="temp.image"
              class="el-upload el-upload--picture-card"
              style="float: left; width: auto"
            />
            <el-upload
              ref="sys_app_logo"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :action="uploadAction"
              style="float: left"
              list-type="picture-card"
              :show-file-list="false"
              :before-upload="validationImages"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
        </el-form>
        <div class="drawer__footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  fetchAdList,
  createAd,
  updateAd,
  delAd,
  searchArticle,
} from "@/api/ad";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  name: "adIndex",
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
      },
      uploadAction: process.env.VUE_APP_BASE_API + "/files/uploadFile",
      temp: {
        id: undefined,
        static: 1,
        title: "",
        url: "",
        article_id: undefined,
        image: "",
        is_show: 1,
      },
      statics: [
        { name: "大轮播图", value: 1 },
        { name: "小轮播图", value: 2 },
        { name: "资讯列表", value: 3 },
      ],
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      rules: {
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
      searchArticleLoading: false,
      articles: [],
      validation: true,
    };
  },
  created() {
    this.getList();
  },
  filters: {
    getStaticName(id, statics) {
      for (var i = 0; i < statics.length; i++) {
        if (id == statics[i].value) {
          return statics[i].name;
        }
      }
      return "";
    },
  },
  methods: {
    // 验证图片宽高
    async validationImages(file) {
      let desc = this.temp.static === 1 ? "bigSwiper" : "smallSwiper";
      let res = await this.$getImgWidth(file, desc);
      this.validation = res;
      return res;
    },
    getList() {
      this.listLoading = true;
      fetchAdList(this.listQuery).then((response) => {
        this.list = response.data.list;
        this.total = response.data.count;

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作Success",
        type: "success",
      });
      row.status = status;
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        static: 1,
        title: "",
        url: "",
        article_id: undefined,
        image: "",
        is_show: 1,
      };
    },
    submitForm() {
      if (this.dialogStatus == "create") {
        this.createData();
      } else if (this.dialogStatus == "update") {
        this.updateData();
      }
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    createData() {
      // this.$refs['dataForm'].validate((valid) => {
      //   if (valid) {
      createAd(this.temp).then(() => {
        this.dialogFormVisible = false;
        this.$message({
          message: "添加成功",
          type: "success",
          duration: 2 * 1000,
        });
        this.getList();
      });
      //   }
      // })
    },
    handleUpdate(row) {
      // let news_id = row.news_id
      // fetchAdDetails({news_id}).then(res => {

      var that = this;
      searchArticle(row.article_id)
        .then((res) => {
          that.articles = res.data;
          that.temp = row;
          this.dialogStatus = "update";
          this.dialogFormVisible = true;
        })
        .catch(function (err) {
          console.log(err);
        });
    },
    updateData() {
      // this.$refs['dataForm'].validate((valid) => {
      //   if (valid) {
      updateAd(this.temp).then(() => {
        this.dialogFormVisible = false;
        this.$message({
          message: "更新成功",
          type: "success",
          duration: 2 * 1000,
        });

        this.getList();
      });
      //   }
      // })
    },
    handleDelete({ title, news_id }) {
      this.$confirm('是否确认删除名称为"' + title + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          console.log("del");
          return delAd({ news_id });
        })
        .then((response) => {
          if (response.code === 200) {
            this.$message({
              message: "删除成功",
              type: "success",
              duration: 2 * 1000,
            });
            this.open = false;
            this.getList();
          } else {
            this.$message({
              message: "删除失败",
              type: "error",
              duration: 2 * 1000,
            });
          }
        })
        .catch(function () {});
    },
    uploadSuccess(response, file) {
      if (this.validation && response.state == "SUCCESS") {
        this.temp.image = response.url;
      }
    },
    uploadFileSuccess(response, file) {
      let obj = {};
      obj.name = response.original;
      obj.url = response.url;
      this.temp.script_url = JSON.stringify(obj);
    },
    uploadRemove(file) {
      const uid = file.uid;
      const objKeyArr = Object.keys(this.listObj);
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]];
          return;
        }
      }
    },
    uploadError(err) {
      this.$alert(err, "发生错误", {
        confirmButtonText: "确定",
        callback: (action) => {},
      });
    },
    handleSelectBranch(item) {
      console.log("远程搜索选中后返回的item：：：：：即value的值");
      console.log(item);
      //如果要获取选择的 id或者名字   从item中取值
      this.$set(this.temp, "article_id", item);
    },
    // 搜索模糊查询数据下拉框
    remoteMethod(query) {
      var that = this;
      searchArticle(query)
        .then(function (res) {
          //将取到的值进行遍历
          that.articles = res.data;
          that.list = that.states.map((item) => {
            // item.uid     item.name根据接口里的关键字
            return { value: item.uid, label: item.name };
          });
        })
        .catch(function (err) {
          console.log(err);
        });
      return;
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  .filter-container {
    margin-left: 5px;
    margin-bottom: 6px;
  }
  ::v-deep .el-drawer__body {
    padding: 20px;
  }
}
</style>
