<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-group ">
        <div class="filter-lable">
          企业名称：
        </div>
        <div class="filter-width">
          <el-input v-model="KEYWORDS" placeholder="搜索" class="filter-item"/>
        </div>
      </div>
      <div class="filter-group">
        <div class="filter-lable">
          属地：
        </div>
        <div class="filter-width">
          <el-cascader id="POSSESSION" ref="POSSESSION" v-model="POSSESSION" :options="areaList" :props="areaProps" placeholder="请选择属地"/>
          <!--            <el-date-picker v-model="dates" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd" class="filter-item" />-->
        </div>
      </div>
      <div class="filter-group mr-10">
        <div class="filter-lable">
          开户人：
        </div>
        <div class="filter-width">
          <el-input v-model="CREATOR" placeholder="开户人" class="filter-item" />
        </div>
      </div>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
        重置
      </el-button>

    </div>
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :data="varList"
      :row-key="getRowKey"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      :row-class-name="tableRowClassName"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        :reserve-selection="true"
        type="selection"
        width="55"
        align="center"/>
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="CORP_NAME" label="企业名称" />
      <el-table-column prop="CREATTIME" label="开户日期" />
      <el-table-column prop="CREATOR" label="开户人" />
      <el-table-column prop="COMPANY_AREA" label="所属区域" />
      <el-table-column prop="VIPLEVELNAME" label="会员级别" />
      <el-table-column prop="usage" label="内存用量(MB)" >
        <template slot-scope="{row}">
          {{ fixNumber(row.TOTAL_USAGE) }}
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      KEYWORDS: '',

      varList: [],
      pd: [],
      form: { },
      dates: [],
      areaList: [], // 属地
      areaProps: {
        lazy: true,
        lazyLoad: this.lazyLoad,
        value: 'numValue',
        id: 'id',
        label: 'label',
        children: 'children',
        checkStrictly: true
      },
      POSSESSION: [],
      validityList: [
        { 'ID': '30', 'NAME': '一个月' },
        { 'ID': '90', 'NAME': '三个月' }
      ],
      formList: [
        { 'ID': '1', 'NAME': '一年' },
        { 'ID': '2', 'NAME': '两年' },
        { 'ID': '3', 'NAME': '三年' },
        { 'ID': '4', 'NAME': '四年' },
        { 'ID': '5', 'NAME': '五年' }
      ],
      VALIDITY: '',
      CREATOR: '',
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogFormDeliver: false,
      dialogFormRenew: false,
      dialogType: 'add',
      rules: {
        USE_DATE_START: [{ required: true, message: '有效使用起始时间不能为空', trigger: 'blur' }],
        USE_DATE_END: [{ required: true, message: '有效使用结束时间不能为空', trigger: 'blur' }]
      },
      deliverRules: {

        DELIVERDATE: [{ required: true, message: '交付日期不能为空', trigger: 'blur' }],
        TERM: [{ required: true, message: '有效期不能为空', trigger: 'blur' }]
      },
      renewRules: {

        TERM: [{ required: true, message: '有效期不能为空', trigger: 'blur' }]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  created() {
    this.getList(this.ROLE_ID)

    this.getDictByDicId('e725d2a91b8248f4b8f49889038df7de').then(data => {
      this.areaList = data
    })
  },
  methods: {
    fixNumber(num) {
      if (num) {
        return (num / 1000 / 1000).toFixed(2)
      } else {
        return 0
      }
    },
    // 加载级联的方法
    lazyLoad(nodeValue, resolve) {
      if (nodeValue.data && (!nodeValue.children || nodeValue.children.length == 0)) {
        this.getDictByDicId(nodeValue.data.id).then(data => {
          resolve(data)
        })
      } else {
        resolve(null)
      }
    },
    getRowKey(row) {
      return row.CORPINFO_ID
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      this.POSSESSION
      var possession = ''
      var possessionLevel = ''
      if (this.POSSESSION && this.POSSESSION.length > 0) {
        possession = this.POSSESSION[this.POSSESSION.length - 1]
        possessionLevel = this.POSSESSION.length
      }
      requestFN(
        '/corpinfo/listUsage?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          CREATOR: this.CREATOR,
          ISSMALL: '2',
          PAGETYPE: '1',
          POSSESSION: possession,
          POSSESSIONLEVEL: possessionLevel,
          VALIDITY: this.VALIDITY,
          DELIVERSTARTTIME: this.dates[0],
          DELIVERENDTIME: this.dates[1]
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 重置
    goKeyReset() {
      this.KEYWORDS = ''
      this.CREATOR = ''
      this.VALIDITY = ''
      this.dates = []
      this.POSSESSION = []

      this.getQuery()
    },
    goDeliver(id) {
      this.form = {}
      this.form.CORPINFO_ID = id
      this.dialogFormDeliver = true
    },
    goRenew(id) {
      this.form = {}
      this.form.CORPINFO_ID = id
      this.dialogFormRenew = true
    },

    deliver(operationType) {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.OPERATIONTYPE = operationType
          const loading = this.$loading({
            lock: true,
            text: '提交中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          requestFN(
            '/corpinfo/deliver',
            this.form
          ).then((data) => {
            loading.close()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.dialogFormDeliver = false
            this.getList()
          }).catch((e) => {
            loading.close()
          })
        } else {
          return false
        }
      })
    },
    renew() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '提交中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          requestFN(
            '/corpinfo/renew',
            this.form
          ).then((data) => {
            loading.close()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.dialogFormRenew = false
            this.getList()
          }).catch((e) => {
            loading.close()
          })
        } else {
          return false
        }
      })
    },
    closeDeliver() {
      this.form = {}
      this.dialogFormDeliver = false
    },
    // 判断按钮权限，用于是否显示按钮
    hasButton: function() {
      var keys = 'corpinfo:add,corpinfo:del,corpinfo:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.corpinfofhadminadd		// 新增权限
        this.del = data.corpinfofhadmindel		// 删除权限
        this.edit = data.corpinfofhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取数据字典数据
    getDict: function() {
    },

    // 获取数据字典数据
    getDictByDicId(dicId) {
      var dicListVal = []
      return new Promise((resolve) => {
        let id = ''
        if (!dicId) {
          id = '0'
        } else {
          id = dicId
        }
        requestFN(
          '/dictionaries/getLevelsAndSCount',
          {
            DICTIONARIES_ID: id
          }
        ).then((data) => {
          if (data.list.length > 0) {
            dicListVal = data.list.map((e) => {
              if (e.zcount == '0') {
                return { value: e.DICTIONARIES_ID.toString(), numValue: e.BIANMA.toString(), label: e.NAME, id: e.DICTIONARIES_ID, leaf: true }
              } else {
                return { value: e.DICTIONARIES_ID.toString(), numValue: e.BIANMA.toString(), label: e.NAME, id: e.DICTIONARIES_ID, children: [], leaf: false }
              }
            })
          } else {
            dicListVal = undefined
          }
          return resolve(dicListVal)
        }).catch((e) => {
        })
      })
    },
    resetForm() {
      this.form = {
        CORPINFO_ID: '' // 备注1
      }
    },
    // 登录企业
    goLogin: function(id) {
      this.$confirm('确定要进入系统吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/corpinfo/goLogin',
          {
            CORPINFO_ID: id
          }
        ).then((data) => {
          this.listLoading = false
          // if (data.USERNAME != 'admin') {
          window.open(config.qyurl + 'static/bi/admin_to_loading.html?qa=' + encodeURI(data.users.USERNAME) + '&zy=' + encodeURI(data.users.PASSWORD), '_blank')
          // }
          // else {
          //   window.open('https://qask.qhdsafety.com/bi/loading.html?qa=' + encodeURI(data.users.USERNAME) + '&zy=' + encodeURI(data.users.PASSWORD), '_blank')
          // }
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    resetPwd(id) {
      this.$confirm('确定要进行密码重置吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/corpinfo/resetPwd',
          {
            corpInfo: id,
            tm: new Date().getTime()
          }
        ).then((data) => {
          if (data.result == 'success') {
            this.$message({
              message: '重置成功',
              type: 'success'
            })
          } else {
            alert(data.msg)
            this.$message({
              message: data.msg,
              type: 'success'
            })
          }
          this.listLoading = false
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    updateISuse(id) {
      this.$confirm('确定要禁用吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/corpinfo/updateISuse',
          {
            CORPINFO_ID: id
          }
        ).then(() => {
          this.$message({
            message: '禁用成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    goupdateISuse(id) {
      // dialogFormEdit" :title="dialogType==='edit'
      this.dialogFormEdit = true
      this.dialogType = 'edit'
      this.form.CORPINFO_ID = id
    },
    goupdateISuseSave() {
      if (this.form.USE_DATE_END < this.form.USE_DATE_START) {
        this.$message({
          message: '结束时间不能早于开始时间',
          type: 'error'
        })
        this.form.USE_DATE_END = ''
        return false
      }
      this.listLoading = true
      requestFN(
        '/corpinfo/updateuse',
        {
          CORPINFO_ID: this.form.CORPINFO_ID,
          USE_DATE_START: this.form.USE_DATE_START,
          USE_DATE_END: this.form.USE_DATE_END
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.$message({
            message: '保存成功',
            type: 'info'
          })
          this.varList = []
          this.getList()
        }
        this.listLoading = false
        this.dialogFormEdit = false
      }).catch((e) => {
        this.listLoading = false
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (!row.REMAININGTIME) {
        return
      }
      if (row.REMAININGTIME <= 30) {
        return 'yellow-row'
      } else if (row.REMAININGTIME > 30 && row.REMAININGTIME <= 90) {
        return 'green-row'
      }
      return ''
    },
    judgeTime(startTime) {
      startTime = startTime.replace(/\-/g, '/')
      var endTime = new Date()
      var sTime = new Date(startTime) // 开始时间
      var eTime = new Date(endTime) // 结束时间
      var timeType = 1000 * 3600 * 24
      var differDay = (eTime.getTime() - sTime.getTime()) / timeType
      var nineMon = 270
      var oneYear = 365
      if (differDay >= oneYear) {
        return 2
      }
      if (differDay >= nineMon) {
        return 1
      }
      return 0
    }
  }
}

</script>
<style>
  .el-table .yellow-row {
    background: rgba(248, 231, 28, 0.2);

  }

  .el-table .red-row {
    background: rgba(252, 2, 33, 0.2);
  }
  .el-table .green-row {
    background: rgba(26, 208, 22, 0.2);
  }

</style>
<style lang="sass" scoped>
  .filter-container
    position: relative
    .filter-flot
      position: absolute
      right: 0
      top: 0
</style>
