<template>
  <div class="app-container">
    <el-card>
      <el-button type="primary" icon="el-icon-plus" @click="handleAddContent"
        >新增</el-button
      >
    </el-card>
    <el-card style="margin-top: 10px">
      <el-table
        v-loading="listLoading"
        :data="contentList"
        border
        fit
        stripe
        highlight-current-row
        max-height="600"
      >
        <el-table-column type="index" width="50" />
        <el-table-column label="名称">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="详情">
          <template slot-scope="scope">{{ scope.row.desc }}</template>
        </el-table-column>

        <el-table-column label="材料类型">
          <template slot-scope="scope">{{ scope.row.type_ }}</template>
        </el-table-column>

        <el-table-column align="center" label="是否可主动报送">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.can_doself">是</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="模板">
          <template slot-scope="scope" v-if="scope.row.template">
            <el-link :href="scope.row.template" type="primary">下载</el-link>
          </template>
        </el-table-column>
        <el-table-column label="排序号">
          <template slot-scope="scope">{{ scope.row.sortnum }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="200px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              :disabled="!checkPermission(['content'])"
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
            />
            <el-button
              :disabled="!checkPermission(['content'])"
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
            />
          </template>
        </el-table-column>
      </el-table>
    </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="type">
          <el-cascader
            v-model="Content.type"
            :options="typeOptions"
            :props="{ emitPath: false }"
            clearable
            style="width: 100%"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="详情" prop="desc">
          <el-input
            type="textarea"
            :rows="4"
            v-model="Content.desc"
            placeholder="详情"
          />
        </el-form-item>
        <el-form-item label="模板" prop="template" 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"
        >
          <el-button size="small" type="primary">上传文件</el-button>
        </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="Content.sortnum"
            :min="1"
            :max="999"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="是否可主动报送"
          prop="can_doself"
          label-width="120px"
        >
          <el-switch v-model="Content.can_doself"></el-switch>
        </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 {
  getContentList,
  createContent,
  deleteContent,
  updateContent,
} from "@/api/content";
import { genTree } from "@/utils";
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 { getDictList, getDictTypeList } from "@/api/dict";
import { upUrl, upHeaders } from "@/api/file";
const defaultContent = {
  name: "",
  desc: "",
  sortnum:1,
  type: null,
  can_doself: false,
  template: null
};
export default {
  components: { Pagination, Treeselect },
  data() {
    return {
      upHeaders: upHeaders(),
      upUrl: upUrl(),
      fileList:[],
      Content: defaultContent,
      contentList: [],
      typeOptions: [],
      listLoading: true,
      dialogVisible: false,
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      filterOrgText: "",
      treeLoding: false,
    };
  },
  computed: {},
  watch: {
    filterOrgText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTypeAll();
  },
  methods: {
    handlePreview(file) {
      if ("url" in file) {
        window.open(file.url);
      } else {
        window.open(file.response.data.path);
      }
    },
    handleUpSuccess(res, file, filelist) {
      this.Content.template = res.data.path;
    },
    handleRemove(file, filelist){
      this.Content.template = null;
    },
    checkPermission,

    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    getList() {
      this.listLoading = true;
      getContentList().then((response) => {
        if (response.data) {
          this.contentList = response.data;
        }
        this.listLoading = false;
      });
    },
    getTypeAll() {
      getDictList({ type__code: "data_type" }).then((res) => {
        this.typeOptions = genTree(res.data);
      });
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    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.template) {
        this.fileList = [
          {
            name:'清单模板',
            url: this.Content.template,
          },
        ];
      }
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteContent(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) {
            updateContent(this.Content.id, this.Content).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          } else {
            createContent(this.Content).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
