<template>
  <div class="app-container home">
    
    <div class="home-header">
      <div class="home-header-left">
        <h1>项目列表</h1>
      </div>
      <div class="home-header-right">
        <el-input
          v-model="queryParams.appName"
          class="search-input mr10"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="getList"
        >
          <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
        </el-input>
        <el-button-group class="mr10">
          <el-button :type="curType === 'card' ? 'primary' : 'default'" icon="el-icon-postcard" @click="checkType('card')">卡片</el-button>
          <el-button :type="curType === 'list' ? 'primary' : 'default'" icon="el-icon-notebook-2" @click="checkType('list')">列表</el-button>
        </el-button-group>
        <el-button type="primary" @click="handleAdd(null)">新增项目</el-button>
      </div>
    </div>
    <!-- <transition name="slide-fade"> -->
      <component :is="curType === 'card' ? 'CardView' : 'ListView'"
        :list="list"
        :loading="loading"
        @update="handleAdd"
        @del="handleDelete"
        @enter="handleEnter"
      />
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    <!-- </transition> -->

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" center :before-close="dialogBeforeClose">
      <el-form ref="form" :model="editForm" :rules="rules">
        <el-form-item label="应用名称" label-width="120px" prop="appName">
          <el-input v-model="editForm.appName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="应用描述" label-width="120px" prop="appDesc">
          <el-input v-model="editForm.appDesc" autocomplete="off" type="textarea" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" label-width="120px" prop="picture">
          <ImageUpload v-model="editForm.picture" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { isExternal } from '@/utils/validate'
import CardView from './components/home/card';
import ListView from './components/home/list';
import { getListApi, getListDetail, delList, addList, updateList } from "@/api/system/application";
export default {
  name: "Index",
  components: {
    CardView,
    ListView,
  },
  data() {
    return {
      loading: false,
      curType: 'card',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      list: [],
      dialogFormVisible: false,
      dialogTitle: '新增应用',
      // 表单校验
      rules: {
        appName: [
          { required: true, message: "应用名称不能为空", trigger: "blur" }
        ],
        appDesc: [
          { required: true, message: "应用描述不能为空", trigger: "blur" }
        ],
      },
      editForm: {
        id: null,
        appName: '',
        appDesc: '',
        picture: '',
      },
      submitLoading: false,
    }
  },
  computed: {
    routes() {
      return this.$store.state.permission.addRoutes;
    },
  },
  created() {
    this.$store.dispatch('app/toggleSideBarHide', true);
    this.getList();
  },
  watch: {
    $route(route) {
      this.$store.dispatch('app/toggleSideBarHide', route.path === '/index');
    }
  },
  methods: {
    /** 查询应用列列表 */
    getList() {
      this.loading = true;
      getListApi(this.queryParams).then(response => {
        console.log(response)
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    checkType(type) {
      this.curType = type;
    },
    dialogBeforeClose(done) {
      this.$refs.form.resetFields();
      done();
    },
    dialogClose() {
      this.$refs.form.resetFields();
      this.dialogFormVisible = false;
    },
    // getList(params) {
    //   return new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //       const num = Math.floor(Math.random() * 10);
    //       const ls = new Array(num).fill(0).map((v,i) => {
    //         return {
    //           id: Math.random(),
    //           name: `第${i}个项目名称`,
    //           desc: `第${i}个项目，是一个排名第${i}的项目，是一个四川的项目，同时也是${i}行业相关的项目，并且还是一个充满智慧的项目。`,
    //           createTime: `2024-04-${i + 1}`,
    //           img: "https://img.yzcdn.cn/vant/cat.jpeg",
    //         };
    //       });
    //       return resolve({
    //         code: 200,
    //         data: {
    //           list: ls,
    //           total: 86,
    //         }
    //       });
    //     }, 1000);
    //   });
    // },
    async handleEnter(row) {
      this.$store.dispatch('SetApplication', row);
      let routes = this.routes;
      if (this.routes.length === 0) {
        routes = await this.$store.dispatch('GenerateRoutes');
        this.$router.addRoutes(routes)
      }
      const [first, secound] = routes;
      const route = this.resolvePath(first, first.path);
      this.$router.push(route);
    },
    resolvePath(route, basepath) {
      if (isExternal(basepath)) {
        return basepath;
      }
      const childRoute = route.children && route.children[0];
      if (childRoute) {
        return path.resolve(basepath, childRoute.path);
      }
      return path.resolve(basepath);
    },
    handleAdd(row) {
      if (!row) {
        this.editForm = {
          id: null,
          appName: '',
          appDesc: '',
          picture: '',
        }
        this.dialogTitle = '新增应用';
      } else {
        this.editForm = {
          id: row.id,
          appName: row.appName,
          appDesc: row.appDesc,
          picture: row.picture,
        }
        this.dialogTitle = '编辑应用';
      }
      this.dialogFormVisible = true;
    },
    async handleDelete(row) {
      this.$confirm('此操作将永久删除该应用, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            this.delFunc(row.id).then(done).finally(() => {
              instance.confirmButtonLoading = false;
            })
          } else {
            done();
          }
        }
      });
    },
    async delFunc(id) {
      try {
        const res = await delList(id);
        this.$message.success('删除成功');
        this.getList();
        return res;
      } catch(e) {
        this.$message.error('删除失败');
        return Promise.reject(e);
      }
    },
    /** 提交按钮 */
    async submitForm() {
      await this.$refs["form"].validate();
      
      const data = Object.assign({},this.editForm);
      const request = data.id ? updateList : addList;
      const msg = data.id ? '修改' : '新增';
      this.submitLoading = true;
      try {
        const { code } = await request(data);
        this.$modal.msgSuccess(`${msg}成功！`);
        this.submitLoading = false;
        this.getList();
        this.dialogClose();
      } catch (error) {
        this.$modal.msgSuccess(`${msg}成功！`);
        this.submitLoading = false;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.top-btn {
  display: flex;
  justify-content: flex-end;
}
.home-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .search-input {
    width: 240px;
  }
}
/* slide-fade 过渡效果的 CSS 类定义 */
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.8s ease;
}
.slide-fade-leave-active {
  position: absolute;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(-100%); /* 左滑出效果，若需右滑入则改为 translateX(100%) */
  opacity: 0;
}

.slide-fade-enter-to,
.slide-fade-leave-from {
  transform: translateX(0);
  opacity: 1;
}
</style>