<template>
  <div class="content-main">
    <el-form :inline="true" :model="searchForm" class="search-bm-boder">
      <el-row>
        <el-form-item>
          <label slot="label">合&nbsp;&nbsp;同&nbsp;&nbsp;号:</label>
          <el-input v-model="searchForm.htbh" 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.cmmc" clearable style="width: 170px" placeholder="请输入委托单位"></el-input>
        </el-form-item>
        <!-- <el-form-item label="收购等级:">
					<el-select clearable v-model="searchForm.ztmc" multiple style="width:170px" >
						<el-option
							v-for="item in status"
							:key="item.dictCode"
							:label="item.dictName"
							:value="item.dictName"
						></el-option>
					</el-select>
        </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>
            <!-- <el-button type="primary" @click="biaodi" size="small" class="iconfont iconzhongzhi"> 分解标的</el-button> -->
          </div>
        </el-form-item>
      </el-row>
      <el-row v-show="searchShowMoreBool">
        <el-form-item label="成交单位:">
          <el-input v-model="searchForm.sgmc" clearable style="width: 170px" placeholder="请输入成交单位"></el-input>
        </el-form-item>
        <el-form-item label="品种:">
          <el-cascader
            style="width:170px;"
            :options="pzOptions"
            :props="pzProps"
            :show-all-levels="false"
            v-model="searchForm.pzmc"
            placeholder="请选择"
            clearable
          ></el-cascader>
        </el-form-item>
        <!-- <el-form-item label="成交时间:" prop="cjrq">
          <el-date-picker
            class="dateInputCompatible"
            v-model="searchForm.cjrq"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item> -->
      </el-row>
    </el-form>

    <el-row v-if="buttonNameList.indexOf('新增') > -1" class="addBtnBg">
      <el-button type="primary" class="iconfont iconxinzeng" size="small" @click="handleAdd">新增</el-button>
      <!-- <el-upload style="display: inline-block" :action="uploadUrl" :headers="myHeaders" :show-file-list="false" :on-success="handleUploadSuccess" :on-error="handleUploadError">
        <el-button type="primary" class="iconfont icondaoru1" size="small">导入</el-button>
      </el-upload>
      <el-button type="primary" class="iconfont iconxiazaimoban" size="small" @click="handleDownloadTemplate">下载模板</el-button> -->
    </el-row>

    <el-table :data="tableData" border stripe tooltip-effect="dark">
      <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
      <el-table-column prop="htbh" label="合同号" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="apcc" label="场次" align="center" width="70"></el-table-column>
      <el-table-column prop="bdh" label="标的" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="jyfxmc" label="交易方向" width="100">
          <template slot-scope="scope">
            {{ scope.row.jyfsmc == '购销双向' ? "采购、销售" : scope.row.jyfxmc }}
          </template>
        </el-table-column>
      <el-table-column align="center" prop="jyfsmc" label="交易方式" width="80"></el-table-column>
      <el-table-column label="委托单位" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <template v-if="scope.row.jylx == 0">{{scope.row.sgmc}}</template>
          <template v-else>{{scope.row.cmmc}}</template>
        </template>
      </el-table-column>
      <el-table-column label="成交单位" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <template v-if="scope.row.jylx == 0">{{scope.row.cmmc}}</template>
          <template v-else>{{scope.row.sgmc}}</template>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="jylxmc" label="交易性质" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ ["采购", "销售"][scope.row.jylx] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="cmmc" label="卖方" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sgmc" label="买方" align="center" show-overflow-tooltip></el-table-column> -->
      <el-table-column prop="pzmc" label="品种" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="nzcjl" label="成交数量(吨)" align="center" width="100">
        <template slot-scope="scope">
          {{
            String(scope.row.nzcjl).indexOf(".") > -1
              ? Number(scope.row.nzcjl).toFixed(3)
              : scope.row.nzcjl
          }}
        </template>
      </el-table-column>
      <el-table-column prop="je" label="成交额(元)" align="center" width="100">
        <template slot-scope="scope">
          {{
            String(scope.row.je).indexOf(".") > -1
              ? Number(scope.row.je).toFixed(2)
              : scope.row.je
          }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="cjrq" label="成交日期" align="center" show-overflow-tooltip></el-table-column> -->
      <el-table-column align="center" label="操作" width="90px">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="light" content="查看" placement="top">
            <el-button type="primary" size="small" @click="showInfo(scope.row)" class="operate_show_btn iconfont iconchakan2"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="light" content="编辑" placement="top" v-if="buttonNameList.indexOf('编辑') > -1 && scope.row.isChange !== '0'">
            <el-button v-show="scope.row.dataVer != 0" type="primary" size="small" @click="updateInfo(scope.row)" class="operate_edit_btn iconfont iconxiugai"></el-button>
          </el-tooltip>
          <!-- 
					<el-tooltip class="item" effect="light" content="删除" placement="top">
						<el-button
							type="primary"
							size="small"
							@click="deleteInfo(scope.row)"
							class="operate_delete_btn iconfont iconshanchu"
						></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="showLog(scope.row)" class="operate_show_btn iconfont iconrizhi"></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>
  </div>
</template>

<script>
import {
  getScalePlanUpdate,
  deleteListItem,
  selectOwnList,
  getScalePlanDetails,
  selectParentList,
  excalOut,
  varietys,
} from "@/api/transaction/trading/transactionSignupFood/index";
import { selectContractPage } from "@/api/transaction/registrationFee/contractInfo/index.js";
import { getPzOptions } from "@/api/transaction/tradeEntrust/outInDepotEntrust/index.js";
import { contractPage } from "@/api/base";
import { authorityControl } from "@/api/menuList";
import { transaction } from "@/api/index";
// 引入导出Excel表格依赖
import FileSaver from "file-saver";
import XLSX from "xlsx";

var token = sessionStorage.getItem("TOKENL");
export default {
  data() {
    return {
      pzProps: {
        label: "dictName",
        value: "dictName",
        children: "subDataDictionarys",
        emitPath: false,
      },
      pzOptions: [],
      uploadUrl: `${transaction}/trademark/impContract`,
      myHeaders: { token: token },
      variety: [],
      excalFalse: false,
      tableMrtabl: [],
      searchShowMoreBool: false,
      statusList: [
        { dictCode: null, dictName: "不限" },
        {
          dictCode: "0",
          dictName: "竞购",
        },
        {
          dictCode: "1",
          dictName: "竞销",
        },
      ], //引用json状态
      status: [
        { dictCode: "1", dictName: "一等" },
        { dictCode: "2", dictName: "二等" },
        { dictCode: "3", dictName: "三等" },
        { dictCode: "4", dictName: "四等" },
        { dictCode: "5", dictName: "五等" },
      ],
      ztOptions: [],
      tableData: [],
      listLoading: true,
      showType: false,
      searchForm: {
        // cmmc: '',
        // ztmc: '',
        // ztbm: '',
        apcc: "",
        pzbm: null,
        htbh: "",
        pzmc: "",
        cjrq: "",
      },
      pageForm: {
        pageNum: 1,
        pageSize: 10,
        total: 1,
      },
      buttonNameList: [],
    };
  },
  beforeCreate() {
    getPzOptions(11).then(res => {
      this.pzOptions = res.data;
    });
  },
  created() {
    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.getList("start");
      });
    },
    async getList(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 data = {
        ...this.pageForm,
        apcc: this.searchForm.apcc,
        pzmc: this.searchForm.pzmc.toString(),
        htbh: this.searchForm.htbh,
        cmmc: this.searchForm.cmmc,
        sgmc: this.searchForm.sgmc,
        // startDate: this.searchForm.cjrq ? this.searchForm.cjrq[0] : "",
        // endDate: this.searchForm.cjrq ? this.searchForm.cjrq[1] : "",
      };
      if (sessionStorage.getItem("orgCode") != "LS001" && sessionStorage.getItem("orgCode") != "LS001020") {
        data.fsdw = sessionStorage.getItem("orgCode")
      }
      let res = await selectContractPage(data);
      if (res.infoCode == 200) {
        this.tableData = res.data.items;
        this.pageForm.total = res.data.total;
      }
    },
    showLog() {
      this.$router.push({ name: "contractInfoLog", query: {} });
    },
    handleAdd() {
      this.$router.push({ name: "contractInfoDetail", query: { type: "add" } });
    },
    handleDownloadTemplate() {
      let a = document.createElement("a");
      a.download = "合同信息模板";
      a.href = transaction + "/trademark/downloadContractTemplate";
      a.click();
    },
    chongzhi() {
      this.searchForm = {
        xzbt: "",
        fbzt: "",
        bzsj: "",
        fbztmc: "",
        jylxbm: "",
        dwmc: "",
        htbh: "",
        pzmc: "",
      };
      this.getList();
    },
    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 = [];
        }
      });
    },
    //初始数据列表请求
    // getList() {
    // 	if (this.searchForm.ztmc == '待分解') {
    // 		this.searchForm.zt = '91000057'
    // 	}
    // 	if (this.searchForm.ztmc == '已分解') {
    // 		this.searchForm.zt = '91000058'
    // 	}
    // 	if (this.searchForm.jylxmc == '竞购') {
    // 		this.searchForm.jylxbm == 0
    // 	}
    // 	if (this.searchForm.jylxmc == '竞销') {
    // 		this.searchForm.jylxbm == 1
    // 	}
    // 	if (this.searchForm.jylxmc == '不限') {
    // 		this.searchForm.jylxbm == null
    // 	}
    // 	let data = {
    // 		// cmmc: this.searchForm.cmmc,
    // 		// zt: this.searchForm.zt,
    // 		// pzbm: this.searchForm.pzbm,
    // 		// jylxbm: this.searchForm.jylxbm,
    // 		...this.searchForm,
    // 		pageNum: this.pageForm.pageNum,
    // 		pageSize: this.pageForm.pageSize,
    // 	}
    // 	selectOwnList(data).then(res => {
    // 		console.log(res, '列表页')
    // 		if (res.infoCode == 200) {
    // 			this.tableData = res.data.items
    // 			this.tableData.forEach(d => {
    // 				d.jylxmc = d.jylx == 1 ? '竞销' : '竞购'
    // 			})
    // 			this.pageForm.total = Number(res.data.total)
    // 		} else {
    // 			this.$message({
    // 				type: 'error',
    // 				message: '获取失败!',
    // 			})
    // 		}
    // 	})
    // },
    //点击搜索时
    searchInfo() {
      this.pageForm.pageNum = 1;
      this.getList();
    },
    //点击查看 跳到detail页面
    showInfo(row) {
      this.$router.push({
        name: "contractInfoDetail",
        query: {
          htbh: row.htbm,
          type: "show",
          dataVer: row.dataVer
        },
      });
    },

    //去detail页面 进行数据添加
    updateInfo(row) {
      this.$router.push({
        name: "contractInfoDetail",
        query: {
          htbh: row.htbm,
          type: "update",
        },
      });
    },
    //点击删除按钮
    deleteInfo(row) {
      this.$confirm("此操作将删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            xzbm: row.xzbm,
          };
          deleteListItem(data).then((res) => {
            if (res.infoCode == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: "删除失败!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //分页
    handleSizeChange(val) {
      this.pageForm.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageForm.pageNum = val;
      this.getList();
    },
    handleUploadSuccess(res, file) {
      if (res.infoCode == 200) {
        this.$message.success("上传成功!, 导入" + res.msg);
        this.getList();
      }
    },
    handleUploadError(res) {
      this.$message.error("上传失败!");
    },
    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;
    },
  },
};
</script>

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

.input-w-220 {
  width: 220px;
}

.iconfont {
  color: white;
}
#out-table {
  border: 2px solid black;
}
</style>
