<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      机构列表
    </h2>
    <div class="m-core">
      <save-form
        :inline="true"
        class="searchForm"
        ref="searchForm"
        @submit="search"
        @reset="reset"
        :saveKey="'platformServiceManager'"
        :model.sync="searchForm"
      >
        <el-form-item :rules="[]">
          <el-input v-model="searchForm.search" placeholder="机构编号/名称/电话"></el-input>
        </el-form-item>
        <el-form-item prop="createTimer">
          <el-date-picker
            v-model.trim="searchForm.createTimer"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :picker-options="{ firstDayOfWeek: 1 }"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="createdName">
          <el-input v-model="searchForm.createdName" placeholder="请输入添加人"></el-input>
        </el-form-item>
        <el-form-item prop="payState">
          <el-select
            v-model.trim="searchForm.payState"
            filterable
            placeholder="请选择支付状态"
            clearable
          >
            <el-option label="未缴费" :value="0"></el-option>
            <el-option label="已缴费" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="state">
          <el-select
            v-model.trim="searchForm.state"
            filterable
            placeholder="请选择机构状态"
            clearable
          >
            <!-- <el-option label="草稿" :value="0"></el-option> -->
            <el-option label="启动" :value="1"></el-option>
            <el-option label="停用" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
          <el-button native-type="reset" type="primary">重置</el-button>
        </el-form-item>
      </save-form>
      <el-button  style="margin-bottom: 20px;" type="primary" v-permission="'tenantInfo/add'" @click="openService('create')" icon="el-icon-plus">新增机构</el-button>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table
          :data="tableList"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        >
          <el-table-column align="center" prop="id" label="机构编号">
          </el-table-column>
          <el-table-column align="center" label="机构名称" prop="name">
          </el-table-column>
          <el-table-column align="center" label="联系人" prop="contacts">
          </el-table-column>
          <el-table-column align="center" label="联系人电话" prop="phone">
          </el-table-column>
          <el-table-column align="center" label="服务" prop="serveName">
          </el-table-column>
          <el-table-column align="center" label="人数" prop="studentUpLimit">
            <template slot-scope="scope">
              {{ scope.row.studentCount }}/{{ scope.row.studentUpLimit }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="有效期到期时间" prop="expireDate">
            <template slot-scope="scope">
              {{ scope.row.expireDate | formatTimer }}
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" label="网络教室剩余时长" prop="productName">
          </el-table-column> -->
          <el-table-column align="center" label="缴费状态" prop="payState">
            <template slot-scope="scope">
              {{ scope.row.payState | organPayState }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="添加人" prop="createdName">
          </el-table-column>
          <el-table-column align="center" label="机构状态" prop="state">
            <template slot-scope="scope">
              {{ scope.row.state | organState }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                @click="openService('look', scope.row)"
                v-permission="'tenantInfo/info'"
                type="text"
                >查看</el-button>
              <el-button
                @click="openService('update', scope.row)"
                v-permission="'tenantInfo/update'"
                type="text"
                >修改</el-button>
              <el-button
                @click="changeOrgan(scope.row)"
                v-permission="scope.row.state == 1 ? 'tenantInfo/opsState/stop' : 'tenantInfo/opsState/open'"
                type="text"
                >{{ scope.row.state == 1 ? '停用' : '启用' }}</el-button>
              <el-button
                v-if="scope.row.payState != 1"
                @click="onQrCode(scope.row)"
                type="text"
                >缴费二维码</el-button>
              <el-button
                v-if="scope.row.payState === 1 && $helpers.permission('tenantContractRecord/queryPage')"
                 @click="onDownloadProtocol(scope.row)"
                type="text"
                >下载协议</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
        :saveKey="'platformServiceManager'"
          sync
          :total.sync="pageInfo.total"
          :page.sync="pageInfo.page"
          :limit.sync="pageInfo.limit"
          :page-sizes="pageInfo.page_size"
          @pagination="getList"
        />
      </div>
    </div>
    <qr-code v-model="qrcodeStatus" title="机构缴费二维码" :codeUrl="codeUrl" />

    <el-dialog title="协议下载" :visible.sync="protocolVisible" width="650px">
      <protocol-model v-if="protocolVisible" @close="protocolVisible = false" :protocolVersions="protocolVersions" />
    </el-dialog>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import QrCode from "@/components/QrCode/index";
import protocolModel from '@/views/studentManager/modals/protocolModel';
import { tenantInfoQueryPage , tenantInfoOpsState, tenantContractRecordList } from "./api";
import { getTimes } from "@/utils";
import { vaildTeachingUrl } from "@/utils/validate";
const initSearch = {
  search: null,
  state: null,
  createTimer: [],
  payState: null,
  createdName: null,
};
export default {
  components: { pagination, QrCode, protocolModel },
  data() {
    return {
      tableList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      searchForm: { ...initSearch },
      qrcodeStatus: false,
      codeUrl: null,
      protocolVisible: false,
      protocolVersions: [],
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    async getList() {
      try {
        let { createTimer, ...reset } = this.searchForm;
        const res = await tenantInfoQueryPage({
          ...reset,
          ...getTimes(createTimer, ["startDate", "endDate"], "YYYY-MM-DD"),
          page: this.pageInfo.page,
          rows: this.pageInfo.limit,
        });
        this.pageInfo.total = res.data.total;
        this.tableList = res.data.rows;
      } catch (e) {}
    },
    search() {
      this.pageInfo.page = 1;
      this.$refs.searchForm.save(this.searchForm);
      this.$refs.searchForm.save(this.pageInfo, "page");
      this.getList();
    },
    reset() {
      this.searchForm = { ...initSearch };
      this.search();
    },
    async onDownloadProtocol(item) {
      try {
        const res = await tenantContractRecordList({ tenantId: item.id })
        console.log(res)
        this.protocolVersions = res.data?.rows || [];
        this.protocolVisible = true;
      } catch(e) {
        //
        console.log(e)
      }
      // window.location.href = item.url;
    },
    onQrCode(row) {
      // 生成报名二维码
      this.qrcodeStatus = true;
      this.codeUrl = vaildTeachingUrl() + "/#/tenantPay/" + row.id;
    },
    changeOrgan(row) {
      const stateStr = row.state == 1 ? '停用' : '启用'
      const state = row.state == 1 ? 2 : 1
      this.$confirm(`是否${stateStr}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then( async() => {
        try{
         await tenantInfoOpsState({ id: row.id, state})
         this.$message.success(stateStr + '成功')
         this.getList()
        }catch{}
      });
    },
    openService(type, row) {
      let tagTitle = '创建'
      if(type == 'update') {
        tagTitle ='修改'
      } else if(type == 'look') {
        tagTitle = '查看'
      }

      this.$router.push({
        path: '/platformManager/organOperation',
        query: {
          type: type,
          id: row?.id || null
        }
      }, (route) => {
        route.meta.title = tagTitle + '机构'
      })
    },
    // async delService(row) {
    //   this.$confirm("是否删除?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   }).then( async() => {
    //     try{
    //      await platformServeDelete({ id:row.id})
    //      this.$message.success('删除成功')
    //      this.getList()
    //     }catch{}
    //   });
    // },
  },
};
</script>
<style lang="scss" scoped>
.courseMask .el-dialog__body {
  padding-bottom: 0;
}
</style>
