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

      <sticky :class-name="'sub-navbar'">
        <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>pick相关</span>
            </div>
            <el-row>
              <el-col :span="24">
                <el-form-item style="margin-bottom: 40px;" prop="name">
                  <MDinput v-model="postForm.name" :maxlength="100" name="name" required>
                    pick名称
                  </MDinput>
                </el-form-item>
                <div class="postInfo-container">
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label-width="45px" label="性别:" class="postInfo-container-item">
                        <el-select v-model="postForm.gender" :placeholder="'性别:'" clearable
                                   class="postInfo-container-item"
                                   style="width: 120px">
                          <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="8">
                      <el-form-item label-width="60px" label="属性:" class="postInfo-container-item">
                        <el-select v-model="postForm.pick_type" :placeholder="'性别:'" clearable
                                   class="postInfo-container-item" style="width:120px">
                          <el-option v-for="item in PickTypeOptions" :key="item.key" :label="item.display_name"
                                     :value="item.key"/>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item style="margin-bottom: 40px;" label-width="45px" label="位置:" prop="position">
                        <el-input :rows="1" v-model="postForm.position" type="number" class="article-textarea"
                                  style="width: 120px"
                                  placeholder="请输入内容"/>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="postInfo-container">
                  <el-row>
                    <el-col :span="8">
                      <el-form-item style="margin-bottom: 40px;" label-width="45px" label="pickid:" prop="id"
                                    v-if="isEdit">
                        <el-input :rows="1" v-model="postForm.id" type="number" class="article-textarea"
                                  style="width: 120px" disabled/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item style="margin-bottom: 40px;" label-width="75px" label="pick用户:" prop="user_nums"
                                    v-if="isEdit">
                        <el-input :rows="1" v-model="postForm.user_nums" type="number" class="article-textarea"
                                  style="width: 120px" disabled/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item style="margin-bottom: 40px;" label-width="85px" label="创建时间:" prop="create_time"
                                    v-if="isEdit">
                        <el-input :rows="1" v-model="postForm.create_time" type="text" class="article-textarea"
                                  style="width: 170px" disabled/>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label-width="45px" label="地区:" class="postInfo-container-item">
                  <el-select v-model="postForm.region" :remote-method="getRemoteCityList" filterable remote multiple
                             value-key="id"
                             placeholder="搜索地区" style="width: 100%">
                    <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-col :span="12">

                <el-form-item label-width="45px" label="小组:" class="postInfo-container-item">
                  <el-select
                    v-model="postForm.pick_group"
                    :remote-method="getRemoteGroupList"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    placeholder="搜索小组"
                    style="width: 100%"
                    :loading="loading"
                    value-key="id"
                  >
                    <el-option v-for="(item, index) in groupListOptions" :key="item+index" :label="item.name"
                               :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item style="margin-bottom: 40px;" label-width="45px" label="简介:" prop="desc">
              <el-input :rows="1" v-model="postForm.desc" type="textarea" class="article-textarea" autosize
                        placeholder="请输入内容"/>
              <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
            </el-form-item>
            <el-form-item style="margin-bottom: 40px;" label-width="45px" 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-card>
        </el-row>

        <el-row :gutter="20" style="margin-top:50px;" v-if="isEdit">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span v-if="">pick明星相关</span>
            </div>
            <div style="margin-bottom:50px;">
              <div class="filter-container">

              </div>
              <el-table :data="list" 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">
                    <span>{{ scope.row.celebrity_id }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="明星名称">
                  <template slot-scope="scope">
                    <span>{{ scope.row.celebrity_name }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="pick值">
                  <template slot-scope="scope">
                    <span>{{ scope.row.pick_nums }}</span>
                  </template>
                </el-table-column>


                <el-table-column align="center" min-width="100" label="添加pick值">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input v-model="scope.row.fake_pick_nums" type="number" class="edit-input" size="small"/>
                    <el-button class="cancel-btn" size="small" icon="el-icon-refresh" type="warning"
                               @click="cancelEdit(scope.row)">取消
                    </el-button>
                  </template>
                  <span v-else>{{ scope.row.fake_pick_nums }}</span>
                </template>
              </el-table-column>

              <el-table-column align="center" label="操作" width="120">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.edit" type="success" size="small" icon="el-icon-circle-check-outline"
                             @click="confirmEdit(scope.row)">确认
                  </el-button>
                  <el-button v-else type="primary" size="small" icon="el-icon-edit"
                             @click="scope.row.edit=!scope.row.edit">添加
                  </el-button>
                </template>
              </el-table-column>
              </el-table>





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


        <el-row :gutter="20" style="margin-top:50px;" v-if="isEdit">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span v-if="">pick帖子相关</span>
            </div>
            <div style="margin-bottom:50px;">
              <div class="filter-container">

              </div>
              <el-table :data="list" 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">
                    <span>{{ scope.row.topic_id }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="帖子名称">
                  <template slot-scope="scope">
                    <span>{{ scope.row.topic_name }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="pick值">
                  <template slot-scope="scope">
                    <span>{{ scope.row.pick_nums }}</span>
                  </template>
                </el-table-column>


                <el-table-column align="center" min-width="100" label="添加pick值">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input v-model="scope.row.fake_pick_nums" type="number" class="edit-input" size="small"/>
                    <el-button class="cancel-btn" size="small" icon="el-icon-refresh" type="warning"
                               @click="cancelEdit(scope.row)">取消
                    </el-button>
                  </template>
                  <span v-else>{{ scope.row.fake_pick_nums }}</span>
                </template>
              </el-table-column>

              <el-table-column align="center" label="操作" width="120">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.edit" type="success" size="small" icon="el-icon-circle-check-outline"
                             @click="confirmEdit(scope.row)">确认
                  </el-button>
                  <el-button v-else type="primary" size="small" icon="el-icon-edit"
                             @click="scope.row.edit=!scope.row.edit">添加
                  </el-button>
                </template>
              </el-table-column>
              </el-table>





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

      </div>
    </el-form>

  </div>
</template>

<script>
  import MDinput from '@/components/MDinput'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import Pagination from '@/components/Pagination'
  import {fetchPickDetail, CreatePick, fetchPickUserList, AddFakePickNums} from '@/api/pick'
  import {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',
    name: '',
    desc: '',
    gender: '',
    region: [],
    pick_group: [],
    pick_type: '',
    position: '',
    is_online: 1,
  }

  export default {
    name: 'PickDetail',
    components: {MDinput, Sticky, Pagination},
    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,
        pick_type: '',
        regionListOptions: [],
        groupListOptions: [],
        GenderTypeOptions: [
          {'key': 2, 'display_name': '全部'},
          {'key': 0, 'display_name': '男'},
          {'key': 1, 'display_name': '女'},
        ],
        PickTypeOptions: [
          {'key': 1, 'display_name': 'PICK明星'},
          {'key': 0, 'display_name': 'PICK帖子'},
        ],
        rules: {
          name: [{validator: validateRequire, trigger: 'blur'}],
          desc: [{validator: validateRequire, trigger: 'blur'}],
          position: [{validator: validateRequire, trigger: 'blur'}],
        },
        tempRoute: {},
        temparray: {
          'region': [],
          'pick_group': [],
        },
        listQuery: {
          id: '',
          pick_type: '',
          page: 0,
          limit: 10,
          filter: {
          },
        },
        list: null,
        total: 1,
        listLoading: true,
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.desc.length
      }
    },
    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) {
        fetchPickDetail(id).then(response => {
          // select 回填数据处理，后期再进行优化
          let rep = response.data.data.data;
          let pick_temp = []
          let region_temp = []
          for (let i = 0; i < rep.pick_group.length; i++) {
            pick_temp.push(rep.pick_group[i]['name']);
            this.temparray['pick_group'].push(rep.pick_group[i])
          }
          for (let i = 0; i < rep.region.length; i++) {
            region_temp.push(rep.region[i]['name']);
            this.temparray['region'].push(rep.region[i])
          }
          rep.region = region_temp
          rep.pick_group = pick_temp
          this.postForm = rep
          this.pick_type = rep.pick_type;
        }).catch(err => {
          console.log(err)
        })
      },
      submitForm() {
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true;
            if (this.isEdit) {
              this.postForm.region = Assembledata(this.temparray['region'], this.postForm.region);
              this.postForm.pick_group = Assembledata(this.temparray['pick_group'], this.postForm.pick_group);
            } else {
              this.postForm.region = this.postForm.region.join(',')
              this.postForm.pick_group = this.postForm.pick_group.join(',')
            }
            CreatePick(this.postForm).then(response => {
              this.$notify({
                title: '成功',
                message: response.data.data.message,
                type: 'success',
                duration: 2000
              })
              setTimeout(() => {
                this.$router.push('/pick/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
        })
      },
      getRemoteGroupList(query) {
        groupSearch(query).then(response => {
          if (!response.data.data.data) return
          this.groupListOptions = response.data.data.data
        })
      },

      // 分页相关
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

      reply() {

      },
      getList() {
        this.listLoading = true
        this.listQuery.id = this.$route.params && this.$route.params.id
        this.listQuery.pick_type = this.pick_type
        fetchPickUserList(this.listQuery).then(response => {
          const items = response.data.data.data
          this.list = items.map(v => {
            this.$set(v, 'edit', false)
            v.original_fake_pick_nums = v.fake_pick_nums
            return v
          })
          this.total = response.data.data.total
          this.listLoading = false;
        })
      },
      cancelEdit(row) {
        row.fake_pick_nums = row.original_fake_pick_nums
        row.edit = false
        this.$message({
          message: '取消成功',
          type: 'warning'
        })
      },
      confirmEdit(row) {
        row.edit = false
        row.original_fake_pick_nums = row.fake_pick_nums
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        AddFakePickNums(row).then(response => {

        }).catch(err => {

        })
      }
    }
  }
</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;
    }
  }
  .edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
