<template>
  <div class="app-container">
    <!-- 表单筛选 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      inline
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="分类名称" prop="categoryId">
        <SelectRemote
          url="/info/category/list"
          field="name"
          v-model="queryParams.categoryId"
          :selectObj="selectObj"
          :searchParams="searchParams"
        />
      </el-form-item>
      <el-form-item label="状态" prop="checkStatus">
        <el-select
          v-model="queryParams.checkStatus"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.check_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 100%"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker
          v-model="updateDateRange"
          style="width: 100%"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAutogeneration"
          >智能生成</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="selectedRow.length < 1"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="selectedRow.length !== 1"
          @click="handleApply"
          >申请审核</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getTableList"
      ></right-toolbar>
    </el-row>
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column
        label="来源"
        align="center"
        prop="source"
        :formatter="sourceFormatter"
      />
      <el-table-column label="状态" align="center" prop="checkStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.check_status"
            :value="scope.row.checkStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="审核结果" align="center" prop="checkResult">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.check_result"
            :value="scope.row.checkResult"
            v-if="scope.row.checkResult"
          />
          <div v-else>无</div>
        </template>
      </el-table-column>
      <el-table-column
        label="发布时间"
        align="center"
        prop="publishTime"
        width="100"
      />
      <el-table-column
        label="撤销时间"
        align="center"
        prop="cancelTime"
        width="100"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="100"
      />
      <el-table-column
        label="修改时间"
        align="center"
        prop="updateTime"
        width="100"
      />
      <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-view"
            @click="handleDetail(scope.row)"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="
              scope.row.checkStatus === '1' ||
              (scope.row.checkStatus === '3' && scope.row.checkResult === '2')
            "
            >修改</el-button
          >
          <!-- 后期需核实删除按钮展示是否有限制(目前是已发布的数据不能删除) -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.checkStatus !== '5'"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-checked"
            @click="handleReview(scope.row)"
            v-if="scope.row.checkStatus === '2'"
            >审核</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleRelease(scope.row)"
            v-if="
              scope.row.checkResult === '2' && scope.row.checkStatus !== '5'
            "
            >发布</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleRevoke(scope.row)"
            v-if="scope.row.checkStatus === '5'"
            >撤销发布</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-order"
            @click="handleRecord(scope.row)"
            >操作记录</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getTableList"
    />
    <!-- 新增编辑弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dlgVisible"
      append-to-body
      width="30%"
    >
      <AddAndEdit
        :loading="dlgLoading"
        :data="formData"
        :dlgType="dlgType"
        @confirm="handleConfirm"
        @cancel="handleCancel"
      ></AddAndEdit>
    </el-dialog>
    <!-- 操作记录弹窗 -->
    <el-dialog title="操作记录" :visible.sync="recordVisible" append-to-body>
      <!-- 表格 -->
      <el-table v-loading="recordLoading" :data="recordList">
        <el-table-column label="操作类型" align="center" prop="operateType" />
        <el-table-column label="操作时间" align="center" prop="createTime" />
        <el-table-column label="操作人" align="center" prop="createBy" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="recordVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  del,
  getRecord,
} from "@/api/infoManage/news";
import SelectRemote from "@/components/SelectRemote";
import AddAndEdit from "./components/addAndEdit.vue";
export default {
  name: "News",
  dicts: ["check_status", "check_result"],
  components: {
    AddAndEdit,
    SelectRemote,
  },
  data() {
    return {
      selectObj: {},
      // 远程搜索框的查询条件
      searchParams: {
        status: "0",
      },
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: "",
        checkStatus: "",
      },
      // 时间
      dateRange: [],
      updateDateRange: [],
      // 来源组
      sourceOption: [
        { value: "0", label: "智能生成" },
        { value: "1", label: "手工录入" },
      ],
      // 分类组
      categoryOption: [],
      // 表格相关
      loading: false,
      tableList: [],
      selectedRow: [],
      total: 0,
      //  弹窗相关
      title: "",
      dlgVisible: false,
      formData: {},
      dlgLoading: false,
      dlgType: 1, // 弹窗类型  1 - 新增   2 - 修改   3 - 查看   4 - 审核
      // 操作记录弹窗相关
      recordVisible: false,
      recordLoading: false,
      recordList: [],
    };
  },
  created() {
    this.getTableList();
  },
  methods: {
    // 来源值映射
    sourceFormatter(row) {
      return this.selectDictLabel(this.sourceOption, row.source);
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getTableList();
    },
    // 重置
    resetQuery() {
      this.dateRange = [];
      this.updateDateRange = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        categoryId: "",
        checkStatus: "",
      };
      this.selectObj = {};
      this.getTableList();
    },
    // 提交，发布，撤销发布公共部分
    handleCommon(params, tip) {
      this.$modal
        .confirm(tip)
        .then(function () {
          return update(params);
        })
        .then(() => {
          this.getTableList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
    // 撤销发布  checkStatus   6
    handleRevoke(row) {
      let params = {
        ...row,
        checkStatus: "6",
      };
      let tip = "是否确认撤销发布？";
      this.handleCommon(params, tip);
    },
    // 发布 checkStatus   5
    handleRelease(row) {
      let params = {
        ...row,
        checkStatus: "5",
      };
      let tip = "是否确认发布？";
      this.handleCommon(params, tip);
    },
    // 审核
    handleReview(row) {
      this.title = "审核";
      this.dlgVisible = true;
      this.dlgType = 4;
      this.dlgLoading = true;
      getDetail(row.id)
        .then((res) => {
          if (res.code === 200) {
            this.formData = { ...res.data, categoryName: row.categoryName };
          }
        })
        .finally(() => (this.dlgLoading = false));
    },
    // 申请审核
    handleApply() {
      let obj = this.selectedRow[0];
      if (obj.checkStatus !== "1")
        return this.$modal.msgError("当前数据不是草稿状态，无法提交");
      let params = {
        ...this.selectedRow[0],
        checkStatus: "2", // 审核状态由草稿 1 改为 待审核 2
      };
      let tip = "是否确认提交审核？";
      this.handleCommon(params, tip);
    },
    // 智能生成（新增一条列表数据）
    handleAutogeneration() {},
    // 新增（手动新增的来源都是手工录入）
    handleAdd() {
      this.title = "新增";
      this.dlgType = 1;
      this.dlgVisible = true;
      this.formData = {};
    },
    // 查看
    handleDetail(row) {
      this.title = "查看";
      this.dlgVisible = true;
      this.dlgType = 3;
      this.dlgLoading = true;
      getDetail(row.id)
        .then((res) => {
          if (res.code === 200) {
            this.formData = { ...res.data, categoryName: row.categoryName };
          }
        })
        .finally(() => (this.dlgLoading = false));
    },
    // 修改
    handleUpdate(row) {
      this.title = "编辑";
      this.dlgType = 2;
      this.dlgVisible = true;
      this.dlgLoading = true;
      getDetail(row.id)
        .then((res) => {
          if (res.code === 200) {
            this.formData = { ...res.data, categoryName: row.categoryName };
          }
        })
        .finally(() => (this.dlgLoading = false));
    },
    // 弹窗确认
    handleConfirm(val) {
      if (val.id) {
        update(val).then((res) => {
          if (res.code === 200) {
            this.$modal.msgSuccess("编辑成功");
            this.handleCancel();
            this.getTableList();
          }
        });
      } else {
        add(val).then((res) => {
          if (res.code === 200) {
            this.$modal.msgSuccess("新增成功");
            this.handleCancel();
            this.getTableList();
          }
        });
      }
    },
    // 弹窗取消
    handleCancel() {
      this.dlgVisible = false;
    },
    // 删除
    handleDelete(row) {
      const selectIds = this.selectedRow.map((item) => item.id);
      const ids = row.id || selectIds;
      this.$modal
        .confirm("是否确认删除数据？")
        .then(function () {
          return del(ids);
        })
        .then(() => {
          this.getTableList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 操作记录
    handleRecord(row) {
      this.recordVisible = true;
      this.recordLoading = true;
      getRecord({ infoId: row.id })
        .then((res) => {
          this.recordList = res.rows;
        })
        .finally(() => (this.recordLoading = false));
    },
    // 表格选中
    handleSelectionChange(selection) {
      this.selectedRow = selection;
    },
    // 查询列表
    getTableList() {
      let params1 = this.addDateRange(this.queryParams, this.dateRange);
      let params2 = this.addDateRange(
        params1,
        this.updateDateRange,
        "updateTime"
      );
      this.loading = true;
      getList(params2)
        .then((res) => {
          if (res.code === 200) {
            this.tableList = res.rows;
            this.total = res.total;
          }
        })
        .finally(() => (this.loading = false));
    },
  },
};
</script>

<style lang="scss" scoped></style>
