<template>
  <div class="type page_container">
    <el-button class="btn-create" type="primary" @click="handleCreate" size="small" v-if="hasCreate"
      >新建类型</el-button
    >
    <el-tabs v-model="activeName" type="card" tab-click="handleTabClick">
      <el-tab-pane label="项目类型" name="0" lazy>
        <table-list v-bind="projectTableOptions" ref="tableList" @selection-change="handleSelectionChange" v-if="activeName === '0'">
          <!-- 项目Id -->
          <template v-slot:table-id="{ row }"
            ><p class="details-handle" @click="handleDetails(row)">{{ row.id }}</p></template
          >
          <!-- 创建人 -->
          <template v-slot:table-creater="{ row }"
            ><p>{{ row.sso_user.realname || row.sso_user.nickname }}</p></template
          >
          <!-- 状态 -->
          <template v-slot:table-status="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="停用"
              @change="statusChange(row)"
              :disabled="!hasCreate"
            ></el-switch>
          </template>
          <template #footer>
            <el-button size="mini" :disabled="!multipleSelection.length" @click="handleRemove" v-if="hasDelete"
              >删除</el-button
            >
          </template>
        </table-list>
      </el-tab-pane>
      <el-tab-pane label="内容类型" name="1" lazy>
        <table-list v-bind="contentTableOptions" ref="tableList" @selection-change="handleSelectionChange" v-if="activeName === '1'">
          <!-- 项目Id -->
          <template v-slot:table-id="{ row }"
            ><p class="details-handle" @click="handleDetails(row)">{{ row.id }}</p></template
          >
          <!-- 创建人 -->
          <template v-slot:table-creater="{ row }"
            ><p>{{ row.sso_user.realname || row.sso_user.nickname }}</p></template
          >
          <!-- 创建人 -->
          <template v-slot:table-category="{ row }"
            ><p>{{ row.category | categoryFilter }}</p></template
          >
          <!-- 状态 -->
          <template v-slot:table-status="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="停用"
              @change="statusChange(row)"
              :disabled="!hasCreate"
            ></el-switch>
          </template>
          <template #footer>
            <el-button size="mini" :disabled="!multipleSelection.length" @click="handleRemove" v-if="hasDelete"
              >删除</el-button
            >
          </template>
        </table-list>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="440px"
      @close="handleDialogClose"
      :destroy-on-close="true"
    >
      <el-form :model="form" label-width="110px" ref="dialogForm" class="dialog-form">
        <template v-if="activeName === '0'">
          <el-form-item
            label="项目类型名称"
            prop="name"
            :rules="{ required: true, message: '请输入项目类型名称', trigger: 'blur' }"
          >
            <el-input v-model="form.name" size="small"></el-input>
          </el-form-item>
          <el-form-item
            v-if="dialogType === 'create'"
            label="参数ID为："
            prop="tag"
            :rules="{ required: true, message: '请输入参数ID', trigger: 'blur' }"
          >
            <el-input v-model="form.tag" size="small"></el-input>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item
            label="内容类型为："
            prop="category"
            :rules="[{ required: true, message: '请选择内容类型', trigger: 'change' }]"
          >
            <el-select v-model="form.category" placeholder="请选择类型" size="small" style="width: 100%">
              <el-option :label="item.name" :value="item.id" v-for="item in contentTypeList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="dialogType === 'create'"
            label="参数ID为："
            prop="tag"
            :rules="{ required: true, message: '请输入参数ID', trigger: 'blur' }"
          >
            <el-input v-model="form.tag" size="small"></el-input>
          </el-form-item>
          <el-form-item
            label="类型名称为："
            prop="name"
            :rules="{ required: true, message: '请输入类型名称', trigger: 'blur' }"
          >
            <el-input v-model="form.name" size="small"></el-input>
          </el-form-item>
        </template>
      </el-form>
      <span slot="footer">
        <el-button @click="handleDialogClose" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleDialogSubmit" size="mini">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import TableList from '@/components/TableList'
import { getTypeList, createType, updateType, batchDeleteType } from '@/api/settings.js'
const defaultForm = {
  name: '',
  category: '',
  tag: ''
}
export default {
  components: { TableList },
  data() {
    return {
      activeName: '0',

      contentTypeList: [
        { id: 1, name: '文章' },
        { id: 2, name: '广告' },
        { id: 3, name: '图文' }
      ],
      dialogVisible: false,
      dialogType: '',
      form: Object.assign({}, defaultForm),
      selectedId: '',
      multipleSelection: []
    }
  },
  computed: {
    // 权限列表
    permissions() {
      return this.$store.state.user.permissions || []
    },
    // 创建权限
    hasCreate() {
      return this.permissions.includes('setting-function-type-create')
    },
    // 删除权限
    hasDelete() {
      return this.permissions.includes('setting-function-type-delete')
    },
    // 项目类型
    projectTableOptions() {
      return {
        remote: {
          httpRequest: getTypeList,
          params: { type: 0 }
        },
        columns: [
          { type: 'selection', visible: this.hasDelete },
          { prop: 'id', label: '项目类型ID', slots: 'table-id', minWidth: '150px' },
          { prop: 'name', label: '项目类型', minWidth: '150px' },
          { prop: 'sso_user', label: '创建人', slots: 'table-creater', minWidth: '100px' },
          { prop: 'created_at', label: '创建时间', minWidth: '150px' },
          { prop: 'tag', label: '参数ID', minWidth: '80px' },
          { prop: 'status', label: '状态', slots: 'table-status', minWidth: '150px' }
        ]
      }
    },
    // 内容类型
    contentTableOptions() {
      return {
        remote: {
          httpRequest: getTypeList,
          params: { type: 1 }
        },
        columns: [
          { type: 'selection', visible: this.hasDelete },
          { prop: 'id', label: '内容ID', slots: 'table-id', minWidth: '150px' },
          { prop: 'name', label: '类型名称', minWidth: '150px' },
          { prop: 'category', label: '内容类型', slots: 'table-category', minWidth: '80px' },
          { prop: 'sso_user', label: '创建人', slots: 'table-creater' },
          { prop: 'created_at', label: '创建时间', minWidth: '150px' },
          { prop: 'tag', label: '参数ID', minWidth: '100px' },
          { prop: 'status', label: '状态', slots: 'table-status', minWidth: '150px' }
        ]
      }
    },
    dialogTitle() {
      let text = this.dialogType === 'create' ? '新建' : '修改'
      text += this.activeName === '0' ? '项目' : '内容'
      return text + '类型'
    }
  },
  filters: {
    categoryFilter(val) {
      let text = '广告'
      switch (val) {
        case 1:
          text = '文章'
          break
        case 3:
          text = '图文'
          break
      }
      return text
    }
  },
  methods: {
    handleTabClick() {
      this.multipleSelection = []
    },
    // 选择
    handleSelectionChange(value) {
      this.multipleSelection = value
    },
    // 删除
    handleRemove() {
      const ids = this.multipleSelection.map(item => item.id)
      batchDeleteType({ ids }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.$refs.tableList.refetch(true)
          // 刷新用户user_detail
          this.$store.dispatch('checkRolesPermissions')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleCreate() {
      this.dialogType = 'create'
      this.dialogVisible = true
    },
    handleDetails(val) {
      if (this.hasCreate) {
        this.dialogType = 'edit'
        this.dialogVisible = true
        this.selectedId = val.id
        this.form = {
          name: val.name,
          category: val.category
        }
      }
    },
    handleDialogClose() {
      this.dialogVisible = false
      this.form = Object.assign({}, defaultForm)
    },
    handleDialogSubmit() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          if (this.dialogType === 'create') {
            this.fetchCreateType()
          } else {
            const params = { ...this.form }
            delete params.tag
            params.type_id = this.selectedId
            this.fetchUpdateType(params, 'name')
          }
        } else {
          return false
        }
        this.handleDialogClose()
      })
    },
    statusChange(val) {
      this.fetchUpdateType(
        {
          type_id: val.id,
          status: val.status
        },
        'status'
      )
    },
    fetchCreateType() {
      const params = { ...this.form }
      !params.category && (params.category = 0)
      params.type = this.activeName === '0' ? 0 : 1
      createType(params)
        .then(res => {
          if (res.code === 0 && res.data && res.data.id) {
            this.$refs.tableList.refetch()
            this.$message.success('新建类型成功')
          } else {
            this.$message.error(res.message || '新建类型失败')
          }
        })
        .catch(() => {
          this.$message.error('新建类型失败')
        })
    },
    fetchUpdateType(data, type) {
      const msg = type === 'status' ? '更改状态' : '更改类型名称'
      updateType(data)
        .then(res => {
          if (res.code === 0 && res.data && res.data.status) {
            this.$message.success(msg + '成功')
            this.$refs.tableList.refetch()
            // 刷新用户user_detail
            if (type === 'status') this.$store.dispatch('checkRolesPermissions')
          } else {
            this.$message.error(res.message || msg + '失败')
          }
        })
        .catch(() => {
          this.$message.error(msg + '失败')
        })
    }
  }
}
</script>
<style scoped>
.type {
  box-sizing: border-box;
  padding: 15px;
  position: relative;
}
.btn-create {
  position: absolute;
  right: 20px;
  top: 16px;
  z-index: 1;
}
.el-tabs {
  height: 100%;
}
.el-tabs ::v-deep.el-tabs__content {
  height: calc(100% - 56px);
}
.el-tab-pane {
  height: 100%;
}
.table-list .table-list-bd {
  height: 100%;
}
</style>
