<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-item">
        <el-select
          v-model="listQuery.sysOrigin"
          placeholder="系统"
          style="width:120px;"
          class="filter-item"
          @change="handleSearch"
        >
          <el-option
            v-for="item in permissionsSysOriginPlatforms"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left;">
              <sys-origin-icon
                :icon="item.value"
                :desc="item.value"
              /></span>
            <span style="float: left;margin-left:10px">{{ item.label }}</span>
          </el-option>
        </el-select>
        <el-select
          v-model="listQuery.top"
          placeholder="是否置顶"
          style="width:120px;"
          class="filter-item"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option label="已置顶" value="1" />
          <el-option label="未置顶" value="0" />
        </el-select>
        <el-date-picker
          v-model="rangeDate"
          type="datetimerange"
          class="filter-item"
          value-format="timestamp"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
        />
        <div class="filter-item">
          <account-input
            v-model="listQuery.userId"
            :sys-origin="listQuery.sysOrigin"
            placeholder="用户ID"
          />
        </div>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          :disabled="searchDisabled"
          @click="handleSearch"
        >
          搜索
        </el-button>
      </div>
    </div>
    <el-checkbox
      v-model="checkAll"
      :indeterminate="isIndeterminate"
      @change="handleCheckAllChange"
    >全选</el-checkbox>
    <div style="margin: 15px 0;" />
    <el-row v-loading="listLoading" :gutter="10">
      <div
        v-for="(item, index) in list"
        :key="index"
        style="margin-bottom: 20px;"
      >
        <div>
          <el-card :body-style="{ padding: '15px' }">
            <div style="padding-bottom: 15px;">
              <span
                style="color:#FF9326;font-weight: 600;line-height: 25px;"
              >动态内容:
              </span>
              <div
                style="overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    word-break: break-all;
    line-height: 20px;"
              >
                {{ item.content }}
              </div>
            </div>
            <div style="display: flex;overflow-x: auto;">
              <div
                v-for="(item2, index2) in item.pictures"
                :key="index2 + item2.id"
                style="margin-right: 5px;"
              >
                <div class="img">
                  <el-image
                    style="width:250px;height:300px;"
                    :src="item2.resourceUrl"
                    :preview-src-list="[item2.resourceUrl]"
                  />
                </div>
              </div>
            </div>
            <div style="padding-top: 10px">
              <div class="bottom">
                <el-checkbox-group v-model="checkList">
                  <el-checkbox :key="item.id" :label="index">选中</el-checkbox>
                </el-checkbox-group>
                <div class="info" @click="handleClickCard(index)">
                  <div>
                    昵称：
                    <a
                      class="underline"
                      @click.stop="queryUserDetails(item.userId)"
                    >{{ item.userBaseInfo.userNickname }}</a>
                    / {{ item.userBaseInfo.actualAccount }}
                  </div>
                  <div class="line">
                    <div>
                      性别：{{ item.userSexName }} / 年龄：{{
                        item.userBaseInfo.age
                      }}
                    </div>
                  </div>
                  <div>创建时间: {{ item.createTime | dateFormat }}</div>
                </div>
                <div
                  v-if="item.top == true"
                  style="font-weight:600; color:deeppink"
                >
                  置顶权重: {{ item.weights }}
                </div>
                <el-button
                  type="text"
                  class="button"
                  @click="accountHanle(item.userId)"
                >账号处理</el-button>
                <el-button
                  type="text"
                  class="button"
                  @click="topHanle(item.id, item.weights)"
                >置顶</el-button>
                <el-button
                  v-if="item.top == true"
                  type="text"
                  class="button"
                  @click="closeTopHanle(item.id)"
                >取消置顶</el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-row>
    <div style="text-align:center;">
      <div style="padding:5px;font-size:14px;color:#909399">
        已勾选了:<span style="color:#F00">{{ checkList.length }}</span>
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-folder-checked"
        @click="pass"
      >
        删除
      </el-button>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <el-dialog
      :title="textOptTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="400px"
    >
      <div v-loading="submitLoading">
        <el-form ref="topForm" :model="topForm" label-width="100px">
          <el-form-item label="平台">
            <el-input
              v-model.trim="listQuery.sysOrigin"
              :disabled="true"
              type="text"
            />
          </el-form-item>
          <el-form-item label="权重" prop="weights">
            <el-input
              v-model.trim="topForm.weights"
              v-number
              type="text"
              placeholder="数字越大越排在前面"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">保存</el-button>
            <el-button @click="handleClose()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <user-deatils-drawer
      v-if="userDeatilsDrawer"
      :user-id="thatSelectedUserId"
      @close="userDeatilsDrawer = false"
    />

    <edit-user-form
      v-if="editUserFormVisible"
      :user-id="thatSelectedUserId"
      @close="editUserFormVisible = false"
      @success="renderDataSuccess"
    />

    <account-hanle
      v-if="accountHandleVisible"
      :user-id="thatSelectedUserId"
      @success="renderDataSuccess"
      @close="accountHandleVisible = false"
    />
  </div>
</template>
<script>
import {
  userDynamicTable,
  deleteUserDynamic,
  setUpTop,
  closeTop
} from '@/api/dynamic'
import Pagination from '@/components/Pagination'
import { commonApprovalStatus, genders } from '@/constant/user'
import EditUserForm from '@/components/data/EditUserForm'
import { pickerOptions } from '@/constant/el-const'
import AccountHanle from '@/components/data/AccountHanle'
import { mapGetters } from 'vuex'
import { dateFormat } from '@/filters'
function getTopFormData() {
  return {
    dynamicId: '',
    sysOrigin: '',
    weights: ''
  }
}
export default {
  name: 'UserDynamicList',
  components: { Pagination, EditUserForm, AccountHanle },
  data() {
    return {
      searchDisabled: false,
      pickerOptions,
      commonApprovalStatus,
      genders,
      userDeatilsDrawer: false,
      submitLoading: false,
      thatSelectedUserId: '',
      list: [],
      checkList: [],
      checkAll: false,
      textOptTitle: '',
      formVisible: false,
      topForm: {},
      accountHandleVisible: false,
      isIndeterminate: false,
      editUserFormVisible: false,
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 30,
        userId: '',
        startTime: '',
        endTime: '',
        sysOrigin: 'HALAR',
        top: ''
      },
      rangeDate: '',
      listLoading: true
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startTime = newVal[0]
          this.listQuery.endTime = newVal[1]
          return
        }
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
  },
  methods: {
    dateFormat,
    renderData(isClean) {
      const that = this
      that.listLoading = true
      that.checkList = []
      that.isIndeterminate = true
      if (isClean === true) {
        that.list = []
        that.listQuery.cursor = 1
      }
      userDynamicTable(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.listLoading = false
      })
    },
    handleSearch() {
      this.renderData(true)
    },
    // 截取数据
    cutout(cellValue) {
      if (cellValue != null) {
        return cellValue.replace(/\,/g, '</br>')
      }
    },
    accountHanle(userId) {
      this.accountHandleVisible = true
      this.thatSelectedUserId = userId
    },
    topHanle(dynamicId, weights) {
      this.textOptTitle = '编辑置顶动态'
      this.topForm = getTopFormData()
      this.topForm.dynamicId = dynamicId
      this.topForm.sysOrigin = this.listQuery.sysOrigin
      this.topForm.weights = weights
      this.formVisible = true
    },
    closeTopHanle(dynamicId) {
      const that = this
      closeTop(dynamicId)
        .then(res => {
          that.renderData(true)
        })
        .catch(er => {
          console.error(er)
          this.$emit('fail')
        })
    },
    handleCheckAllChange(val) {
      const that = this
      that.checkList = []
      if (val) {
        that.list.forEach((item, index) => {
          that.checkList.push(index)
        })
      }
      this.isIndeterminate = false
    },
    submitForm() {
      const that = this
      that.$refs.topForm.validate(valid => {
        if (valid) {
          that.submitLoading = true
          setUpTop(that.topForm)
            .then(res => {
              that.$opsMessage.success()
              that.submitLoading = false
              that.formVisible = false
              this.topForm = getTopFormData()
              that.renderData(true)
            })
            .catch(er => {
              that.submitLoading = false
              console.error(er)
              this.$emit('fail')
            })
        } else {
          console.error('error submit!!')
          return false
        }
      })
    },
    pass() {
      const that = this
      if (that.checkList.length === 0) {
        that.$opsMessage.warn('请勾选审批项')
        return
      }
      that
        .$confirm('确认审核选中记录吗？', '提示', {
          type: 'warning'
        })
        .then(() => {
          that.listLoading = true
          deleteUserDynamic(that.getApprovalParams())
            .then(res => {
              that.listLoading = false
              that.$opsMessage.success()
              that.renderData()
            })
            .catch(() => {
              that.listLoading = false
            })
        })
        .catch(() => {})
    },
    editUserForm(id) {
      this.thatSelectedUserId = id
      this.editUserFormVisible = true
    },
    renderDataSuccess() {
      this.$opsMessage.success()
      this.renderData()
    },
    handleClose() {
      this.formVisible = false
      this.topForm = getTopFormData()
    },
    queryUserDetails(id) {
      this.thatSelectedUserId = id
      this.userDeatilsDrawer = true
    },
    handleClickCard(id) {
      const index = this.checkList.findIndex(nid => nid === id)
      if (index > -1) {
        this.checkList.splice(index, 1)
        return
      }
      this.checkList.push(id)
    },
    getApprovalParams() {
      const that = this
      const approvalParams = []
      that.checkList.forEach(item => {
        const checkData = that.list[item]
        approvalParams.push(checkData.id)
        // approvalParams.push({
        //   userId: checkData.userId,
        //   contentId: checkData.id,
        //   content: checkData.resourceUrl,
        //   tags: checkData.labelNames
        // })
      })
      return approvalParams
    }
  }
}
</script>
<style scoped lang="scss">
.bottom {
  color: #666;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 25px;
  .line {
    display: flex;
    > div {
      width: 100%;
    }
  }
  .info {
    cursor: pointer;
  }
}
.img {
  position: relative;
  .label {
    position: absolute;
    bottom: 0px;
    border: 1px solid;
    width: 100%;
    background: black;
    opacity: 0.5;
    color: #fff;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 25px;
  }
}
</style>
