<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" :disabled="isdisabledFn">保存
        </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>

            <el-row>
              <el-col :span="24">
                <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.user_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" 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.password" 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.topic_nums" type="text" 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="*用户名:" prop="nick_name">
                        <el-input v-model="postForm.nick_name" type="text" style="width: 230px"/>
                      </el-form-item>
                    </el-col>
                    <!--<el-col :span="12">-->
                      <!--<el-form-item label-width="75px" label="展示时间:" class="postInfo-container-item">-->
              <!--<el-date-picker v-model="postForm.show_time " type="datetime" format="yyyy-MM-dd HH:mm:ss"-->
                              <!--placeholder="选择日期时间" :picker-options="expireTimeOption" style="width: 230px"/>-->
            <!--</el-form-item>-->
                    <!--</el-col>-->
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item style="margin-bottom: 20px;" label-width="75px" label="电话:" prop="phone">
                        <el-input v-model="postForm.phone" type="text" style="width: 230px;"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item style="margin-bottom: 20px;" label-width="75px" label="邮箱:" prop="email">
                        <el-input v-model="postForm.email" type="text" style="width: 230px"/>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label-width="75px" label="*性别:" prop="gender">
                        <el-select v-model="postForm.gender" :placeholder="'性别:'" clearable
                                   class="postInfo-container-item"
                                   style="width: 230px">
                          <el-option v-for="item in GenderTypeOptions" :key="item.key" :label="item.display_name"
                                     :value="item.key"/>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label-width="75px" label="*城市:">
                        <el-select v-model="city" :remote-method="getRemoteCityList" filterable remote clearable
                                   value-key="id"
                                   placeholder="搜索城市" style="width: 230px">
                          <el-option v-for="(item,index) in regionListOptions" :key="item+index" :label="item"
                                     :value="item"/>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label-width="75px" label="标签:">
                        <el-select v-model="tags" :remote-method="getRemoteTagList" filterable remote clearable
                                   multiple value-key="id"
                                   placeholder="搜索标签" style="width: 720px">
                          <el-option v-for="(item,index) in tagListOptions" :key="item+index" :label="item"
                                     :value="item"/>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item style="margin-bottom: 20px;margin-left: 10px" label-width="75px" label="马甲号:">
                        <el-radio-group v-model="postForm.is_puppet">
                          <el-radio :label="1">是</el-radio>
                          <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item style="margin-bottom: 20px;margin-left: 10px" label-width="75px" label="推荐:">
                        <el-radio-group v-model="postForm.is_recommend">
                          <el-radio :label="1">是</el-radio>
                          <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>

            <div style="margin-bottom: 20px;">
              <el-form-item style="margin-bottom: 40px;" label-width="85px" label="*用户头像:" prop="avatar">
                <span v-model="uploadType"></span>
                <Upload v-model="postForm.avatar" :uploadType="uploadType"/>
              </el-form-item>
            </div>
          </el-card>
        </el-row>
      </div>
    </el-form>

  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  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 {validateURL} from '@/utils/validate'
  import {UserDetail, fetchGroupUser, userCreate} from '@/api/user'
  import { tagSearch, groupSearch, citySearch} from '@/api/remoteSearch'


  const defaultForm = {
    status: 'draft',
    uploadType: '',
    is_recommend: 0,
    user_id: '',
    create_time: '',
    topic_nums: 0,
    password: '',
    avatar: '',
    nick_name: '',
    gender: '',

    tags: [],
    is_puppet: 1,
    city: '',
  }

  export default {
    name: 'UserDetail',
    components: {Tinymce, 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,

        city: '',
        tags: [],

        rules: {
          nick_name: [{validator: validateRequire, trigger: 'blur'}],
          avatar: [{validator: validateRequire, trigger: 'blur'}],
          avatar: [{validator: validateRequire, trigger: 'blur'}],
        },
        tempRoute: {},
        GenderTypeOptions: [
          {'key': 0, 'display_name': '男'},
          {'key': 1, 'display_name': '女'},
        ],
        regionListOptions: [],
        tagListOptions: [],
        uploadType: 99,
        isdisabledFn: false
      }
    },
    computed: {
      lang() {
        return this.$store.getters.language
      }
    },
    created() {
      if (this.isEdit) {
        const id = this.$route.params && this.$route.params.id
        this.fetchData(id)
      } else {
        this.postForm = Object.assign({}, defaultForm)
      }
      this.tempRoute = Object.assign({}, this.$route)
    },
    methods: {
      fetchData(id) {
        UserDetail(id).then(response => {
          let rep = response.data.data
          this.postForm = response.data.data
          this.city = response.data.data.city.id + ':' + response.data.data.city.name
          for (let i = 0;i < rep.tag_list.length; i++){
            this.tags.push(rep.tag_list[i].id + ':' + rep.tag_list[i].name)
          }

        }).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
            }
            console.log(this.postForm.gender)
            if (this.postForm.gender === ''){
              this.$message.error('性别必填~')
              this.loading = false
              return false
            }
            this.isdisabledFn = true
            this.postForm.city = this.city;
            this.postForm.tags = JSON.stringify(this.tags)
            userCreate(this.postForm).then(response => {
              this.$notify({
                title: '成功',
                message: response.data.data.message,
                type: 'success',
                duration: 2000
              })
              setTimeout(() => {
                this.$router.push('/user/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
          }
        })
      },
      getRemoteCityList(query) {
        citySearch(query).then(response => {
          if (!response.data.data.data) return
          this.regionListOptions = response.data.data.data
        })
      },
      getRemoteTagList(query) {
        tagSearch(query).then(response => {
          if (!response.data.data.data) return
          this.tagListOptions = response.data.data.data
        })
      },
    }
  }
</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>
