<template>
  <div>
    <basic-container>
      <avue-crud
        :option="option"
        v-model="form"
        :data="data"
        @row-del="rowDel"
        @on-load="onLoad"
        :table-loading="loading"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @search-change="searchChange"
        @search-reset="searchReset"
        :page.sync="page"
        :upload-after="uploadAfter"
      >
        <template slot="pictureImg" slot-scope="scope">
          <!-- {{scope.row.picture}} -->
          <el-image
            style="width: 60px; height: 60px"
            :src="scope.row.picture"
            fit="fill"
          ></el-image>
        </template>
      </avue-crud>
    </basic-container>
  </div>
</template>
<script>
import { getList, add, remove, update, getCode } from "@/api/materials/list";
import { upload } from "@/api/materials/index";
export default {
  data() {
    return {
      selectionList: [],
      query: {},
      loading: true,
      codeList: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 18,
        border: true,
        index: true,
        selection: true,
        viewBtn: true,
        dialogClickModal: false,
        menu: true,
        selection: false,
        printBtn: false,
        refreshBtn: false,
        gridBtn: false,
        gridBackgroundImage: false,
        gridSpan: false,
        filterBtn: false,
        columnBtn: false,
        menuAlign: "center",
        searchMenuPosition: "right",
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        column: [
          {
            label: "物资名称",
            prop: "materialName",
            search: true,
            headerAlign: "center",
            align: "center",
          },
          {
            label: "规格/型号",
            prop: "model",
            headerAlign: "center",
            align: "center",
          },
          {
            label: "物资编码",
            prop: "materialCode",
            type: "select",
            headerAlign: "center",
            align: "center",
            dicData: [],
            props: {
              label: "label",
              value: "value",
            },
            dataType: "string",
          },
          {
            label: "单位",
            prop: "unit",
            headerAlign: "center",
            align: "center",
          },
          {
            label: "描述",
            prop: "remark",
            headerAlign: "center",
            align: "center",
            formatter: (row, column) => {
              const value = row.remark;
              if (value === null || value === undefined || value === "") {
                return "无";
              }
              return value;
            },
          },
          {
            label: "图片",
            prop: "picture",
            type: "upload",
            headerAlign: "center",
            align: "center",
            loadText: "图片上传中，请稍等",
            span: 12,
            tip: "只能上传jpg/png文件",
            hide: true,
            httpRequest: this.handleUpload,
          },
          {
            label: "图片",
            prop: "pictureImg",
            span: 12,
            display: false,
          },
        ],
      },
      data: [],
      dialogLogVisible: false,
      activeName: "first",
      tableData: [],
    };
  },
  mounted() {
    this.tableData = this.ckTable;
    this.fetchMaterialCode();
  },
  methods: {
    uploadAfter(res, done, loading, column) {
      console.log("上传成功", res, done, loading, column);
    },
    handleUpload(params) {
      const formData = new FormData();
      formData.append("file", params.file);
      upload(formData)
        .then((res) => {
          this.form.picture = res.data.message;
          params.onSuccess(res);
        })
        .catch((err) => {
          params.onError(err);
        });
    },
    fetchMaterialCode() {
      getCode()
        .then((res) => {
          const dicData = res.data.result.map((item) => ({
            label: item.name,
            value: item.code,
          }));
          const targetColumn = this.option.column.find(
            (col) => col.prop === "materialCode"
          );
          if (targetColumn) {
            targetColumn.dicData = dicData;
          }
        })
        .catch((error) => {
          this.$message.error("加载类别数据失败，请刷新重试");
        });
    },
    handleLog() {
      this.dialogLogVisible = true;
    },
    handleTabClick(tab, event) {
      if (this.activeName == "first") {
        this.tableData = this.ckTable;
      }
      if (this.activeName == "second") {
        this.tableData = this.rkTable;
      }
      if (this.activeName == "third") {
        this.tableData = this.bfTable;
      }
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    //新增
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    //修改
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done(row);
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    //删除
    rowDel(row, index, done) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id.toString());
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        })
        .catch((action) => {
          if (action !== "cancel") {
            this.$message({
              type: "error",
              message: "操作失败",
            });
          }
        });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        this.data = res.data.result.list;
        this.loading = false;
        this.page.total = res.data.result.total;
        // this.selectionClear();
      });
      this.loading = false;
    },
  },
};
</script>
