<template>
  <div class="app-container">
    <!-- 顶部操作区域 -->
    <div class="filter-container">
      <div class="filter-control">
        <span>服务商名称:</span>
        <el-input
          v-model="listQuery.name"
          placeholder="关键词"
          clearable
          @keyup.enter.native="getList"
          @clear="getList"
        />
      </div>
      <div class="filter-control">
        <span>服务商级别:</span>
        <el-select v-model="listQuery.serviceLevel" placeholder="请选择服务商级别" @change="getList">
          <el-option
            v-for="(i, index) in serviceLevel"
            :key="index"
            :label="i.value"
            :value="i.id"
          />
        </el-select>
      </div>
      <div class="filter-control">
        <span>服务商类型:</span>
        <el-select v-model="listQuery.serviceCategory" placeholder="服务商类型" @change="getList">
          <el-option
            v-for="(i, index) in serviceCategoryList"
            :key="index"
            :label="i.value"
            :value="i.id"
            @change="getList"
          />
        </el-select>
      </div>
      <div class="filter-control">
        <span>资格证书编号:</span>
        <el-input
          v-model="listQuery.qualificationId"
          placeholder="关键词"
          clearable
          @keyup.enter.native="getList"
          @clear="getList"
        />
      </div>
      <div class="filter-control">
        <span>授权起止日期:</span>
        <el-date-picker
          v-model="time"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="getList"
        />
      </div>
      <div class="filter-control">
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button type="primary" @click="$router.push('/service/settlement/edit')">添加</el-button>
        <el-button type="primary" @click="batchOffline(3)">下线</el-button>
        <el-button type="primary" @click="batchOffline(1)">下载资格证书</el-button>
        <el-button type="primary" @click="batchOffline(2)">下载二维码</el-button>
      </div>
    </div>

    <el-table
      ref="table"
      v-loading="isLoading"
      :data="list"
      border
      :default-sort="{ prop: 'frequency', order: 'descending' }"
      @selection-change="handleSelectionChange"
    >
      <!--<el-table-column type="selection" width="55" align="center" />-->
      <el-table-column
        label="序号"
        type="index"
        sortable="custom"
        align="center"
        width="80"
      />
      <el-table-column prop="name" label="服务商名称" align="center" />
      <el-table-column prop="serviceLevel" label="服务商级别" align="center">
        <template slot-scope="scope">
          <div>
            {{
              scope.row.serviceLevel == "1"
                ? "一级"
                : scope.row.serviceLevel == "2"
                  ? "二级"
                  : "三级"
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="serviceCategory" label="服务商类型" align="center">
        <template slot-scope="scope">
          <div>
            {{ scope.row.serviceCategory == "1" ? "个人" : "企业" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="contractStartDate" label="授权起始日期" align="center" />
      <el-table-column prop="contractEndDate" label="授权截止日期" align="center" />
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <div>
            已{{ scope.row.status === 90 ? "上线" : "下线" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="添加时间" align="center" />
      <el-table-column prop="createBy" label="创建人" align="center" />
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="{ row }">
          <div class="labelCenter">
            <el-button
              type="primary"
              size="mini"
              @click="handleStatus({ userIds: row.userId, status: row.status })"
            >{{ row.status === 91 ? "上线" : "下线" }}</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="$router.push('/service/settlement/edit?id=' + row.id)"
            >编辑</el-button>
            <el-button type="primary" size="mini" @click="showQrCode(row)">二维码</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="
                $router.push('/service/settlement/contract/list?providersId=' + row.id)
              "
            >合同管理</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <qr-code
      ref="qrCode"
      :item-obj="providerItem"
      :show-qr-code="showQrImag"
      @showQrCode="showQrCode"
    />

    <el-dialog title="选择服务商" :visible.sync="exportDialogVisible" width="70%">
      <service-list-selector
        v-if="exportDialogVisible"
        @cancel="onSelectorCancel"
        @confirm="onSelectorConfirm"
      />
    </el-dialog>

    <!-- 页码 -->
    <pagination
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import QrCode from '../components/CmQrcode/index.vue'
import ServiceListSelector from '../components/ServiceListSelector.vue'
import { getProviderList, updatedStatus } from '@/api/serviceSettlement/service'
import serviceMixin from '../mixin/index'

export default {
  components: {
    QrCode,
    ServiceListSelector
  },
  mixins: [serviceMixin],
  data() {
    return {
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        serviceCategory: '',
        serviceLevel: ''
      },
      time: '',
      showQrImag: false,
      isLoading: false,
      exportDialogVisible: false,
      list: [],
      indexMethod: 1,
      total: 0,
      selectType: 0,
      providerItem: {}
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    async getList(obj) {
      const form = Object.assign(this.listQuery, {
        contractStartDate: obj ? obj[0] : '',
        contractEndDate: obj ? obj[1] : '',
        providersId: this.providersId || ''
      })
      const { data } = await getProviderList(form)
      this.list = data.results
      this.total = data.totalRecord
    },
    showQrCode($event) {
      if ($event) {
        this.providerItem = $event
      }
      this.showQrImag = !this.showQrImag
    },
    // 批量下线
    batchOffline(type) {
      this.selectType = type
      this.exportDialogVisible = true
    },
    handleSelectionChange() {},
    async handleStatus($event) {
      this.$confirm(`是否${$event.status === 91 ? '上线' : '下线'}该服务商?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const data = await updatedStatus({
            userIds: $event.userIds,
            status: $event.status === 91 ? 90 : 91
          })
          if (data.code === 0) {
            this.$message({
              message: '更新成功',
              type: 'success'
            })
            this.getList()
          }
        } catch (error) {
          console.log(error)
        }
      })
    },
    onSelectorCancel() {
      this.exportDialogVisible = false
    },
    downLoadImage(options) {
      try {
        this.$confirm('是否下载所选的内容?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          this.isLoading = true
          // 使用a链接下载
          const downUrl = `${process.env.VUE_APP_BASE_API}/providers/download/image?ids=${options.ids}&type=${options.type}`
          const confirmText = options.type === 1 ? '服务商资格证书' : '服务商二维码'
          this.downloadWithUrl(downUrl, confirmText)
            .catch((err) => {
              console.log(err)
              this.$message.error(`下载${confirmText}失败`)
            })
            .finally(() => {
              this.isLoading = false
            })
        })
      } catch (error) {
        console.log(error)
      }
    },
    onSelectorConfirm($event) {
      this.exportDialogVisible = false
      const toSelect = {
        3: () =>
          this.handleStatus({
            userIds: $event.map((e) => e.userId).join(','),
            status: 90
          }),
        1: () =>
          this.downLoadImage({
            ids: $event.map((e) => e.id).join(','),
            type: this.selectType
          }),
        2: () =>
          this.downLoadImage({
            ids: $event.map((e) => e.id).join(','),
            type: this.selectType
          })
      }
      toSelect[this.selectType]()
    }
  }
}
</script>

<style lang="scss" scoped>
.labelCenter {
  display: grid;
  grid-template-rows: repeat(2, 1fr);
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 10px;
  .el-button {
    width: 80px;
    margin-left: 0;
  }
}
</style>
