<template>
  <div :class="queryBackOperation ? 'app-container-inside' : 'app-container'">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        :placeholder="$t('pages.userFreightInfoList.filter.system')"
        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>
      <div class="filter-item">
        <account-input
          v-model="listQuery.userId"
          :sys-origin="listQuery.sysOrigin"
          :placeholder="$t('pages.userFreightInfoList.filter.sender')"
        />
      </div>
      <div class="filter-item">
        <account-input
          v-model="listQuery.acceptUserId"
          :sys-origin="listQuery.sysOrigin"
          :placeholder="$t('pages.userFreightInfoList.filter.receiver')"
        />
      </div>
      <el-select
        v-model="listQuery.origin"
        :placeholder="$t('pages.userFreightInfoList.filter.origin')"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in freightBalanceOrigin"
          :key="item.value"
          :label="getFreightBalanceOriginName(item)"
          :value="item.value"
        />
      </el-select>

      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          :range-separator="$t('pages.userFreightInfoList.date.rangeSeparator')"
          :start-placeholder="$t('pages.userFreightInfoList.date.start')"
          :end-placeholder="$t('pages.userFreightInfoList.date.end')"
        />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        {{ $t('pages.userFreightInfoList.action.search') }}
      </el-button>
      <el-button
        v-if="buttonPermissions.includes('user:table:freightwarter:export')"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="exprotOrder"
      >
        {{ $t('pages.userFreightInfoList.action.export') }}
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column prop="sysOrigin" :label="$t('pages.userFreightInfoList.table.system')" align="center" width="80">
        <template slot-scope="scope">
          <sys-origin-icon
            :icon="scope.row.sysOrigin"
            :desc="scope.row.sysOrigin"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.userFreightInfoList.table.user')" align="center" min-width="240">
        <template slot-scope="scope">
          <user-table-exhibit
            :user-profile="scope.row.userBaseInfo"
            :query-details="true"
            :tag-name="scope.row.operationUserNickname"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.userFreightInfoList.table.receiver')" align="center" min-width="240">
        <template slot-scope="scope">
          <user-table-exhibit
            :user-profile="scope.row.acceptUser"
            :query-details="true"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.userFreightInfoList.table.type')" align="center" min-width="100">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.type === 0">{{ $t('pages.userFreightInfoList.type.income') }}</span>
            <span v-if="scope.row.type === 1">{{ $t('pages.userFreightInfoList.type.expense') }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.userFreightInfoList.table.quantity')" align="center" min-width="100">
        <template slot-scope="scope">
          <div>
            <span
              v-if="scope.row.type === 0"
              class="font-danger"
            >+{{ scope.row.quantity }}</span>
            <span v-if="scope.row.type === 1">-{{ scope.row.quantity }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="balance"
        :label="$t('pages.userFreightInfoList.table.balance')"
        align="center"
        min-width="100"
      />
      <el-table-column
        prop="amount"
        :label="$t('pages.userFreightInfoList.table.amount')"
        align="center"
        min-width="100"
      />
      <el-table-column
        prop="originName"
        :label="$t('pages.userFreightInfoList.table.origin')"
        align="center"
        min-width="100"
      />
      <el-table-column
        prop="remark"
        :label="$t('pages.userFreightInfoList.table.remark')"
        align="center"
        min-width="200"
      />
      <el-table-column
        prop="createTime"
        :label="$t('pages.userFreightInfoList.table.createdAt')"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <el-drawer
      :title="$t('pages.userFreightInfoList.exportDialog.title')"
      :visible="exportConditionVisible"
      :before-close="exportConditionClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div class="exprot-select">
        <div class="drawer-form">
          <el-form
            ref="exportQuery"
            :rules="exportQueryRules"
            :model="exportQuery"
            label-position="left"
            label-width="70px"
          >
            <el-form-item :label="$t('pages.userFreightInfoList.exportDialog.system')" prop="sysOrigin">
              <el-select
                v-model="exportQuery.sysOrigin"
                :placeholder="$t('pages.userFreightInfoList.exportDialog.system')"
                style="width: 100%;"
                class="filter-item"
              >
                <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-form-item>

            <el-form-item :label="$t('pages.userFreightInfoList.exportDialog.month')" prop="monthDate">
              <el-date-picker
                v-model="exportQuery.monthDate"
                type="month"
                value-format="yyyyMM"
                :placeholder="$t('pages.userFreightInfoList.exportDialog.selectMonth')"
                style="width: 100%;"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button @click="exportConditionClose()">{{ $t('pages.userFreightInfoList.action.close') }}</el-button>
          <el-button
            type="primary"
            :disabled="exportLoading"
            :loading="exportLoading"
            @click="exportConditionSubmit()"
          >{{ $t('pages.userFreightInfoList.action.export') }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { pageRunningWater, exportFreightWaters } from '@/api/app-user'
import { freightBalanceOrigin } from '@/constant/type'
import { pickerOptions } from '@/constant/el-const'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
export default {
  name: 'UserFreightInfoList',
  components: { Pagination },
  props: {
    queryBackOperation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const commonRules = [
      { required: true, message: this.$t('pages.userFreightInfoList.validation.requiredField'), trigger: 'blur' }
    ]
    return {
      list: [],
      total: 0,
      freightBalanceOrigin,
      thatSelectedUserId: '',
      thatSelectedAcceptUserId: '',
      searchDisabled: false,
      pickerOptions,
      listQuery: {
        cursor: 1,
        limit: 20,
        userId: '',
        acceptUserId: '',
        origin: '',
        sysOrigin: '',
        queryBackOperationUser: false
      },
      listLoading: false,
      rangeDate: '',
      exportConditionVisible: false,
      exportLoading: false,
      exportQuery: {
        monthDate: '',
        sysOrigin: ''
      },
      exportQueryRules: {
        monthDate: commonRules,
        sysOrigin: commonRules
      }
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms', 'buttonPermissions'])
  },
  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 = ''
      }
    },
    queryBackOperation: {
      immediate: true,
      deep: true,
      handler(newVal) {
        this.listQuery.queryBackOperationUser = newVal === true
      }
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
  },
  methods: {
    renderData() {
      const that = this
      that.listLoading = true
      pageRunningWater(that.listQuery)
        .then(res => {
          const { body } = res
          that.total = body.total || 0
          that.list = body.records
          that.listLoading = false
        })
        .catch(er => {
          that.listLoading = false
          console.error(er)
        })
    },
    handleSearch() {
      this.renderData(true)
    },
    getFreightBalanceOriginName(origin) {
      const value = origin && origin.value ? origin.value : origin
      const fallback = origin && origin.name ? origin.name : value
      const key = `pages.userFreightInfoList.origin.${value}`
      const label = this.$t(key)
      return label === key ? fallback : label
    },
    exportConditionClose() {
      if (this.exportLoading) {
        this.$opsMessage.warn(this.$t('pages.userFreightInfoList.message.exporting'))
        return
      }
      this.exportConditionVisible = false
    },
    exprotOrder() {
      this.exportConditionVisible = true
    },
    exportConditionSubmit() {
      const that = this
      that.$refs.exportQuery.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return false
        }
        that.exportLoading = true
        exportFreightWaters(
          that.exportQuery,
          `FreightWaters ${that.exportQuery.monthDate}`
        )
          .then(res => {
            that.exportLoading = false
            that.exportConditionVisible = false
          })
          .catch(er => {
            that.exportLoading = false
            this.$opsMessage.fail(this.$t('pages.userFreightInfoList.message.downloadFailed'))
          })
      })
    }
  }
}
</script>
<style scoped lang="scss">
.user-css {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 0.15rem;
  line-height: 0.3rem;
  padding: 0.02rem;
  border-radius: 0.04rem;
}
</style>
