<template>
  <div class="app-warp">
    <div class="app-structure">
      <div class="app-search">
        <div class="app-search-form">
          <div class="form-item four_more">
            <label>机构（企业）名称：</label>
            <el-input v-model="KEYWORDS" placeholder="搜索" class="filter-item"/>
          </div>
          <div class="form-item four_more">
            <label>类型：</label>
            <el-select v-model="TYPE" placeholder="请选择">
              <el-option v-for="item in typeList" :key="item.DICTIONARIES_ID" :label="item.NAME" :value="item.DICTIONARIES_ID" />
            </el-select>
          </div>
          <div v-show="!searchFromCollapse" class="form-item four_more">
            <label > 状态：</label>
            <el-select v-model="ISUSE" placeholder="请选择" class="input_def">
              <el-option v-for="item in isUseList" :key="item.ID" :label="item.NAME" :value="item.ID" />
            </el-select>
          </div>
          <div v-show="!searchFromCollapse" class="form-item four_more">
            <label>属地：</label>
            <el-input v-model="COMPANY_AREA" placeholder="搜索" class="filter-item"/>
          </div>
          <div v-show="!searchFromCollapse" class="form-item four_more"/>
          <div class="form-item text-right">
            <el-button v-waves type="primary" icon="el-icon-search" @click="getQuery">
              搜索
            </el-button>
            <el-button v-waves icon="el-icon-refresh" @click="goKeyReset">
              重置
            </el-button>
            <el-button v-if="searchFromCollapse==true" type="text" @click="searchFromCollapse = false">展开 <i class="el-icon-arrow-down"/></el-button>
            <el-button v-else type="text" @click="searchFromCollapse = true">合并 <i class="el-icon-arrow-up"/></el-button>
          </div>
        </div>
      </div>
      <div class="app-tools">
        <div class="app-function">
          <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        </div>
        <div class="app-minbtn">
          <span class="screening">
            <el-dropdown trigger="click">
              <el-button type="text" icon="el-icon-finished"/>
              <el-dropdown-menu slot="dropdown" style="margin-top:3px;">
                <div class="app-checkbox-group">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox v-for="item in headList" :key="item.prop" :label="item" style="display:block;" >{{ item.label }}</el-checkbox>

                  </el-checkbox-group>
                </div>
              </el-dropdown-menu>
            </el-dropdown>
          </span>

          <el-button type="text" icon="el-icon-refresh-left"/>
          <el-button type="text" icon="el-icon-full-screen"/>
        </div>
      </div>
      <div class="app-container">
        <el-table
          v-loading="listLoading"
          ref="multipleTable"
          :data="varList"
          :row-key="getRowKey"
          :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
          :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="CONTACTS" label="主要负责人" />
          <el-table-column prop="CONTACTS_PHONE" label="电话" />
          <el-table-column prop="COMPANY_AREA" label="属地" />
          <el-table-column prop="CREATOR" label="状态" width="100" align="center" >
            <template slot-scope="{row}">
              <template v-if="row.ISUSE=='1'"><span class="status-dot status-green"/>启用</template>
              <template v-else-if="row.ISUSE=='0'"><span class="status-dot status-red"/>禁用</template>
            </template>

          </el-table-column>
          <el-table-column prop="TYPENAME" label="类型" />
          <el-table-column label="操作" align="center" width="280">
            <template slot-scope="{row}">
              <el-button v-show="edit" type="text" @click="resetPwd(row.CORPINFO_ID)">重置密码</el-button>
              <span class="app-divider"/>
              <el-button v-show="edit" type="text" @click="handleEdit(row.CORPINFO_ID)">编辑</el-button>
              <span class="app-divider"/>
              <el-button type="text" @click="handleView(row.CORPINFO_ID)">查看</el-button>
              <span v-if="row.ISUSE=='1'" class="app-divider"/>
              <el-button v-if="row.ISUSE=='1'" type="text" class="color-red" @click="updateISuse(row.CORPINFO_ID,'0')">禁用</el-button>
              <span v-if="row.ISUSE=='0'" class="app-divider"/>
              <el-button v-if="row.ISUSE=='0'" type="text" class="color-green" @click="updateISuse(row.CORPINFO_ID,'1')">启用</el-button>

            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-btn-group">
        <div/>
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
    </div>
    <el-dialog :visible.sync="dialogFormDeliver" title="交付" width="600px">
      <el-form ref="form" :rules="deliverRules" :model="form" label-width="110px" style="width: 500px;">
        <el-form-item label="交付日期" prop="DELIVERDATE">
          <el-date-picker id="DELIVERDATE" ref="DELIVERDATE" v-model="form.DELIVERDATE" :picker-options="pickerOptions" value-format="yyyy-MM-dd" format="yyyy-MM-dd" style="width: 100%" type="date" placeholder="交付日期"/>
        </el-form-item>
        <el-form-item label="使用期限" prop="TERM">

          <el-select v-model="form.TERM" placeholder="请选择">
            <el-option v-for="item in formList" :key="item.ID" :label="item.NAME" :value="item.ID" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDeliver">取 消</el-button>
        <el-button type="warning" @click="deliver(1)">清 除</el-button>
        <el-button type="primary" @click="deliver(2)">确 定</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog :visible.sync="dialogFormRenew" title="续费" width="600px">
      <el-form ref="form" :rules="renewRules" :model="form" label-width="110px" style="width: 500px;">

        <el-form-item label="使用期限" prop="TERM">
          <el-select v-model="form.TERM" placeholder="请选择">
            <el-option v-for="item in formList" :key="item.ID" :label="item.NAME" :value="item.ID" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeRenew">取 消</el-button>
        <el-button type="primary" @click="renew()">确 定</el-button>
      </div>
    </el-dialog> -->

    <el-dialog :visible.sync="dialogFormEdit" :title="dialogType==='edit'?'修改':'新增'" width="600px">
      <el-form ref="form" :rules="rules" :model="form" label-width="110px" style="width: 500px;">
        <el-form-item label="有效使用起始时间" prop="USE_DATE_START">
          <el-date-picker
            v-model="form.USE_DATE_START"
            type="date"
            placeholder="选择日期"/>
        </el-form-item>
        <el-form-item label="有效使用结束时间" prop="USE_DATE_END">
          <el-date-picker
            v-model="form.USE_DATE_END"
            type="date"
            placeholder="选择日期"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="goupdateISuseSave">确 定</el-button>
      </div>
    </el-dialog>
  </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 {
      searchFromCollapse: true,
      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
      },
      COMPANY_AREA: '',
      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()
        }
      },

      // 新增的字段
      TYPE: '',
      ISUSE: '',
      isUseList: [
        { ID: '0', NAME: '禁用' },
        { ID: '1', NAME: '启用' }
      ],
      typeList: [],
      headList: [],
      checkList: []
    }
  },
  created() {
    this.getList()
    this.getDict()
  },
  methods: {

    // 加载级联的方法
    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

      requestFN(
        '/corpinfo/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          TYPE: this.TYPE,
          ISUSE: this.ISUSE,
          COMPANY_AREA: this.COMPANY_AREA
        }
      ).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.COMPANY_AREA = ''
      this.KEYWORDS = ''
      this.TYPE = ''
      this.ISUSE = ''
      this.listQuery = {
        page: 1,
        limit: 10
      }
      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
    },
    // 添加
    handleAdd() {
      this.$parent.CORPINFO_ID = ''
      this.$parent.activeName = 'CorpEdit'
    },
    // 修改
    handleEdit(ID) {
      this.$parent.CORPINFO_ID = ID
      this.$parent.activeName = 'CorpEdit'
    },
    // 详情
    handleView(ID) {
      this.$parent.CORPINFO_ID = ID
      this.$parent.activeName = 'CorpView'
    },
    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          requestFN(
            '/corpinfo/' + this.dialogType,
            this.form
          ).then((data) => {
            this.listLoading = false
            this.dialogFormEdit = false
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },

    handleDelete(id) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/corpinfo/delete',
          {
            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(() => {
      })
    },

    batchDel() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.CORPINFO_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/corpinfo/deleteAll',
          {
            DATA_IDS: ids
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 判断按钮权限，用于是否显示按钮
    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() {
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: 'e2c777c811954e7285349684525aa26b'
        }
      ).then((data) => {
        this.typeList = data.list
      }).catch((e) => {
      })
    },

    // 获取数据字典数据
    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('http://192.168.0.18:8080/static/bi/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 {
            this.$message({
              message: data.message,
              type: 'success'
            })
          }
          this.listLoading = false
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    updateISuse(id, isuse) {
      var msg = '启用'
      if (isuse == '0') {
        msg = '禁用'
      }
      this.$confirm('确定要' + msg + '吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/corpinfo/updateISuse',
          {
            CORPINFO_ID: id,
            ISUSE: isuse
          }
        ).then((res) => {
          this.$message({
            message: msg + '成功',
            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>
