<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>

            <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="username">
                        <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="性别:">
                        <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="postForm.city" :remote-method="getRemoteCityList" filterable remote
                                   value-key="id"
                                   placeholder="搜索城市" style="width: 230px">
                          <el-option v-for="(item,index) in regionListOptions" :key="item+index" :label="item.name"
                                     :value="item.id"/>
                        </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="postForm.tag_ids" :remote-method="getRemoteTagList" filterable remote
                                   multiple value-key="id"
                                   placeholder="搜索地区" style="width: 720px">
                          <el-option v-for="(item,index) in tagListOptions" :key="item+index" :label="item.name"
                                     :value="item.id"/>
                        </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="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-->
                         <!--value-key="id"-->
                         <!--placeholder="小组" style="width: 220px">-->
                <!--<el-option v-for="(item,index) in groupListOptions" :key="item+index" :label="item.id + ':' + item.name" :value="item.id"/>-->
              <!--</el-select>-->
                <!--<el-button v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="appendGroup">添加-->
                <!--</el-button>-->
              <!--</div>-->
              <!--<el-table :data="list" border fit highlight-current-row style="width: 100%"-->
                        <!--ref="multipleTable">-->
                <!--<el-table-column align="center" label="小组ID">-->
                  <!--<template slot-scope="scope">-->
                    <!--<span>{{ scope.row.id }}</span>-->
                  <!--</template>-->
                <!--</el-table-column>-->
                <!--<el-table-column align="center" label="小组名称">-->
                  <!--<template slot-scope="scope">-->
                    <!--<span>{{ scope.row.group_name }}</span>-->
                  <!--</template>-->
                <!--</el-table-column>-->
                <!--<el-table-column align="center" label="小组简介">-->
                  <!--<template slot-scope="scope">-->
                    <!--<span>{{ scope.row.group_desc }}</span>-->
                  <!--</template>-->
                <!--</el-table-column>-->
                <!--<el-table-column align="center" label="组长">-->
                  <!--<template slot-scope="scope">-->
                    <!--<span>{{ scope.row.nick_name }}</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.group_identify }}</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 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 { GroupDetail } from '@/api/group'
  import {regionSearch, tagSearch, groupSearch, citySearch} from '@/api/remoteSearch'
  import { isInArray, removeByvale} from "@/utils";

  function Assembledata(target, source) {
    var region_data = []
    for (var i=0;i<target.length;i++){
      if (isInArray(source, target[i]['name'])){
        region_data.push(target[i]['id'])
        removeByvale(source, target[i]['name']);
      }
    }
    region_data.push(...source)
    return region_data.join(',')
  }

  const defaultForm = {
    status: 'draft',
    uploadType: '',
    is_recommend: 1,
    user_id: '',
    create_time: '',
    topic_nums: 0,
    password: '',
    avatar: '',
    nick_name: '',
    tag_ids: [],
    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()
        }
      }
      const validateSourceUri = (rule, value, callback) => {
        if (value) {
          if (validateURL(value)) {
            callback()
          } else {
            this.$message({
              message: '外链url填写不正确',
              type: 'error'
            })
            callback(new Error('外链url填写不正确'))
          }
        } else {
          callback()
        }
      }
      return {
        postForm: Object.assign({}, defaultForm),
        loading: false,
        group_ids: [],
        groupListOptions: [],
        rules: {
          image_uri: [{validator: validateRequire}],
          title: [{validator: validateRequire}],
          content: [{validator: validateRequire}],
          source_uri: [{validator: validateSourceUri, trigger: 'blur'}]
        },
        expireTimeOption: {
          disabledDate(date){
            return date.getTime() <= Date.now();
          }
        },
        tempRoute: {},
        listQuery: {
          page: 1,
          limit: 10,
          filter: {
          },
        },
        GenderTypeOptions: [
          {'key': 0, 'display_name': '男'},
          {'key': 1, 'display_name': '女'},
        ],
        regionListOptions: [],
        tagListOptions: [],
        temp_group_ids: '',
        uploadType: 99,
        list: [],
        total: 0,
        listLoading: true,
        multipleSelection: [],
        del_list: [],
        temp: {
          tags:[],
          city_temp_id:'',
          city_temp_name: '',
          group_ids: []
        }
      }
    },
    computed: {
      lang() {
        return this.$store.getters.language
      }
    },
    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) {
        UserDetail(id).then(response => {
          let rep = response.data.data
          let temp_tags = []
          this.postForm = response.data.data
          this.temp.city_temp_id = response.data.data.city.id
          this.postForm.city = this.temp.city_temp_name =  response.data.data.city.name
          for (let i = 0;i < rep.tag_list.length; i++){
            temp_tags.push(rep.tag_list[i].name)
            this.temp.tags.push(rep.tag_list[i])
          }
          this.postForm.tag_ids = temp_tags

        }).catch(err => {
          console.log(err)
        })
      },
      submitForm() {

        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.postForm.group_ids = JSON.stringify(this.temp.group_ids)

            if (this.temp.city_temp_name === this.postForm.city){
              this.postForm.city = this.temp.city_temp_id
            }

            if (this.isEdit){
              this.postForm.tag_ids = Assembledata(this.temp.tags, this.postForm.tag_ids)
            }else{
              this.postForm.tag_ids = this.postForm.tag_ids.join(',')
            }

            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
          }
        })
      },
      appendGroup() {
        if (isInArray(this.group_ids, this.temp_group_ids)){
          this.$message({
            message: '数据添加重复',
            type: 'error'
          })
          return false;
        }
        GroupDetail(this.temp_group_ids).then(response => {
          if (!response.data.data) return
          console.log(response.data.data)
          console.log(this.list)
          this.list.push(response.data.data)
          this.total = this.list.length
        })
        this.temp.group_ids.push(this.temp_group_ids)
        this.temp_group_ids = ''
      },
      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
        })
      },
      getRemoteTagList(query) {
        tagSearch(query).then(response => {
          if (!response.data.data.data) return
          this.tagListOptions = response.data.data.data
        })
      },
      getList() {
        this.listLoading = true
        this.listQuery.id = this.$route.params && this.$route.params.id
        fetchGroupUser(this.listQuery).then(response => {
             let rep = response.data.data.data
             this.list = response.data.data.data
             this.total = response.data.data.total
            for (let i=0;i<rep.length;i++){
              this.temp.group_ids.push(rep[i].id)
            }
          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>
