<template>
  <div class="app-container">
    <div class="filter-container">
      <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>
      <account-input v-model="listQuery.userId" :sys-origin="listQuery.sysOrigin" class="filter-item" placeholder="用户ID" />
      <el-input
        v-model.trim="listQuery.account"
        placeholder="靓号Account"
        style="width: 200px;"
        class="filter-item"
      />

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        v-if="buttonPermissions.includes('user:special:add')"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>
    <el-table
     v-if="buttonPermissions.includes('user:special:table:query:list')"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
    >

      <el-table-column type="index" width="50" label="No" />
      <el-table-column prop="userSpecialId.sysOrigin" label="系统" align="center" width="150">
        <template slot-scope="scope">
          <sys-origin-icon :icon="scope.row.userSpecialId.sysOrigin" :desc="scope.row.userSpecialId.sysOrigin" />
        </template>
      </el-table-column>
      <el-table-column label="用户" align="center">

        <template slot-scope="scope">
          <div class="box-header flex-l">
            <div class="avatar">
              <avatar size="mini" :url="scope.row.userBaseInfo.userAvatar" :gender="scope.row.userBaseInfo.userSex" />
            </div>
            <div class="info nowrap-ellipsis" style="margin-left:10px;">
              <div class="nickname">
                <el-link @click="queryUserDetails(scope.row.userBaseInfo.id)"><a :title="scope.row.userBaseInfo.userNickname"> {{ scope.row.userBaseInfo.userNickname }} </a></el-link>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="userSpecialId.account" label="靓号" align="center" />
      <el-table-column prop="userSpecialId.expiredTime" label="过期时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.userSpecialId.expiredTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="userSpecialId.createTime" label="创建时间" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.userSpecialId.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="userSpecialId.updateTime" label="修改时间" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.userSpecialId.updateTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="optUserNickname" label="操作人" align="center" width="80" />
      <el-table-column fixed="right" label="操作" align="center" width="50">
        <template slot-scope="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              <i class="el-icon-more" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="buttonPermissions.includes('user:special:log:table:query:list')" @click.native="clickQueryLog(scope.row)">查看日志</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('user:special:update')" @click.native="clickUpdateAccount(scope.row)">修改靓号</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('user:special:editTime')" @click.native="clickEditTime(scope.row)">编辑时间</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('user:special:custom')" @click.native="clickEditField(scope.row)">自定义属性</el-dropdown-item>
              <el-dropdown-item v-if="buttonPermissions.includes('user:special:del')" @click.native="clickRemove(scope.row)">删除靓号</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="listQuery.lastId" class="load-more">
      <span v-if="notData">已加载全部</span>
      <el-button v-else size="mini" :disabled="loadMoreLoading" :loading="loadMoreLoading" @click="clickLoadMore">加载更多</el-button>
    </div>

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

    <form-edit
      v-if="formEditVisable"
      :row="thatRow"
      :sys-origin="listQuery.sysOrigin"
      @close="formEditClose"
      @success="formEditSuccess"
    />

    <special-log
      v-if="specialLogVisible"
      :user-id="thatRow.userSpecialId.userId"
      @close="specialLogVisible=false"
    />

    <customize-field-dialog
      v-if="customizeFieldDialogVisable"
      :customize-field="thatRow.userSpecialId.customizeField"
      @close="customizeFieldDialogVisable=false"
      @submit="customizeFieldDialogSubmit"
    />
    <el-dialog
      v-loading="submitLoading"
      title="修改靓号"
      width="450px"
      :visible.sync="dialogFormVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :before-close="editAccountClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="editAccountData"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="靓号" prop="newAccount">
          <el-input
            v-model.trim="editAccountData.newAccount"
            placeholder="请输入靓号"
          />
        </el-form-item>
        <el-form-item label="有效期(天)" prop="expiredDays">
          <el-input
            v-model="editAccountData.expiredDays"
            v-number
            placeholder="请输入有效期"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="editAccountData.remark" type="textarea" resize="none" :rows="3" placeholder="请输入备注" maxlength="100" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editAccountClose()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="editSubmit()"
        >
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CustomizeFieldDialog from './customize-field-dialog'
import { shipFreight, deductionFreight, switchStatusFreight } from '@/api/app-user'
import FormEdit from './form-edit'
import SpecialLog from './special-log'
import { sysOriginPlatforms } from '@/constant/origin'
import { mapGetters } from 'vuex'
import { flow, saveOrUpdate, updateExpiredTime, remove, updateAccount } from '@/api/user-special-id'

export default {
  name: 'UserSpecialIdTable',
  components: { FormEdit, SpecialLog, CustomizeFieldDialog },
  data() {
    const commonRules = [
      { required: true, message: '必填字段', trigger: 'blur' }
    ]

    return {
      listQuery: {
        sysOrigin: '',
        userId: '',
        account: '',
        lastId: ''
      },
      list: [],
      listLoading: false,
      customizeFieldDialogVisable: false,
      dialogFormVisible: false,
      submitLoading: false,
      thatRow: {},
      specialLogVisible: false,
      notData: false,
      loadMoreLoading: false,
      // ---
      userInfo: {},
      searchDisabled: false,
      sysOriginPlatforms,
      userDeatilsDrawer: false,
      goldInputBoxVisible: false,
      // true：发货  false：扣除
      type: false,
      thatSelectedUserId: '',
      total: 0,

      formData: {
        userId: '',
        earnPoints: '',
        sysOrigin: '',
        remark: ''
      },
      formRules: {
        userId: commonRules,
        earnPoints: { required: true, message: '必填字段不可为空', trigger: 'blur' },
        sysOrigin: commonRules
      },
      formEditVisable: false,
      editAccountData: {
        id: '',
        newAccount: '',
        expiredDays: '',
        remark: ''
      },
      rules: {
        newAccount: [{ required: true, message: '必填参数不可为空', trigger: 'blur' }],
        expiredDays: [{ required: true, message: '必填参数不可为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'buttonPermissions',
      'permissionsSysOriginPlatforms'
    ])
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
  },
  methods: {
    clickLoadMore() {
      const that = this
      that.loadMoreLoading = true
      that.renderData(false, true)
    },
    renderData(isReset, loadMore) {
      const that = this
      if (isReset === true) {
        that.listQuery.lastId = ''
        that.list = []
      }
      
      that.listQuery.account = that.listQuery.account.length === 0 && that.listQuery.userId.length === 0
          ? 'aaaaa'
          : that.listQuery.account
      that.loadMoreLoading = loadMore
      that.listLoading = !that.loadMoreLoading
      that.searchDisabled = true
      flow(that.listQuery).then(res => {
        that.listLoading = false
        that.loadMoreLoading = false
        that.searchDisabled = false
        const { body } = res
        const list = body || []
        that.notData = list.length <= 0
        if (!that.notData) {
          that.list = that.list.concat(list)
          that.listQuery.lastId = that.list[that.list.length - 1].userSpecialId.timeId
        }
      }).catch(er => {
        that.listLoading = false
        that.loadMoreLoading = false
        that.searchDisabled = false
      })
    },
    clickEditField(row) {
      this.customizeFieldDialogVisable = true
    },
    clickRemove(row) {
      const that = this
      that.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(row.userSpecialId).then(res => {
          that.renderData(true, true)
        }).catch(er => {
          that.$message.error('操作失败')
        })
      }).catch(() => {})
    },
    clickEditTime(row) {
      const that = this
      that.$prompt('请输入天数,负数表示在原有基础上减去天(0.永久)', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^-?\d{1,4}$/,
        inputErrorMessage: '请输入有效数字-9999~9999'
      }).then(({ value }) => {
        updateExpiredTime({
          id: row.userSpecialId.id,
          expiredDays: value
        }).then(res => {
          that.renderData()
        }).catch(er => {
          that.$message.error('操作失败')
        })
      }).catch(() => {})
    },
    clickUpdateAccount(row) {
      const that = this
      that.dialogFormVisible = true
      that.editAccountData.id = row.userSpecialId.id
    },
    editSubmit() {
      const that = this
      that.$refs.dataForm.validate(valid => {
        if (!valid) {
          console.error('submit fial!')
          return false
        }
        that.submitLoading = true
        updateAccount(that.editAccountData).then(res => {
          that.submitLoading = false
          that.editAccountClose()
          that.renderData(true, false)
        }).catch(er => { that.submitLoading = false })
      })
    },
    editAccountClose() {
      this.editAccountData.id = ''
      this.editAccountData.newAccount = ''
      this.editAccountData.expiredDays = ''
      this.editAccountData.remark = ''
      this.dialogFormVisible = false
    },
    clickQueryLog(row) {
      this.specialLogVisible = true
    },
    customizeFieldDialogSubmit(fieldObj) {
      const that = this
      that.customizeFieldDialogVisable = false
      that.submitLoading = true
      that.thatRow.userSpecialId.customizeField = fieldObj
      saveOrUpdate(that.thatRow.userSpecialId).then(res => {
        that.$message.success('操作成功')
      }).catch(er => {
        that.$message.error('操作失败')
      })
    },
    handleMouseEnter(row) {
      this.thatRow = row
    },
    handleCreate() {
      this.thatRow = null
      this.formEditVisable = true
    },
    // --

    handleImageUrl(row) {
      return row.propsCover ? row.propsCover : ''
    },

    handleSearch() {
      this.renderData(true, false)
    },
    queryUserDetails(userId) {
      this.userDeatilsDrawer = true
      this.thatSelectedUserId = userId
    },

    handleClose() {
      this.$emit('close')
    },

    formEditClose() {
      this.formEditVisable = false
    },
    formEditSuccess() {
      this.formEditVisable = false
      this.renderData()
    },
    handleSwitchChange(row) {
      switchStatusFreight(row.id, row.close)
        .then(res => {})
        .catch(er => {
          row.close = !row.close
        })
    },
    showGoldInputBox(row, type) {
      const that = this
      that.type = type

      that.formData = {
        userId: row.userId,
        earnPoints: '',
        sysOrigin: row.sysOrigin,
        remark: ''
      }
      that.goldInputBoxVisible = true
    },
    hideGoldInputBox() {
      const that = this
      that.goldInputBoxVisible = false
    },
    goldSubmit() {
      const that = this

      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        that.listLoading = true
        if (that.type) {
          shipFreight(that.formData).then(res => {
            that.$message.success('操作成功')
            that.goldInputBoxVisible = false
            that.listLoading = false
            that.renderData()
          }).catch(er => {
            that.listLoading = false
            that.$message.error('操作失败')
            console.error(er)
          })
          return
        }

        deductionFreight(that.formData).then(res => {
          that.$message.success('操作成功')
          that.goldInputBoxVisible = false
          that.listLoading = false
          that.renderData()
        }).catch(er => {
          that.listLoading = false
          that.$message.error('操作失败')
          console.error(er)
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.load-more {
  padding: 20px;
  text-align: center;
}
</style>
