<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-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="detailDialog"
      :title="detailForm.type === 0 ? '新增' : '修改'"
    >
      <div class="add_content" slot="content">
        <el-form ref="detailForm" :model="detailForm" :rules="detailFormRules">
          <el-form-item
            label="SDK类型"
            prop="style_name"
            class="inline_form_item"
          >
            <el-input
              v-model="detailForm.style_name"
              placeholder="请填写SDK类型名称，如Java SDK"
            ></el-input>
          </el-form-item>
          <el-form-item label="版本号" prop="version" class="inline_form_item">
            <el-input
              v-model="detailForm.version"
              placeholder="版本号"
            ></el-input>
          </el-form-item>
          <el-form-item label="SDK包上传" prop="file_url">
            <apass-upload
              v-model="detailForm.file_url"
              tip="支持扩展名：.rar .zip"
            ></apass-upload>
          </el-form-item>
        </el-form>
      </div>

      <template slot="action">
        <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: "SDK类型",
          prop: "style_name",
          type: "button",
          width: 240,
        },
        {
          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: "",
        time: "",
      },
      types: [],
      tempFilter: {},
      detailForm: {
        type: 0, // 0：新增 1：修改
        style_name: "",
        version: "",
        file_url: "",
      },
      detailFormRules: {
        style_name: [
          { required: true, message: "请填写SDK类型名称", trigger: "blur" },
          { max: 20, message: "长度应小于20个字符", trigger: "change" },
        ],
      },
      deleteDialogInfo: {
        msg: "",
        submit: null,
      },
      saveSection: false,
      selection: [],
    };
  },
  methods: {
    init(filter) {
      let fullFilter = {
        ...filter,
        ...this.topFilter,
      };

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

      this.$http
        .get("/apaas/support/sdk/styles/list", {
          params: {
            style: fullFilter.type,
            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;
            });
          }
        });

      this.$http.get("/apaas/support/sdk/styleNames/list").then(({ data }) => {
        if (data.success === 1) {
          this.types = data.data || [];
        }
      });
    },
    topFilterClear() {
      this.topFilter = {
        type: "",
        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.style_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_name: "",
        version: "",
        file_url: "",
      };
      this.$refs.detailDialog.show();
    },
    detailCancelAction() {
      this.$refs.detailDialog.hide();
    },
    detailSubmitAction() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          if (this.detailForm.type === 0) {
            this.$http
              .post("/apaas/support/sdk/styles/create", {
                style_name: this.detailForm.style_name,
                version: this.detailForm.version,
                file_url: this.detailForm.file_url,
              })
              .then(({ data }) => {
                if (data.success === 1) {
                  this.$message.success("新增成功");
                  this.refreshPage();
                  this.$refs.detailDialog.hide();
                } else {
                  this.$message.error("新增失败");
                }
              })
              .catch((error) => {
                console.log(error);
                this.$message.error("新增失败");
              });
          } else {
            this.$http
              .put("/apaas/support/sdk/styles/put", {
                id: this.detailForm.id,
                style_name: this.detailForm.style_name,
                version: this.detailForm.version,
                file_url: this.detailForm.file_url,
              })
              .then(({ data }) => {
                if (data.success === 1) {
                  this.$message.success("修改成功");
                  this.refreshPage();
                  this.$refs.detailDialog.hide();
                } else {
                  this.$message.error("修改失败");
                }
              })
              .catch((error) => {
                console.log(error);
                this.$message.error("修改失败");
              });
          }
        } else {
          return false;
        }
      });
    },
    editItem(item) {
      this.detailForm = {
        type: 1,
      };
      this.$http
        .get("/apaas/support/sdk/styles/detail", {
          params: {
            id: item.id,
          },
        })
        .then(({ data }) => {
          if (data.success === 1) {
            this.detailForm = {
              ...data.data,
              type: 1,
            };
          }
        });
      this.$refs.detailDialog.show();
    },
    deleteItem(item) {
      this.deleteDialogInfo.msg = `确认删除${item.style_name}吗？`;
      this.deleteDialogInfo.submit = () => {
        this.deleteRequest([item.id]);
      };
      this.$refs.deleteDialog.show();
    },
    deleteRequest(ids) {
      this.$http
        .delete("/apaas/support/sdk/styles/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("删除失败");
        });
    },
    getTimeText(time) {
      return helper.dateStringTransform(time);
    },
    selectAction(values) {
      if (this.saveSection) {
        return;
      }

      let cleanPage = values.length === 0; // 是否清空当前页所有选中
      let selection = [...this.selection];

      if (cleanPage) {
        selection = selection.filter((item) => {
          return !this.listData.find((v) => {
            return v.id === item.id;
          });
        });
      } else {
        selection.push(...values);
      }

      this.selection = selection;
    },
  },
};
</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;
}
.el-form {
  font-size: 0;
}
.inline_form_item {
  display: inline-block;
  vertical-align: middle;
  width: calc(50% - 10px);
}
.inline_form_item + .inline_form_item {
  margin-left: 20px;
}
</style>
