<template>
  <div class="list_container">
    <apass-list
      ref="list"
      search-placeholder="请输入关键字"
      :list-padding-left="paddingLeft"
      :hide-search="true"
      :list-total="listTotal"
      :list-header="listHeader"
      :list-data="listData"
      :list-select="true"
      @list-action="init"
      @list-select="selectAction"
    >
      <el-breadcrumb separator="/" slot="breadcrumb">
        <el-breadcrumb-item to="/technical_support">
          技术支持
        </el-breadcrumb-item>
        <el-breadcrumb-item to="/technical_support/doc_manage">
          SDK管理
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          SDK示例管理
        </el-breadcrumb-item>
      </el-breadcrumb>

      <template slot="top">
        <div class="top_fliter">
          <show-more-filter class="filter_list">
            <div class="filter_item">
              <span class="filter_title">SDK类型：</span>
              <el-select v-model="topFilter.type" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="(item, index) in types"
                  :key="'top_type_' + index"
                  :label="item.style_name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
            <div class="filter_item">
              <span class="filter_title">示例名称：</span>
              <el-input
                v-model="topFilter.name"
                placeholder="请输入示例名称"
              ></el-input>
            </div>
            <div class="filter_item">
              <span class="filter_title">最后更新时间：</span>
              <el-date-picker
                v-model="topFilter.time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </div>
          </show-more-filter>
          <div class="filter_action apaas_button">
            <el-button type="primary" @click="topFilterAction">
              查询
            </el-button>
            <el-button type="defalut" @click="topFilterClear">
              重置
            </el-button>
          </div>
        </div>
      </template>

      <div class="main_top_action apaas_button" slot="main-top">
        <el-button class="delete_btn" type="danger" @click="deleteSlection">
          批量删除
        </el-button>
        <span class="selected_text">
          已选择
          <span>{{ selection.length }}</span>
          项
        </span>
        <a class="clean_btn" @click.prevent="clearSelection">清空</a>
        <el-button class="add_btn" type="primary" @click="addNewSdk">
          新增SDK示例
        </el-button>
      </div>
    </apass-list>

    <apass-dialog
      ref="viewDialog"
      :title="detailForm.example_name"
      class="sdk_manage_detail_dialog"
      width="1340px"
    >
      <div
        class="view_content w-e-text w-e-text-container apaas_scroll"
        slot="content"
        v-html="detailForm.content"
      ></div>
    </apass-dialog>

    <apass-dialog
      ref="detailDialog"
      :title="detailForm.type === 0 ? '新增' : '修改'"
    >
      <div class="detail_content" slot="content">
        <div class="detail_notice">
          <p>注：同一SDK类型下可维护多个示例名称</p>
        </div>
        <el-form ref="detailForm" :model="detailForm" :rules="detailFormRules">
          <el-form-item label="SDK类型" prop="style_id">
            <el-select
              v-model="detailForm.style_id"
              placeholder="请选择SDK类型"
              style="width: 100%;"
            >
              <el-option
                v-for="(item, index) in types"
                :key="'detail_type_' + index"
                :label="item.style_name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="示例名称" prop="example_name">
            <el-input
              v-model="detailForm.example_name"
              placeholder="请输入示例名称"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <template slot="action">
        <el-button
          type="primary"
          size="mini"
          @click="detailEditContent"
          style="float: left;"
          v-if="detailForm.type === 1"
        >
          修改文档
        </el-button>
        <el-button type="defalut" size="mini" @click="detailCancelAction">
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="detailSubmitAction">
          确定
        </el-button>
      </template>
    </apass-dialog>

    <apass-dialog
      ref="deleteDialog"
      :msg="deleteDialogInfo.msg"
      :submit="deleteDialogInfo.submit"
    ></apass-dialog>
  </div>
</template>

<script>
import helper from "@/services/helper.js";
import apassList from "@/components/apass-list";
import apassDialog from "@/components/apass-dialog";
import apassUpload from "@/components/apass-upload";
import showMoreFilter from "@/components/show-more-filter";

export default {
  components: {
    apassList,
    apassDialog,
    apassUpload,
    showMoreFilter,
  },
  data() {
    return {
      paddingLeft: 0,
      listTotal: 0,
      listHeader: [
        {
          label: "示例名称",
          prop: "example_name",
          type: "button",
          callback: this.viewItem,
          width: 320,
        },
        {
          label: "SDK类型",
          prop: "style_name",
          align: "center",
        },
        {
          label: "版本号",
          prop: "version",
          align: "center",
        },
        {
          label: "是否提供SDK包下载",
          prop: "is_sdk",
          align: "center",
        },
        {
          label: "操作人",
          prop: "user_name",
          align: "center",
        },
        {
          label: "最后更新时间",
          prop: "updated",
          getText: ({ updated }) => this.getTimeText(updated || ""),
          align: "center",
        },
        {
          label: "操作",
          type: "buttons",
          align: "center",
          width: 240,
          actionList: [
            {
              label: "修改",
              callback: this.editItem,
            },
            {
              label: "删除",
              callback: this.deleteItem,
              class: "warn",
            },
          ],
        },
      ],
      listData: [],
      topFilter: {
        type: "",
        name: "",
        time: "",
      },
      types: [],
      tempFilter: {},
      detailForm: {
        type: 0, // 0：新增 1：修改
        style_id: "",
        example_name: "",
        content: "",
      },
      detailFormRules: {
        style_id: [
          { required: true, message: "请选择SDK类型", trigger: "change" },
        ],
        example_name: [
          { required: true, message: "请输入示例名称", trigger: "blur" },
          { max: 20, message: "长度应小于20个字符", trigger: "change" },
        ],
      },
      deleteDialogInfo: {
        msg: "",
        submit: null,
      },
      saveSection: false,
      selection: [],
    };
  },
  created() {
    this.getTypes();
  },
  methods: {
    init(filter) {
      let fullFilter = {
        ...filter,
        ...this.topFilter,
      };

      this.tempFilter = filter;
      this.saveSection = true;

      this.$http
        .get("/apaas/support/sdk/example/list", {
          params: {
            style: fullFilter.type,
            name: fullFilter.name,
            start: fullFilter.time && fullFilter.time[0],
            end: fullFilter.time && fullFilter.time[1],
            limit: fullFilter.size,
            page: fullFilter.page,
          },
        })
        .then(({ data }) => {
          if (data.success === 1) {
            this.listTotal = data.total;
            this.listData = data.data || [];

            this.$nextTick(() => {
              this.selection.forEach((item) => {
                let target = this.listData.find((v) => v.id === item.id);

                if (target) {
                  this.setCurrentRow(target, true);
                }
              });
              this.saveSection = false;
            });
          }
        });
    },
    getTypes() {
      this.$http.get("/apaas/support/sdk/styleNames/list").then(({ data }) => {
        if (data.success === 1) {
          this.types = data.data || [];
        }
      });
    },
    topFilterClear() {
      this.topFilter = {
        type: "",
        name: "",
        time: "",
      };
      this.refreshPage();
    },
    topFilterAction() {
      this.refreshPage();
    },
    refreshPage() {
      this.$refs.list.resetCurrentPage();
    },
    deleteSlection() {
      if (this.selection.length) {
        let names = [];
        let ids = [];

        this.selection.forEach((item) => {
          names.push("《" + item.example_name + "》");
          ids.push(item.id);
        });

        this.deleteDialogInfo.msg = `您确认要删除${names.join("、")}吗？`;
        this.deleteDialogInfo.submit = () => {
          this.deleteRequest(ids);
        };
        this.$refs.deleteDialog.show();
      } else {
        this.$message.closeAll();
        this.$message.warning("您尚未选中任何SDK示例");
      }
    },
    clearSelection() {
      this.$refs.list.clearSelection();
    },
    setCurrentRow(row, flag) {
      this.$refs.list.setSelectedRow(row, flag);
    },
    addNewSdk() {
      this.detailForm = {
        type: 0,
        style_id: (this.types[0] && this.types[0].id) || "",
        example_name: "",
        content: "",
      };
      this.$refs.detailDialog.show();
    },
    viewItem(item) {
      this.detailForm = {
        type: 1,
      };
      this.detailRequest(item.id);
      this.$refs.viewDialog.show();
    },
    editItem(item) {
      this.detailRequest(item.id);
      this.$refs.detailDialog.show();
    },
    deleteItem(item) {
      this.deleteDialogInfo.msg = `确认删除《${item.example_name}》吗？`;
      this.deleteDialogInfo.submit = () => {
        this.deleteRequest([item.id]);
      };
      this.$refs.deleteDialog.show();
    },
    getTimeText(time) {
      return helper.dateStringTransform(time);
    },
    selectAction(values) {
      // 页码操作需要保存所选项
      if (this.saveSection) {
        return;
      }

      let selection = [...this.selection];

      selection = selection.filter((item) => {
        return !this.listData.find((v) => {
          return v.id === item.id;
        });
      });

      selection.push(...values);

      this.selection = selection;
    },
    detailEditContent() {
      this.$router.push({
        name: "technicalSupportSdkExampleDetail",
        params: {
          id: this.detailForm.id,
        },
      });
    },
    detailCancelAction() {
      this.$refs.detailDialog.hide();
    },
    detailSubmitAction() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          if (this.detailForm.type === 0) {
            this.addRequest(
              {
                style_id: this.detailForm.style_id,
                example_name: this.detailForm.example_name,
                content: this.detailForm.content,
              },
              (data) => {
                this.$router.push({
                  name: "technicalSupportSdkExampleDetail",
                  params: {
                    id: data.id,
                  },
                });
              }
            );
          } else {
            this.editRequest(
              {
                id: this.detailForm.id,
                style_id: this.detailForm.style_id,
                example_name: this.detailForm.example_name,
                content: this.detailForm.content,
              },
              () => {
                this.refreshPage();
                this.$refs.detailDialog.hide();
              }
            );
          }
        } else {
          return false;
        }
      });
    },
    detailRequest(id) {
      this.$http
        .get("/apaas/support/sdk/example/detail", {
          params: {
            id: id,
          },
        })
        .then(({ data }) => {
          if (data.success === 1) {
            this.detailForm = {
              ...data.data,
              type: 1,
            };
          }
        });
    },
    deleteRequest(ids) {
      this.$http
        .delete("/apaas/support/sdk/example/delete", {
          body: {
            ids: ids,
          },
        })
        .then(({ data }) => {
          if (data.success === 1) {
            this.$message.success("删除成功");
            this.selection = [];
            this.refreshPage();
          } else {
            this.$message.error("删除失败");
          }
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("删除失败");
        });
    },
    addRequest(data, callback) {
      this.$http
        .post("/apaas/support/sdk/example/create", data)
        .then(({ data }) => {
          if (data.success === 1) {
            this.$message.success("新增成功");
            typeof callback === "function" && callback(data.data);
          } else {
            this.$message.error(data.errMsg || "新增失败");
          }
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("新增失败");
        });
    },
    editRequest(data, callback) {
      this.$http
        .put("/apaas/support/sdk/example/put", data)
        .then(({ data }) => {
          if (data.success === 1) {
            this.$message.success("修改成功");
            typeof callback === "function" && callback();
          } else {
            this.$message.error(data.errMsg || "修改失败");
          }
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("修改失败");
        });
    },
  },
};
</script>

<style>
.list_container {
  height: 100%;
}
.main_top_action {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.main_top_action .selected_text {
  font-size: 14px;
  color: #8890a7;
  margin-left: 30px;
}
.main_top_action .selected_text > span {
  font-weight: bold;
  color: #242c43;
  margin: 0 3px;
}
.main_top_action .clean_btn {
  font-size: 14px;
  line-height: 24px;
  color: #2b4695;
  text-decoration: underline;
  cursor: pointer;
  user-select: none;
  margin-left: 30px;
}
.main_top_action .add_btn {
  margin-left: auto;
}
.view_content {
  height: 650px;
  overflow: auto;
  text-align: left;
}
.detail_notice {
  display: inline-block;
  margin: 10px auto;
  background-color: #f4f7fc;
  border-radius: 8px;
  padding: 10px;
}
.detail_notice > p {
  font-size: 12px;
  line-height: 16px;
  color: #58617a;
  padding-left: 20px;
  background-image: url("../../../../assets/imgs/ic_tishi.png");
  background-repeat: no-repeat;
  background-position: left center;
}
</style>

<style>
.sdk_manage_detail_dialog .el-dialog__body {
  padding: 15px;
}
.sdk_manage_detail_dialog .el-dialog__footer {
  display: none;
}
</style>
