<template>
  <div class="content-main">
    <el-form :inline="true" :model="searchForm" class="search-bm-boder">
      <el-row>
        <el-form-item label="委托编号:">
          <el-input
            v-model="searchForm.wtbh"
            clearable
            style="width: 170px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="场次:">
          <el-input
            v-model="searchForm.apcc"
            clearable
            style="width: 170px"
            placeholder="请输入场次"
          ></el-input>
        </el-form-item>
        <el-form-item label="委托单位:">
          <el-input
            v-model="searchForm.wtfmc"
            clearable
            style="width: 200px"
            placeholder="请输入委托单位"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <div class="search-button">
            <span class="search-line"></span>
            <div
              class="search-select"
              @click="searchShowMoreBool = !searchShowMoreBool"
            >
              更多条件
              <i class="el-icon-arrow-up" v-show="searchShowMoreBool"></i>
              <i class="el-icon-arrow-down" v-show="!searchShowMoreBool"></i>
            </div>
            <el-button
              type="primary"
              @click="searchInfo"
              size="small"
              class="iconfont iconchaxun"
              >查询</el-button
            >
            <el-button
              type="primary"
              @click="chongzhi"
              size="small"
              class="iconfont iconzhongzhi"
              >重置</el-button
            >
          </div>
        </el-form-item>
      </el-row>
      <el-row v-show="searchShowMoreBool">
        <el-form-item label="交易方向:">
          <el-select
            clearable
            v-model="searchForm.jyfx"
            placeholder="请选择交易方向"
          >
            <el-option
              v-for="(item, index) in statusList"
              :key="index"
              :label="item.dictName"
              :value="item.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易方式:">
          <el-select
            clearable
            v-model="searchForm.jyfs"
            style="width: 150px"
            placeholder="请选择交易方式"
          >
            <el-option
              v-for="(item, index) in jyfsList"
              :key="index"
              :label="item.dictName"
              :value="item.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易日期" prop="jyrq">
          <el-date-picker
            v-model="searchForm.jyrq"
            type="date"
            style="width: 150px"
            value-format="yyyy-MM-dd"
            class="input-w"
            placeholder="交易日期"
          ></el-date-picker>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row class="addBtnBg">
      <el-button
        type="primary"
        class="iconfont iconxinzeng"
        size="small"
        @click="handleAdd"
        >新增</el-button
      >
    </el-row>
    <el-table :data="tableData" border stripe tooltip-effect="dark">
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="60"
      ></el-table-column>
      <el-table-column
        prop="wtbh"
        label="委托编号"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="apcc"
        label="场次"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="wtfmc"
        label="委托单位"
        align="center"
        width="200"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="jyfx"
        label="交易方向"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <!-- <span v-if="scope.row.jyfx == '0'">不限</span> -->
          <span v-if="scope.row.jyfx == 0">采购</span>
          <span v-if="scope.row.jyfx == 1">销售</span>
          <span v-if="scope.row.jyfx == '0,1'">采购、销售</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="jyfs"
        label="交易方式"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <!-- <span v-if="scope.row.jyfx == '0'">不限</span> -->
          <span v-if="scope.row.jyfs == 0">竞价</span>
          <span v-if="scope.row.jyfs == 1">挂牌</span>
          <span v-if="scope.row.jyfs == 2">购销双向</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="pz"
        label="品种"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="jyrq"
        label="交易日期"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="jysj"
        label="交易时间"
        align="center"
        show-overflow-tooltip
      ></el-table-column>

      <el-table-column align="center" label="操作" width="180px">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="light"
            content="查看"
            placement="top"
          >
            <el-button
              type="primary"
              size="small"
              @click="showInfo(scope.row, 1)"
              class="operate_show_btn iconfont iconchakan2"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="light"
            content="编辑"
            placement="top"
            v-if="buttonNameList.indexOf('编辑') > -1"
          >
            <el-button
              v-if="scope.row.cczt != '已发布'"
              type="primary"
              size="small"
              @click="updateInfo(scope.row, 2)"
              class="operate_edit_btn iconfont iconxiugai"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect=""
            content=""
            placement=""
          >
            <el-button
              type="primary"
              size="mini"
              @click="getCustomInfo(scope.row)"
              :class="{iconfont:true, isBack:true, isTrue:(scope.row.zt==true)}"
              id="khxx_icon"
              style=""
            >客户信息</el-button>
          </el-tooltip>
          <!-- <el-tooltip
            class="item"
            effect="light"
            content="删除"
            placement="top"
            v-if="buttonNameList.indexOf('删除') > -1"
          >
            <el-button
              type="primary"
              size="small"
              @click="deleteInfo(scope.row.ccbm)"
              class="operate_delete_btn iconfont iconshanchu"
              v-if="scope.row.cczt == '待发布'"
            ></el-button>
          </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>
    <el-row class="pagination-wrap">
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="pageForm.applyNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageForm.total"
      ></el-pagination>
    </el-row>
  <el-dialog title="报名客户" :visible.sync="dialogVisible" width="1200px" :close-on-click-modal="false">
    <el-row style="height:50px">
      <el-col :span="12">
        <span>场次信息：{{dialogData.apcc}}</span>
      </el-col>
      <el-col :span="12">
        <span>交易时间：{{dialogData.jyrq}}</span>
      </el-col>
    </el-row>
    <el-row style="height:50px">
      <el-upload
        :action="uploadpath"
        :headers="myHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :show-file-list="false"
        style="width: 115px; display: inline-block; margin-left: 10px"
      >
        <el-button
          type="primary"
          class="iconfont iconpiliangdaoru"
          size="small"
          style="margin-top: -2px"
          >导入</el-button
        >
      </el-upload>
      <!-- <el-button
        type="primary"
        @click="handleDownload"
        size="small"
        class="iconfont iconchaxun"
        >模板下载</el-button
      > -->
    </el-row>
    <el-table
      border
      stripe
      ref="multipleTable"
      :data="customList"
      style="width: 100%;margin:auto;"
      max-height="500"
    >
      <el-table-column align="center" type="index" width="100" label="序号">
      </el-table-column>
      <el-table-column
        align="center"
        prop="hydm"
        label="会员代码"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="khmc"
        width="230"
        label="会员名称"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="yyzzbh"
        label="营业执照编号"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="jyqbzj"
        label="交易前保证金"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="bmsj"
        label="报名时间"
      >
      </el-table-column>
      <!-- <el-table-column
        align="center"
        prop="zt"
        label="状态"
      >
      </el-table-column> -->
    </el-table>
    <!-- <span slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        class="iconfont iconqueren"
        @click="dialogVisible = false"
        >保 存</el-button
      >
      <el-button
        type="primary"
        class="iconfont iconquxiao"
        @click="dialogVisible = false"
        >取 消</el-button
      >
    </span> -->
  </el-dialog>
  </div>
</template>

<script>
import {
  getScalePlanUpdate,
  deleteListItem,
  selectOwnList,
  getScalePlanDetails,
  selectParentList,
  excalOut,
  varietys,
} from "@/api/transaction/trading/transactionSignupFood/index";
import {
  selectList,
  delTrademark,
  customInfo,
} from "@/api/transaction/trading/fieldInfo/index";
import { authorityControl } from "@/api/menuList";
import { main } from "@/api/index";
import { getToken } from "@/utils/auth";
// 引入导出Excel表格依赖
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    return {
      variety: [],
      excalFalse: false,
      tableMrtabl: [],
      searchShowMoreBool: false,
      statusList: [
        {
          dictCode: "0",
          dictName: "采购",
        },
        {
          dictCode: "1",
          dictName: "销售",
        },
        /* {
          dictCode: "3",
          dictName: "采购、销售",
        }, */
      ], //引用json状态
      jyfsList: [
        {
          dictCode: "0",
          dictName: "竞价",
        },
        {
          dictCode: "1",
          dictName: "挂牌",
        },
        {
          dictCode: "2",
          dictName: "购销双向",
        },
      ],
      ztOptions: [],
      tableData: [],
      listLoading: true,
      showType: false,
      searchForm: {
        wtbh: "",
        apcc: "",
        wtfmc: "",
        jyfx: "",
        jyfs: "",
        jyrq: "",
        cczt: "",
        jylx: null,
        pz: null,
        pageType: 1,
      },
      pageForm: {
        pageNum: 1,
        pageSize: 10,
        total: 1,
      },
      buttonNameList: [],
      dialogVisible:false,
      uploadpath: "",
      dialogData:{},
      customccId:"",
      customList:[],
    };
  },
  computed: {
    myHeaders() {
      return {
        token: getToken(),
      };
    },
  },
  created() {
    // this.getCcList()
    // this.selectList()
    this.getresourceCode();
    varietys().then((res) => {
      this.variety = res.data;
    });
  },
  methods: {
    getresourceCode() {
      let codeData = {
        resourceCode: sessionStorage.getItem("resourceCode"),
        userId: sessionStorage.getItem("userCode"),
      };
      authorityControl(codeData).then((res) => {
        this.buttonNameList = [];
        res.data.forEach((item) => {
          this.buttonNameList.push(item.resourceName);
        });
        this.getCcList("start");
      });
    },
    /* async selectList(type) {
      if (type != "start") {
        //非初始化调用：查询、分页
        sessionStorage.setItem("searchData", JSON.stringify(this.searchForm));
        sessionStorage.setItem("pageData", JSON.stringify(this.pageForm));
      } else {
        //初始化分两种情况，详情页等返回后的初始化，以及第一次进入此菜单的初始化
        if (JSON.parse(sessionStorage.getItem("searchData"))) {
          //详情页返回后，将对应查询条件和分页的字段赋值，页面回显参数
          this.searchForm = JSON.parse(sessionStorage.getItem("searchData"));
          this.pageForm = JSON.parse(sessionStorage.getItem("pageData"));
        } else {
          //第一次进去此菜单时，保存上方默认的data
          sessionStorage.setItem("searchData", JSON.stringify(this.searchForm));
          sessionStorage.setItem("pageData", JSON.stringify(this.pageForm));
        }
      }
      let res = await selectList(
        JSON.parse(sessionStorage.getItem("pageData")),
        JSON.parse(sessionStorage.getItem("searchData"))
      );
      if (res.infoCode == 200) {
        this.tableData = res.data.items || [];
        this.tableData.forEach((d) => {
          d.jylxmc = ["采购", "销售"][d.jylx];
        });
        this.pageForm.total = res.data.total;
      }
    }, */
    getCcList(type) {
      // pageType 1 场次  2：底价
      let { pageNum, pageSize } = this.pageForm;
      for (var key in this.searchForm) {
        if (this.searchForm[key] === "") this.searchForm[key] = null;
        if (typeof this.searchForm[key] === "string")
          this.searchForm[key] = this.searchForm[key].trim();
      }
      if (type != "start") {
        //非初始化调用：查询、分页
        sessionStorage.setItem("searchData", JSON.stringify(this.searchForm));
        sessionStorage.setItem("pageData", JSON.stringify(this.pageForm));
      } else {
        //初始化分两种情况，详情页等返回后的初始化，以及第一次进入此菜单的初始化
        if (JSON.parse(sessionStorage.getItem("searchData"))) {
          //详情页返回后，将对应查询条件和分页的字段赋值，页面回显参数
          this.searchForm = JSON.parse(sessionStorage.getItem("searchData"));
          this.pageForm = JSON.parse(sessionStorage.getItem("pageData"));
        } else {
          //第一次进去此菜单时，保存上方默认的data
          sessionStorage.setItem("searchData", JSON.stringify(this.searchForm));
          sessionStorage.setItem("pageData", JSON.stringify(this.pageForm));
        }
      }
      let pageType = 1;
      let data = {
        ...JSON.parse(sessionStorage.getItem("searchData")),
        pageType,
      };
      selectList(JSON.parse(sessionStorage.getItem("pageData")), data)
        .then((res) => {
          console.log(res,'场次列表')
          if (res.infoCode == 200) {
            this.tableData = res.data.items || [];
            this.pageForm.total = res.data.total;
            this.tableData.forEach(item=>{
              customInfo(item.ccbm).then((res)=>{
                if (res.data.tyJyccKhxxList.length>0) {
                  item.zt = true
                }
              })
            })
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    handleAdd() {
      this.$router.push({
        path: "/transaction/fieldPlan/add",
        query: { state: 0 },
      });
    },
    chongzhi() {
      (this.searchForm = {
        wtbh: "",
        apcc: "",
        wtdw: "",
        jyfx: "",
        jyfs: "",
        jyrq: "",
        cczt: "",
        jylx: null,
        pz: null,
      }),
        this.getCcList();
    },
    submitUpload() {
      let list = document.getElementsByClassName(
        "el-upload-list__item is-ready"
      );
      if (list.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择需要导入的模板！",
        });
        return;
      }
      this.$refs.upload.submit();
    },
    uploadSectionFile(param) {
      var fileObj = param.file;
      // FormData 对象
      var form = new FormData();
      // 文件对象
      form.append("file", fileObj);
      form.append("userId", this.userId);
      form.append("userName", this.userName);
      this.GLOBAL.POST("/hqx/knowledge/importKnowledge", form).then((res) => {
        if (res.data.success == true) {
          this.$message({
            type: "success",
            message: res.data.msg,
          });
          this.fileList = [];
        } else {
          this.$message({
            type: "success",
            message: res.data.msg,
          });
          this.fileList = [];
        }
      });
    },

    //点击搜索时
    searchInfo() {
      this.pageForm.pageNum = 1;
      this.getCcList();
    },
    //点击查看 跳到detail页面
    showInfo(row, type) {
      console.log(type, "type");
      this.$router.push({
        path: "/transaction/fieldPlan/detail",
        query: {
          ccbm: row.ccbm,
          data: row,
          type: "show",
        },
      });
    },

    //去detail页面 进行数据添加
    updateInfo(row, type) {
      // console.log(row,'编辑行信息')
      this.$router.push({
        path: "/transaction/fieldPlan/update",
        query: {
          ccbm: row.ccbm,
          data: row,
          type: "update",
        },
      });
    },
    //点击删除按钮
    deleteInfo(id) {
      this.$confirm("此操作将删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // console.log("999", id);
          delTrademark(id)
            .then((res) => {
              // console.log("res", res);
              if (res.infoCode == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.getCcList();
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败!",
                });
              }
            })
            .catch((err) => {
              console.log("err", err);
            });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //分页
    handleSizeChange(val) {
      this.pageForm.pageSize = val;
      this.getCcList();
    },
    handleCurrentChange(val) {
      this.pageForm.pageNum = val;
      this.getCcList();
    },

    biaodi() {
      this.$router.push({
        name: "transactionSignupFoodDetail",
        query: {
          type: "signa",
        },
      });
    },
    //定义导出Excel表格事件
    exportExcel() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "sheetjs.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    // 客户信息
    getCustomInfo(row){
      this.dialogVisible = true
      this.dialogData = {
        apcc: row.apcc,
        jyrq: row.jyrq.substr(0,4)+"年"+row.jyrq.substr(5,2)+ "月" +row.jyrq.substr(8,2)+ "日",
      }
      this.uploadpath = `${main}/jyccKhxx/importExcel?wtbh=${row.wtbm}`
      this.customccId = row.ccbm
      this.getCustom(this.customccId )
    },
    getCustom(ccId){
      customInfo(ccId).then(res=>{
        this.customList = res.data.tyJyccKhxxList
      })
    },
    //导入
    handleUploadSuccess(res, file) {
      console.log(file);
      if (res.infoCode == 200) {
        this.$message.success("导入成功!");
        this.getCustom(this.customccId)
      } else {
        this.$message.error("导入失败!" + res.msg);
      }
    },
    handleUploadError(res) {
      this.$message.error("导入失败!");
    },
  },
};
</script>

<style lang="scss" scoped>
.pagination-wrap {
  text-align: right;
  margin-top: 10px;
}

/* .input-w-220 {
  width: 220px;
} */
.iconfont {
  font-size: 13px;
}

/* .iconfont {
  color: white;
} */
#out-table {
  border: 2px solid black;
}
#khxx_icon{
  padding:0 5px !important;
  height:26px !important;
}
.isBack{
  background:#169bd5 !important;
}
.isTrue {
  background: rgba(231, 116, 9, 0.578) !important;
}
</style>
