<template>
  <div class="app-container">
    <el-card>
      <el-button type="primary" icon="el-icon-plus" @click="handleAddContent" v-if="checkPermission(['policy_create'])"
        >
        新增
      </el-button>
      <el-input
            v-model="listQuery.search" 
            placeholder="输入关键字搜索" 
            style="width: 200px;" 
            class="filter-item"
        />
        <el-button 
        class="filter-item" 
        type="primary" 
        icon="el-icon-search" 
        @click="handleSearch">搜索</el-button>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-table
        v-loading="listLoading"
        :data="contentList.results"
        border
        fit
        stripe
        highlight-current-row
        max-height="600"
      >
        <el-table-column type="index" width="50" />
        <el-table-column label="名称" min-width="110">
          <template slot-scope="scope" v-if="scope.row.file_.file">
            <el-link :href="scope.row.file_.file" type="primary">{{ scope.row.name }}</el-link>
          </template>
          <template slot-scope="scope" v-else>{{ scope.row.name }}</template>
        </el-table-column>
        <!-- <el-table-column align="center" label="文件下载" width="80">
          <template slot-scope="scope" v-if="scope.row.file_.file">
            <el-link :href="scope.row.file_.file" type="primary">
              <el-icon class="el-icon--right"><icon-view /></el-icon>
              <i class="el-icon-download"></i>
            </el-link>
          </template>
        </el-table-column> -->
         <el-table-column label="文件描述"  >
          <template slot-scope="scope">{{ scope.row.description }}</template>
        </el-table-column>
         <el-table-column label="创建时间" width='160'>
          <template slot-scope="scope">{{ scope.row.create_time }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="120px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              :disabled="!checkPermission(['policy_update'])"
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
            />
            <el-button
              :disabled="!checkPermission(['policy_delete'])"
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="contentList.count > 0"
        :total="contentList.count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑政策资讯' : '新增政策资讯'"
    >
      <el-form
        ref="Form"
        :model="Content"
        label-width="80px"
        label-position="right"
        :rules="rule1"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="Content.name" placeholder="文档名称" />
        </el-form-item>
         
       
        <el-form-item label="文档描述" prop="description">
          <el-input
            type="textarea"
            :rows="4"
            v-model="Content.description"
            placeholder="文档描述"
          />
        </el-form-item>
        <el-form-item label="文档上传" prop="file" v-if="dialogVisible">
          <el-upload
          ref="upload"
          :action="upUrl"
          :on-preview="handlePreview"
          :on-success="handleUpSuccess"
          :on-remove="handleRemove"
          :headers="upHeaders"
          :file-list="fileList"
          :limit="1"
          accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.zip"
        >
          <el-button size="small" type="primary">上传文件</el-button>
        </el-upload>
        </el-form-item>
       
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm('Form')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getPolicyList,
  createPolicy,
  deletePolicy,
  updatePolicy,
} from "@/api/policy";
import checkPermission from "@/utils/permission";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { upUrl, upHeaders } from "@/api/file";
const defaultContent = {
  cate:'政策',
  name: "",
  description: "",
  file:null
};
export default {
  components: { Pagination, Treeselect },
  data() {
    return {
      upHeaders: upHeaders(),
      upUrl: upUrl(),
      fileList:[],
      Content: defaultContent,
      listLoading:false,
      dialogVisible: false,
      listQuery: {
        page: 1,
        cate:'政策',
        search:'',
        page_size: 20,
      },
       contentList: {
        count:0
      },
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
    };
  },
  computed: {},
  watch: {
    filterOrgText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
  
  },
  methods: {
    handleSearch(){
        this.getList(); 
    },
    handlePreview(file) {
      if ("url" in file) {
        window.open(file.url);
      } else {
        window.open(file.response.data.path);
      }
    },
    handleUpSuccess(res, file, filelist) {
      this.Content.file = res.data.id;
      
    },
    handleRemove(file, filelist){
      this.Content.file = null;
    },
    checkPermission,

    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getList() {
     
      getPolicyList(this.listQuery).then((response) => {
        if (response.data) {
          this.contentList = response.data;
        }
      
      });
    },
   

    handleAddContent() {
      this.Content = Object.assign({}, defaultContent);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.fileList=[]
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleEdit(scope) {
      this.Content = Object.assign({}, scope.row); // copy obj
      this.dialogType = "edit";
      this.dialogVisible = true;
      if (this.Content.file) {
        this.fileList = [
          {
            name:this.Content.file_.name,
            url: this.Content.file,
          },
        ];
      }
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deletePolicy(scope.row.id);
          this.getList();
          this.$message.success("成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
    async confirm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
            console.log(this.Content)
            updatePolicy(this.Content.id, this.Content).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("编辑成功");
              }
            });
          } else {
            createPolicy(this.Content).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("新建成功");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
