<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">
      </avue-crud>
      <template slot="picture" slot-scope="scope">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"              
            :show-file-list="false"
            list-type="picture-card"
            :on-success="(res, file) => handleUploadSuccess(res, file, scope)"
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :headers="uploadHeaders"
          >
            <img v-if="scope.row.picture" :src="scope.row.picture" class="avatar" style="width:100%;height:100%;object-fit:contain;" />
            <i v-else class="el-icon-plus"></i>
          </el-upload>
        </template>
    </basic-container>
  </div>
</template>
<script>
import { getList, add, remove, update, getCode } from "@/api/materials/list";
export default {
  data() {
    return {
      form: {
        imageUrl: "",
        picture: ""  // 用于存储接口返回的图片地址
      },
      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',
            headerAlign: "center",
            align: "center",
            slot: true,  // 使用自定义插槽
            add: true,   // 新增时显示
            edit: true,  // 编辑时显示
            view: true,  // 查看时显示
            rules: [{
              required: true,
              message: "请上传图片",
              trigger: "change"
            }]
          },
          // {
          //   label: '图片',
          //   prop: 'picture',
          //   type: 'upload',
          //   headerAlign: "center",
          //   align: "center",
          //   loadText: "图片上传中，请稍等",
          //   span: 12,
          //   // propsHttp: { //配置请求接口返回的数据结构
          //   //   url: 'picture', //路径地址
          //   //   name: 'name', //图片名称
          //   //   res: 'data' //返回数据层级结构
          //   // },
          //   tip: "只能上传jpg/png文件",
          //   rules: [{
          //     required: true,
          //     message: "请上传图片",
          //     trigger: "change",
          //   }],
          //       formatter: (row, column) => {
          //     const value = row.picture;
          //     if (value === null || value === undefined || value === "") {
          //       return "无"
          //     }
          //     return value;
          //   }
          // },
        ],
      },
      data: [],
      dialogLogVisible: false,
      activeName: "first",
      tableData: [],
    };
  },
  mounted() {
    this.tableData = this.ckTable;
    this.fetchMaterialCode();
  },
  methods: {
   
    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) {
      console.log(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>
