<template>
  <div class="project page_container">
    <table-list v-bind="tableOptions" ref="tabList" @selection-change="handleSelectionChange">
      <template #header-aside>
        <el-button type="primary" size="mini" @click="handleCreate" v-if="hasCreate">新建项目</el-button>
      </template>
      <!-- 项目Id -->
      <template v-slot:project_id="scope"
        ><span class="details-handle" @click="handleDetails(scope.row)">{{ scope.row.id }}</span></template
      >
      <!-- 状态 -->
      <template v-slot: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-drawer ref="drawer" :visible.sync="drawerVisible" size="490px" @close="handleDrawerClose">
      <template slot="title">
        <h5>
          {{ drawerTitle }}
          <el-button
            v-if="drawerType !== 'create' && hasCreate"
            type="primary"
            @click="drawerType = 'edit'"
            size="mini"
            style="float: right; margin-right: 30px"
            >编辑</el-button
          >
        </h5>
      </template>
      <div class="drawer__content">
        <el-form
          :model="form"
          :rules="rules"
          ref="drawerForm"
          label-width="80px"
          class="drawer-form"
          :disabled="isDetails"
        >
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="form.name" size="small"></el-input>
          </el-form-item>
          <el-form-item label="项目简称" prop="short_name">
            <el-input v-model="form.short_name" size="small"></el-input>
          </el-form-item>
          <el-form-item label="项目类型" prop="type_id">
            <el-select v-model="form.type_id" placeholder="请选择项目类型" size="small" style="width: 100%">
              <el-option :label="item.name" :value="item.id" v-for="item in projectTypeList" :key="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="项目网址" prop="project_uri">
            <el-input v-model="form.project_uri" size="small"></el-input>
          </el-form-item>
          <el-form-item label="广告类型" style="margin-bottom: 0">
            <el-checkbox
              :indeterminate="adType.isIndeterminate"
              v-model="adType.checkAll"
              @change="val => handleCheckAllChange(val, 'adType')"
              >全选</el-checkbox
            >
            <div style="margin: 2px 0"></div>
            <el-checkbox-group v-model="form.adType" @change="val => handleCheckedChange(val, 'adType')">
              <el-checkbox v-for="item in adTypeList" :label="item.id" :key="item.id">{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="文章类型" style="margin-bottom: 0">
            <el-checkbox
              :indeterminate="articleType.isIndeterminate"
              v-model="articleType.checkAll"
              @change="val => handleCheckAllChange(val, 'articleType')"
              >全选</el-checkbox
            >
            <div style="margin: 2px 0"></div>
            <el-checkbox-group v-model="form.articleType" @change="val => handleCheckedChange(val, 'articleType')">
              <el-checkbox v-for="item in articleTypeList" :label="item.id" :key="item.id">{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="图文类型" style="margin-bottom: 0">
            <el-checkbox
              :indeterminate="imageTextType.isIndeterminate"
              v-model="imageTextType.checkAll"
              @change="val => handleCheckAllChange(val, 'imageTextType')"
              >全选</el-checkbox
            >
            <div style="margin: 2px 0"></div>
            <el-checkbox-group v-model="form.imageTextType" @change="val => handleCheckedChange(val, 'imageTextType')">
              <el-checkbox v-for="item in imageTextTypeList" :label="item.id" :key="item.id">{{
                item.name
              }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div class="drawer__footer" v-if="drawerType !== 'details'">
          <el-button @click="handleDrawerClose" size="mini">取 消</el-button>
          <el-button type="primary" @click="handleDrawerSubmit" size="mini">提 交</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import TableList from '@/components/TableList'
import { mapGetters } from 'vuex'
import {
  getProjectList,
  getTypeList,
  getContentTypesList,
  createProject,
  updateProject,
  deleteProject
} from '@/api/settings'
const defaultForm = {
  name: '',
  short_name: '',
  type_id: '',
  project_uri: '',
  adType: [],
  articleType: [],
  imageTextType: []
}
const checkboxStatus = {
  isIndeterminate: false,
  checkAll: false
}
export default {
  components: { TableList },
  data() {
    return {
      activeName: '0',
      statusList: [
        { id: '1', name: '启用' },
        { id: '0', name: '停用' }
      ],
      selectedItem: {},
      drawerVisible: false,
      drawerType: '',
      form: Object.assign({}, defaultForm),
      rules: {
        name: { required: true, message: '请输入项目名称', trigger: 'blur' },
        short_name: { required: true, message: '请输入项目简称', trigger: 'blur' },
        type_id: { required: true, message: '请输入项目类型', trigger: 'blur' },
        project_uri: { required: true, message: '请输入项目网址', trigger: 'blur' }
      },
      projectTypeList: [],
      adTypeList: [],
      articleTypeList: [],
      imageTextTypeList: [],
      adType: Object.assign({}, checkboxStatus),
      articleType: Object.assign({}, checkboxStatus),
      imageTextType: Object.assign({}, checkboxStatus),
      multipleSelection: []
    }
  },
  computed: {
    ...mapGetters(['projects']),
    userProjectIds() {
      return this.projects.map(item => item.id)
    },
    // 权限列表
    permissions() {
      return this.$store.state.user.permissions || []
    },
    // 创建权限
    hasCreate() {
      return this.permissions.includes('setting-function-project-create')
    },
    // 删除权限
    hasDelete() {
      return this.permissions.includes('setting-function-project-delete')
    },
    isDetails() {
      return this.drawerType === 'details'
    },
    drawerTitle() {
      const type = this.drawerType
      let text = ''
      if (type === 'create') text = '新建项目'
      else if (type === 'edit') text = '编辑项目'
      else text = this.selectedItem.name || '项目详情'
      return text
    },
    tableOptions() {
      return {
        remote: {
          httpRequest: getProjectList,
          params: { name: '', type_id: '', status: null }
        },
        filters: [
          {
            type: 'select',
            placeholder: '项目类型',
            prop: 'type_id',
            options: this.projectTypeList,
            labelKey: 'name',
            valueKey: 'id'
          },
          { type: 'input', placeholder: '项目ID/项目名称', prop: 'name' },
          {
            type: 'select',
            placeholder: '状态',
            prop: 'status',
            options: this.statusList,
            labelKey: 'name',
            valueKey: 'id'
          }
        ],
        columns: [
          { type: 'selection', minWidth: '50px', fixed: 'left', visible: this.hasDelete },
          { prop: 'id', label: '项目ID', slots: 'project_id', minWidth: '160px', fixed: 'left' },
          { prop: 'name', label: '项目名称', minWidth: '150px', fixed: 'left' },
          { prop: 'short_name', label: '项目简称', minWidth: '150px' },
          { prop: 'type.name', label: '项目类型', minWidth: '150px' },
          { prop: 'project_uri', label: '项目网址', minWidth: '150px' },
          { prop: 'sso_user.nickname', label: '创建人', minWidth: '150px' },
          { prop: 'created_at', label: '创建时间', minWidth: '150px' },
          { prop: 'status', label: '状态', slots: 'status', minWidth: '150px', fixed: 'right' }
        ],
        bodyHeight: 'calc(100% - 50px)'
      }
    }
  },
  created() {
    this.fetchProjectTypeList()
    this.fetchContentTypeList()
  },
  methods: {
    handleCreate() {
      this.drawerVisible = true
      this.drawerType = 'create'
    },
    handleDetails(val) {
      this.selectedItem = Object.assign({}, val)
      this.drawerVisible = true
      this.drawerType = 'details'
      Object.keys(this.form).forEach(key => {
        const valItem = val[key]
        if (valItem) {
          this.form[key] = valItem
        }
      })
      this.form.adType = val.advert_type_ids
      this.form.articleType = val.article_type_ids
      this.form.imageTextType = val.imgtext_type_ids
      console.log(this.form)
    },
    handleRemove() {
      this.fetchDeleteProject()
    },
    handleCheckAllChange(val, target) {
      this.form[target] = val ? this[target + 'List'].map(item => item.id) : []
      this[target].isIndeterminate = false
    },
    handleCheckedChange(val, target) {
      const checkedCount = val.length
      this[target].checkAll = checkedCount === this[target + 'List'].length
      this[target].isIndeterminate = checkedCount > 0 && checkedCount < this[target + 'List'].length
    },
    handleDrawerClose() {
      this.drawerVisible = false
      this.form = Object.assign({}, defaultForm)
      const arr = ['adType', 'articleType', 'imageTextType']
      arr.forEach(key => {
        this[key] = Object.assign({}, checkboxStatus)
      })
    },
    handleDrawerSubmit() {
      this.$refs.drawerForm.validate(valid => {
        if (valid) {
          if (this.drawerType === 'create') {
            this.fetchCreateProject()
          } else {
            const data = this.getFormData()
            data.project_id = this.selectedItem.id
            this.fetchUpdateProject(data)
          }
          this.drawerVisible = false
        } else {
          return false
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id)
    },
    statusChange(val) {
      this.fetchUpdateProject(
        {
          project_id: val.id,
          status: val.status
        },
        'status'
      )
    },
    getFormData() {
      const form = this.form
      const data = {
        advert_type_ids: form.adType,
        article_type_ids: form.articleType,
        imgtext_type_ids: form.imageTextType
      }
      Object.keys(form).forEach(key => {
        if (typeof key === 'string') {
          data[key] = form[key]
        }
      })
      return data
    },
    fetchCreateProject() {
      const data = this.getFormData()
      createProject(data).then(res => {
        if (res.code === 0 && res.message === 'SUCCESS') {
          this.$message.success('新建项目成功')
          this.$refs.tabList.refetch()
        } else {
          this.$message.error(res.message || '新建项目失败')
        }
      })
    },
    fetchUpdateProject(data, type) {
      const msg = type === 'status' ? '更改状态' : '更改项目'
      updateProject(data).then(res => {
        if (res.code === 0 && res.message === 'SUCCESS') {
          this.$message.success(msg + '成功')
          this.$refs.tabList.refetch()
          // 刷新用户user_detail
          if (this.userProjectIds.includes(data.project_id)) {
            this.$store.dispatch('checkRolesPermissions')
          }
        } else {
          this.$message.error(res.message || msg + '失败')
        }
      })
    },
    fetchDeleteProject() {
      deleteProject({ project_id: this.multipleSelection[0] }).then(res => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success('删除项目成功')
          this.$refs.tabList.refetch()
          // 刷新用户user_detail
          if (this.userProjectIds.includes(this.multipleSelection[0])) {
            this.$store.dispatch('checkRolesPermissions')
          }
        } else {
          this.$message.error(res.message || '删除项目失败')
        }
      })
    },
    fetchProjectTypeList() {
      getTypeList({ type: 0, status: 1, limit: 100 }).then(res => {
        if (res.code === 0 && res.data && Array.isArray(res.data.data)) {
          this.projectTypeList = res.data.data
        }
      })
    },
    fetchContentTypeList() {
      getContentTypesList().then(res => {
        if (res.code === 0 && res.data) {
          this.adTypeList = res.data.advert_list
          this.articleTypeList = res.data.article_list
          this.imageTextTypeList = res.data.imgtext_list
        }
      })
    }
  }
}
</script>
<style scoped>
.details-handle {
  cursor: pointer;
}
.details-handle:hover {
  color: #409eff;
}
.drawer__content {
  height: 100%;
}
.drawer-form {
  width: 450px;
  margin: 0 20px;
  padding: 20px 0 10px;
  min-height: calc(100% - 73px);
}
.drawer__footer {
  text-align: center;
  padding-bottom: 15px;
}
</style>
