<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :class-name="'sub-navbar '+postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">保存
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row :gutter="20">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>明星相关</span>
            </div>
            <div>
              <el-col :span="24">
                <el-form-item style="margin-bottom: 20px;" prop="name">
                  <MDinput v-model="postForm.name" :maxlength="100" name="name" required>
                    明星名称
                  </MDinput>
                </el-form-item>
                <div class="postInfo-container">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item style="margin-bottom: 20px;" label-width="75px" label="明星ID:" v-if="isEdit">
                        <el-input v-model="postForm.id" type="text"  style="width: 230px;" disabled/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item style="margin-bottom: 20px;" label-width="75px" label="创建时间:" v-if="isEdit">
                        <el-input v-model="postForm.create_time" type="text" placeholder="请输入内容" style="width: 230px;"
                                  disabled/>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="12">
                      <el-form-item style="margin-bottom: 20px;" label-width="75px" label="用户数:"
                                    v-if="isEdit">
                        <el-input v-model="postForm.user_nums" type="number" style="width: 220px;" disabled/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item style="margin-bottom: 20px;" label-width="75px" label="帖子数:"
                                    v-if="isEdit">
                        <el-input v-model="postForm.topic_nums" type="number" style="width: 220px;" disabled/>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item style="margin-bottom: 20px;" label-width="75px" label="小组数:" v-if="isEdit">
                        <el-input v-model="postForm.group_nums" type="number" style="width: 220px;" disabled/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">


                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </div>
            <el-form-item label-width="75px" label="性别:" style="margin-left: 10px" prop="gender">
              <el-select v-model="postForm.gender" :placeholder="'性别:'" clearable
                         class="postInfo-container-item"
                         style="width: 220px" :disabled="this.isEdit">
                <el-option v-for="item in GenderTypeOptions" :key="item.key" :label="item.display_name"
                           :value="item.key"/>
              </el-select>
            </el-form-item>
            <el-form-item label-width="75px" label="城市:" style="margin-left: 10px" prop="city">
              <el-select v-model="city" :remote-method="getRemoteCityList" filterable remote clearable
                         value-key="id"
                         placeholder="搜索地区" style="width: 220px">
                <el-option v-for="(item,index) in regionListOptions" :key="item+index" :label="item" :value="item"/>
              </el-select>
            </el-form-item>
            <el-form-item style="margin-bottom: 20px;margin-left: 10px" label-width="75px" label="是否在线:">
              <el-radio-group v-model="postForm.is_online">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="margin-bottom: 20px;margin-left: 10px" label-width="75px" label="明星简介:">
              <el-input :rows="1" v-model="postForm.description" type="textarea" class="article-textarea" autosize
                        placeholder="请输入内容"/>
              <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
            </el-form-item>


            <div style="margin-bottom: 20px;margin-left: 10px">
              <el-form-item style="margin-bottom: 40px;" label-width="75px" label="明星头像:" prop="avatar">
                <span v-model="uploadType"></span>
              <Upload v-model="postForm.avatar" :uploadType="uploadType"/>
                </el-form-item>
            </div>

          </el-card>
        </el-row>
        <el-row :gutter="20" style="margin-top:50px;">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>小组相关</span>
            </div>
            <div style="margin-bottom:50px;">
              <div class="filter-container">
               <el-select v-model="temp_group_ids" :remote-method="getRemoteGroupList" filterable remote clearable
                         value-key="id"
                         placeholder="小组" style="width: 220px">
                <el-option v-for="(item,index) in groupListOptions" :key="item+index" :label="item" :value="item"/>
              </el-select>
                <el-button v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="appendUser">添加
                </el-button>
                <el-button v-waves class="filter-item" type="primary" icon="el-icon-delete" @click="delUser">移除
                </el-button>
              </div>
              <el-table :data="data" border fit highlight-current-row style="width: 100%"
                        ref="multipleTable" @selection-change="handleSelectionChange">
                <el-table-column type="selection" align="center"></el-table-column>
                <el-table-column align="center" label="小组ID ">
                  <template slot-scope="scope">
                    <router-link :to="'/group/edit/'+scope.row.id" class="link-type">
                      <span>{{ scope.row.id }}</span>
                    </router-link>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="小组名称">
                  <template slot-scope="scope">
                    <span>{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="小组简介">
                  <template slot-scope="scope">
                    <span>{{ scope.row.description }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="用户数">
                  <template slot-scope="scope">
                    <span>{{ scope.row.user_nums }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="帖子数">
                  <template slot-scope="scope">
                    <span>{{ scope.row.topic_nums }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="组长">
                  <template slot-scope="scope">
                    <span>{{ scope.row.creator.name }}</span>
                  </template>
                </el-table-column>

              </el-table>
              <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                          style="margin-left: 250px;" @pagination="getList"/>
            </div>
          </el-card>
        </el-row>
      </div>
    </el-form>

  </div>
</template>

<script>
  import Upload from '@/components/Upload/singleImage3'
  import MDinput from '@/components/MDinput'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import waves from '@/directive/waves'
  import Pagination from '@/components/Pagination'
  import {starCreate, starDetail, fetchStarRelatedGroup} from '@/api/star'
  import { GroupDetail } from '@/api/group'
  import {citySearch, groupSearch} from '@/api/remoteSearch'
  import { isInArray } from "@/utils";

  const defaultForm = {
    status: 'draft',
    name: '',
    id: '',
    gender: '',
    city: '',
    is_online: 0,
    description: '',
    avatar: '',
    groups: [],
  }

  export default {
    name: 'StarDetail',
    components: {MDinput, Upload, Sticky, Pagination},
    directives: {waves},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateRequire = (rule, value, callback) => {
        if (value === '') {
          this.$message({
            message: rule.field + '为必传项',
            type: 'error'
          })
          callback(new Error(rule.field + '为必传项'))
        } else {
          callback()
        }
      }
      return {
        postForm: Object.assign({}, defaultForm),
        loading: false,
        groupListOptions: [],


        temp_group_ids: '',
        group_ids: [],
        city: '',

        rules: {
          name: [{validator: validateRequire, trigger: 'blur'}],
          gender: [{validator: validateRequire, trigger: 'blur'}],
          avatar: [{validator: validateRequire, trigger: 'blur'}],
        },
        GenderTypeOptions: [
          {'key': 0, 'display_name': '男'},
          {'key': 1, 'display_name': '女'},
        ],
        tempRoute: {},
        regionListOptions: [],
        uploadType: 99,
        list: [],
        tableData: [],
        total: 0,
        listLoading: true,
        multipleSelection: [],
        del_list: [],
        listQuery: {
          id: '',
          page: 0,
          limit: 10,
        },
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.description.length
      },
      lang() {
        return this.$store.getters.language
      },
      data() {
        return this.tableData.filter((d) => {
          let is_del = false;
          for (let i = 0;i < this.del_list.length; i++){
            if (d.id == this.del_list[i].id){
              is_del = true;
              break
            }
          }
          if (!is_del){
              return d
          }
        })
      }
    },
    created() {
      if (this.isEdit) {
        const id = this.$route.params && this.$route.params.id
        this.fetchData(id)
        this.getList()
      } else {
        this.postForm = Object.assign({}, defaultForm)
      }

      this.tempRoute = Object.assign({}, this.$route)
    },
    methods: {
      fetchData(id) {
        starDetail(id).then(response => {
          let rep = response.data.data.data
          this.postForm = rep
          if (rep.city.id && rep.city.name){
            this.city = rep.city.id + ':' + rep.city.name
          }else{
            this.city = ''
          }
        }).catch(err => {
          console.log(err)
        })
      },
      submitForm() {
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true
            if (this.city == ''){
              this.$message.error('城市必填')
              this.loading = false
              return false
            }
            this.postForm.groups = JSON.stringify(this.group_ids);
            this.postForm.city = this.city
            starCreate(this.postForm).then(response => {
              this.$notify({
                title: '成功',
                message: response.data.data.message,
                type: 'success',
                duration: 2000
              })
              setTimeout(() => {
                this.$router.push('/star/list')
              }, 1000)

            }).catch(err => {
              this.$notify({
                title: '失败',
                message: '操作失败',
                type: 'danger',
                duration: 2000
              })
            });

            this.postForm.status = 'published'
            this.loading = false

          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      getRemoteGroupList(query) {
        groupSearch(query).then(response => {
          if (!response.data.data.data) return
          this.groupListOptions = response.data.data.data
        })
      },
      getRemoteCityList(query) {
        citySearch(query).then(response => {
          if (!response.data.data.data) return
          this.regionListOptions = response.data.data.data
        })
      },
      appendUser() {
        if (!this.temp_group_ids){
          this.$message.error('还没输入小组呢~~')
          this.temp_group_ids = ''
          return false
        }
        GroupDetail(this.temp_group_ids).then(response => {
          if (!response.data.data) return
          this.tableData.push(response.data.data)
          this.total = this.tableData.length
        })
        this.group_ids.push(this.temp_group_ids)
        this.temp_group_ids = ''
      },
      delUser() {

        let origin_group_ids = [];
        var left_group_ids = [];
        let select_group_ids = []

        this.del_list.push(...this.multipleSelection)

        for (let i = 0; i < this.tableData.length; i++){
          origin_group_ids.push(this.tableData[i].id + ':' + this.tableData[i].name)
        }
        for (let i = 0; i < this.multipleSelection.length; i++){
          select_group_ids.push(this.multipleSelection[i].id + ':' + this.multipleSelection[i].name)
        }
        for (let i =0; i < origin_group_ids.length; i++){
          if (!isInArray(select_group_ids ,origin_group_ids[i])){
            left_group_ids.push(origin_group_ids[i])
          }
        }
        this.group_ids = left_group_ids;
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      getList() {
        this.listLoading = true
        this.listQuery.id = this.$route.params && this.$route.params.id
        fetchStarRelatedGroup(this.listQuery).then(response => {
          let rep = response.data.data.data;
          for (let i = 0; i < rep.length; i++){
            this.group_ids.push(rep[i].id + ':' + rep[i].name)
          }
          this.tableData = response.data.data.data
          this.total = response.data.data.total
          this.listLoading = false
        })
      },
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/mixin.scss";

  .createPost-container {
    position: relative;
    .createPost-main-container {
      padding: 40px 45px 20px 50px;
      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;
        .postInfo-container-item {
          float: left;
        }
      }
      .editor-container {
        min-height: 500px;
        margin: 0 0 30px;
        .editor-upload-btn-container {
          text-align: right;
          margin-right: 10px;
          .editor-upload-btn {
            display: inline-block;
          }
        }
      }
    }
    .word-counter {
      width: 40px;
      position: absolute;
      right: -10px;
      top: 0px;
    }
  }
</style>