<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      乐器置换
    </h2>
    <div class="m-core">
      <div class="btnList">
        <!--      v-permission="'export/practiceGroup'" -->
        <div
          class="newBand"
          @click="makeUrl('create')"
          style="max-width: 150px; margin-right: 10px"
          v-if="permission('replacementInstrumentCooperation/add')"
        >
          生成链接
        </div>
        <div class="newBand" @click="onExport" style="max-width: 150px" v-if="permission('replacementInstrumentActivity/export')">
          导出
        </div>
      </div>
      <save-form
        :inline="true"
        ref="searchForm"
        :model="searchForm"
        @submit="search"
        @reset="onReSet"
      >
        <el-form-item prop="search">
          <el-input
            v-model.trim="searchForm.search"
            clearable
            @keyup.enter.native="search"
            placeholder="学校名称或编号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="organId">
          <el-select
            v-model.trim="searchForm.organId"
            filterable
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="openPay">
          <el-select
            class="multiple"
            v-model.trim="searchForm.openPay"
            filterable
            clearable
            placeholder="是否开启缴费"
          >
            <el-option label="是" value="YES"></el-option>
            <el-option label="否" value="NO"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="primary">搜索</el-button>
          <el-button native-type="reset" type="danger">重置</el-button>
        </el-form-item>
      </save-form>
      <div class="tableWrap">
        <el-table
          style="width: 100%"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :data="tableList"
        >
          <el-table-column
            align="center"
            prop="id"
            label="编号"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="title"
            label="活动主题"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="organName"
            label="分部"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="cooperationOrganName"
            label="合作单位"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.cooperationOrganName }}
                <!-- (<copy-text> {{ scope.row.cooperationOrganId }} </copy-text>) -->
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="问卷名称">
            <template slot-scope="scope">
              <span v-if="scope.row.topicTitle">{{ scope.row.topicTitle }}</span>
              <el-tag style="margin: 8px 20px; font-size: 14px;" type="danger" v-else>无问卷</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column
            align="center"
            prop="showQuestion"
            label="是否参加问卷调查"
          >
            <template slot-scope="scope">
              {{ scope.row.showQuestion ? '是' : '否' }}
            </template>
          </el-table-column> -->
          <el-table-column
            align="center"
            prop="activeNum"
            label="调查人数"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="replaceNum"
            label="置换人数"
          ></el-table-column>
          <el-table-column align="center" prop="replaceScale" label="置换率">
            <template slot-scope="scope">
              <div>{{ scope.row.replaceScale }}%</div>
            </template>
          </el-table-column>
               <el-table-column align="center" prop="replaceScale" label="缴费率">
            <template slot-scope="scope">
              <div>{{ scope.row.payScale }}%</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="openPay" label="是否开启缴费">
            <template slot-scope="scope">
              <div>{{ scope.row.openPay ? "是" : "否" }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="250px" label="操作">
            <template slot-scope="scope">
              <div>
                <el-button type="text" @click="lookDetail(scope.row)" v-if="permission('replacementInstrumentActivity/queryPage')">问卷详情</el-button>
                <el-button type="text" @click="lookDetail(scope.row, 'answer')" v-if="permission('/reaplceMusicPlayer/answer')">问答详情</el-button>
                <el-button type="text" @click="makeUrl('update', scope.row)" v-if="permission('replacementInstrumentCooperation/update')">修改主题</el-button>
                <el-button
                  type="text"
                  @click="openPay(scope.row)"
                  v-if="
                    !scope.row.openPay &&
                    permission('replacementInstrumentCooperation/openPay')
                  "
                  >开启缴费</el-button>
                <el-dropdown>
                  <span class="el-dropdown-link" style="color: #14928A">
                    更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown" style="margin-left: 10px;">
                    <el-dropdown-item>
                      <el-button type="text" @click="onCreateQRCode(scope.row, '调查链接')" >调查链接</el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button type="text" @click="onCreateQRCode(scope.row, '统计链接')">统计链接</el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button type="text" @click="onCreateQRCode(scope.row, '缴费链接')">缴费链接</el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          sync
          :total.sync="rules.total"
          :page.sync="rules.page"
          :limit.sync="rules.limit"
          :page-sizes="rules.page_size"
          @pagination="getList"
        />
      </div>
    </div>
    <el-dialog
      :title="makeType == 'create' ? '生成链接' : '修改主题'"
      :visible.sync="makeUrlVisible"
      width="500px"
      v-if="makeUrlVisible"
    >
      <addUrl ref="addUrl" @close="close" :makeType="makeType" :makeDetail="makeDetail" @getList="getList" />
      <div slot="footer">
        <el-button @click="makeUrlVisible = false">取 消</el-button>
        <el-button type="primary" @click="addurl">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="详情"
      :visible.sync="detailVisible"
      width="1200px"
      @close="getClose"
      v-if="detailVisible"
    >
      <detail ref="detail" @close="close" :detail="activeRow" />
      <div slot="footer">
        <el-button type="primary" @click="getClose"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <qr-code v-model="qrcodeStatus" :title="qrcodeName" :codeUrl="codeUrl" />

    <!-- <el-dialog :title="qrcodeName" :visible.sync="qrcodeStatus" width="300px">
      <div class="left-code">
        <div id="qrcode" class="qrcode code" ref="qrCodeUrl"></div>
        <p class="code-url" v-if="codeUrl">
          <copy-text>
            {{ codeUrl }}
          </copy-text>
        </p>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { permission } from "@/utils/directivePage";
import { vaildStudentUrl, vaildTeachingUrl } from "@/utils/validate";
import pagination from "@/components/Pagination/index";
import addUrl from "./modals/addUrl";
import detail from "./modals/detail";
import { getReplacementList, openPayReplacement, updateReplacement } from "./api";
import { Export } from '@/utils/downLoadFile'
import cleanDeep from 'clean-deep'
import qs from 'qs';
import QrCode from "@/components/QrCode/index";
import { encode } from 'js-base64';
export default {
  components: { pagination, addUrl, detail, QrCode },
  data() {
    return {
      searchForm: {
        search: null,
        organId: "",
        openPay: "",
      },

      tableList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      makeUrlVisible: false,
      makeType: 'create',
      detailVisible: false,
      makeDetail: null,
      codeUrl: "",
      qrcodes: true,
      qrcodeStatus: false,
      qrcodeName: "调查链接",
      activeRow: null,
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // 获取分部

    this.init();
  },
  methods: {
    permission(str, parent) {
      return permission(str, parent);
    },
    init() {
      this.$store.dispatch("setBranchs");
      this.getList();
    },
    async getList() {
      try {
        const res = await getReplacementList({
          ...this.searchForm,
          page: this.rules.page,
          rows: this.rules.limit,
        });
        this.rules.total = res.data.total;
        this.tableList = res.data.rows;
      } catch (e) {
        console.log(e);
      }
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
      this.$refs.searchForm.resetFields();
      this.search();
    },
    makeUrl(type, row) {
      this.makeUrlVisible = true;
      this.makeType = type
      if(type == 'update') {
        this.makeDetail = row
      }
    },
    addurl() {
      this.$refs.addUrl.submit();
    },
    close() {
      this.makeUrlVisible = false;
      this.detailVisible = false;
    },
    getClose() {
      this.detailVisible = false
      this.getList()
    },
    async onExport() {
      const { search, ...rest } = this.searchForm;
      let obj = {
        ...rest,
        // activeType: 'REPLACEMENT',
        page: this.rules.page,
        rows: this.rules.limit,
        cooperationOrganIdOrName:search
      };
      await Export(
        this,
        {
          url: "/api-web/replacementInstrumentActivity/export",
          fileName: "乐器置换列表.xls",
          method: "post",
          params: qs.stringify(cleanDeep(obj)),
        },
        "您确定导出乐器置换列表"
      );
    },
    lookDetail(row, type) {
      if(type == 'answer') {
        this.$router.push({
          path: '/reaplceMusicPlayer/answer',
          query: {
            id: row.id,
            topicId: row.topicId
          }
        })
      } else {
        this.activeRow = row;
        this.detailVisible = true;
      }
    },
    onCreateQRCode(row, name) {
      // 生成链接
      this.qrcodeName = name;
      this.qrcodeStatus = true;

      let id = this.$route.query.id;
      if (this.qrcodes) {
        this.qrcodes = false;

        // setTimeout(() => {
        //   document.getElementById("qrcode").innerHTML = "";
        //   this.qrcode = new QRCode("qrcode", {
        //     width: 260,
        //     height: 260,
        //     colorDark: "#000000",
        //     colorLight: "#ffffff",
        //     correctLevel: QRCode.CorrectLevel.H,
        //   });
        let str;
        if (name == "调查链接") {
          let returnUrl = vaildStudentUrl() + `/#/questionnaire?` + encodeURIComponent(encode(`id=${row.id}`));
          // console.log(returnUrl)
          // let tempUrl =
          //   vaildStudentUrl() +
          //   `/#/transfer?returnUrl=${encodeURIComponent(returnUrl)}`;
          str = returnUrl;
        } else if (name == "统计链接") {
          str =
            vaildTeachingUrl() +
            `/#/questionStatistics?o=${row.organId}&c=${row.cooperationOrganId}&id=${row.id}`;
        } else if(name == '缴费链接') {
          str = vaildStudentUrl() + `/#/questionGoodsSale?` + encodeURIComponent(encode(`rid=${row.id}`));
        }
        // vaildTeachingUrl
        // this.qrcode.makeCode(
        //   str +
        //     `/#/questionnaireInfo?o=${row.organId}&c=${row.cooperationOrganId}`
        // );
        this.codeUrl = str;
        this.qrcodes = true;
        // }, 100);
      }
    },
    openPay(row) {
      this.$confirm("确定开启缴费?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await openPayReplacement({ id: row.id });
            this.$message.success("开启缴费成功");
            this.getList();
          } catch (e) {
            console.log(e);
          }
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang='scss' scoped>
.btnList {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
.code-url {
  margin-top: 10px;
}
</style>
