<template>
  <div class="content-main">
    <el-form :inline="true" :model="searchForm" class="search-bm-boder">
      <el-row>
        <el-form-item label="成交单位:">
          <el-input
            clearable
            v-model="searchForm.cjdwmc"
            style="width: 170px"
            placeholder="请输入成交单位"
          ></el-input>
        </el-form-item>
        <el-form-item label="合同编号:">
          <el-input
            clearable
            v-model="searchForm.hth"
            style="width: 170px"
            placeholder="请输入合同编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态:">
          <el-select
            v-model="searchForm.ztbm"
            style="width: 170px"
            clearable
            placeholder="请选择状态"
          >
            <el-option
              v-for="(item, index) in status"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></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="doSearch"
              size="small"
              class="iconfont iconchaxun"
              >查询</el-button
            >
            <el-button
              type="primary"
              @click="
                searchForm = {};
                cjrq = null;
                doSearch();
              "
              size="small"
              class="iconfont iconzhongzhi"
              >重置</el-button
            >
          </div>
        </el-form-item>
      </el-row>
      <el-row v-if="searchShowMoreBool">
        <el-form-item label="成交日期:">
          <el-date-picker
            style="width: 250px"
            v-model="cjrq"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            range-separator="至"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="品种:">
          <el-select
            v-model="searchForm.lspzbm"
            style="width: 170px"
            clearable
            placeholder="请选择品种"
          >
            <el-option
              v-for="(item, index) in types"
              :key="index"
              :label="item.dictName"
              :value="item.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价:">
          <el-input
            clearable
            style="width: 100px"
            v-model="searchForm.cjdjStart"
            placeholder="请输入"
          ></el-input
          >--
          <el-input
            clearable
            placeholder="请输入"
            style="width: 100px"
            v-model="searchForm.cjdjEnd"
          ></el-input>
        </el-form-item>
        <el-form-item label="粮食性质:">
          <el-select
            v-model="searchForm.lsxzbm"
            style="width: 170px"
            clearable
            placeholder="请选择粮食性质"
          >
            <el-option
              v-for="item in lsxzs"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-row>
    </el-form>
    <el-row class="addBtnBg" type="flex" justify="start">
      <el-button
        type="primary"
        style="margin-top: 10px"
        class="iconfont iconxinzeng"
        size="small"
        @click="$router.push({ path: 'detail', query: { state: 0 } })"
        >新增</el-button
      >
      <!-- <el-button
        type="primary"
        style="margin-top:10px;margin-right:10px"
        class="iconfont iconxiazai"
        size="small"
      >
        <a :href="downloadpath" style="color:white">下载模板</a>
      </el-button>-->
      <el-upload
        :action="uploadpath"
        :with-credentials="true"
        :headers="myHeader"
        :on-success="handleUploadSuccess"
        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"
        style="margin-top:10px;margin-left:-7px"
        class="iconfont iconzhuangtaixiugai"
        :disabled="!hasSelect"
        size="small"
        @click="handleDialog"
      >状态维护</el-button>
      <el-button
        type="primary"
        style="margin-top:10px"
        class="iconfont iconweiguizhuangtaiqingchu"
        :disabled="!hasSelect"
        size="small"
        @click="handleClear"
      >违规状态清除</el-button>-->
      <el-button
        type="primary"
        style="margin-top: 10px"
        class="iconfont iconxiazaimoban"
        size="small"
        @click="handleDownload"
        >模板下载</el-button
      >
    </el-row>
    <el-row>
      <el-table
        :data="tableData"
        stripe
        v-loading="listLoading"
        border
        style="width: 100%"
      >
        <!-- @selection-change="handleSelectionChange" -->
        <!-- <el-table-column type="selection" align="center" fixed="left"></el-table-column> -->
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="70"
        ></el-table-column>
        <el-table-column
          align="center"
          label="合同号"
          prop="hth"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="卖方承储库"
          prop="mfcckmc"
          show-overflow-tooltip
        ></el-table-column>
        <!-- <el-table-column align="center" label="仓号" prop="chmc" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="生产年份" prop="scnf" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="收购等级" prop="sgdjmc" show-overflow-tooltip></el-table-column>
        <el-table-column
          align="center"
          label="总成交数量"
          width="100"
          prop="zcjsl"
          show-overflow-tooltip
        ></el-table-column>-->
        <el-table-column
          align="center"
          label="粮食性质"
          prop="lsxzmc"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div>{{ lsxzObj[scope.row.lsxzbm] }}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="粮食品种"
          prop="lspzmc"
          show-overflow-tooltip
        ></el-table-column>
        <!-- <el-table-column align="center" label="起拍价格" prop="qpjg" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="成交单价" prop="cjdj" show-overflow-tooltip></el-table-column>-->
        <el-table-column
          align="center"
          label="成交金额"
          prop="cjje"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="成交单价"
          prop="cjdj"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="成交日期"
          min-width="100"
          prop="cjrq"
          show-overflow-tooltip
        ></el-table-column>
        <!-- <el-table-column
          align="center"
          label="出库截止日期"
          min-width="100"
          prop="ckjzrq"
          show-overflow-tooltip
        ></el-table-column>-->
        <el-table-column
          align="center"
          label="成交单位"
          prop="cjdwmc"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="来源"
          prop="sjlx"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div>{{ ["系统合同", "新增"][scope.row.sjlx] }}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="状态"
          prop="ztmc"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="横向得分"
          prop="hxdf"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="140">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                @click="
                  $router.push({
                    path: 'detail',
                    query: { cjbm: scope.row.cjbm, state: 2 },
                  })
                "
                class="operate_show_btn iconfont iconchakan2"
                size="small"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="light"
              content="编辑"
              placement="top"
              v-if="buttonNameList.indexOf('编辑') > -1"
            >
              <el-button
                type="primary"
                @click="
                  $router.push({
                    path: 'detail',
                    query: { cjbm: scope.row.cjbm, state: 1 },
                  })
                "
                class="operate_edit_btn iconfont iconxiugai"
                size="small"
                v-if="scope.row.ztmc != '违规'"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="light"
              content="违规清除"
              placement="top"
              v-if="buttonNameList.indexOf('违规清除') > -1"
            >
              <el-button
                type="primary"
                @click="handleClear(scope.row)"
                class="operate_delete_btn iconfont iconweiguizhuangtaiqingchu"
                size="small"
                v-if="scope.row.ztmc == '违规'"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="light"
              content="删除"
              placement="top"
              v-if="buttonNameList.indexOf('删除') > -1"
            >
              <el-button
                type="primary"
                @click="handleDel(scope.row)"
                class="operate_delete_btn iconfont iconshanchu1"
                size="small"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>单位：[ 数量: 吨；单价：元/吨；金额：元；]</el-row>
    <el-row>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pageForm.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageForm.total"
      ></el-pagination>
    </el-row>
    <el-dialog :visible.sync="dialogVisible" title="合同履约状态维护">
      <el-table :data="selectData" border stripe style="width: 100%">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="70"
        ></el-table-column>
        <el-table-column
          label="合同号"
          prop="hth"
          align="center"
        ></el-table-column>
        <el-table-column label="状态" prop="index" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.ztmc"
              :disabled="scope.row.frozenZt"
              style="width: 170px"
              clearable
              placeholder="请选择状态"
              @change="handleSum(scope.row, scope.$index)"
            >
              <el-option
                v-for="item in status"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="横向得分" prop="hxdf" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.ztmc != '违规' && scope.row.ztmc != '违约'">{{
              scope.row.hxdf
            }}</span>
            <span v-if="scope.row.ztmc == '违规' || scope.row.ztmc == '违约'">{{
              scope.row.ztmc
            }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="text-align: center; margin-top: 20px">
        <el-button
          class="iconfont iconbaocun"
          type="primary"
          @click="handleSave"
          >保存</el-button
        >
        <el-button
          class="iconfont iconfanhui"
          type="primary"
          @click="dialogVisible = false"
          >返回</el-button
        >
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  list,
  // varietys,
  lsxz,
  del,
  getconfig,
  updatestate,
} from "@/api/transaction/creditAssess/transactionDataMaintain/index";
import { transaction } from "@/api/index";
import { varietys } from "@/api/dict";
import statusList from "./status.js";
import { getToken } from "@/utils/auth";
import { authorityControl } from "@/api/menuList";
var selectDataBak = [];
export default {
  data() {
    return {
      downloadpath: `${transaction}/turnoverdata/downloadTemplate`,
      uploadpath: `${transaction}/turnoverdata/impData`,
      hasSelect: false,
      searchShowMoreBool: false,
      searchForm: {
        cjrq: null,
      },
      cjrq: null, // searchForm里的查询字段 成交日期
      //       :
      // YGQ("91000079","已过期"),
      // YLY("91000080","已履约"),
      // BFLY("91000081", "部分履约"),
      // WY("91000082","违约"),
      // WG("91000083","违规"),
      // YZZ("91000084", "已终止");
      // :
      // YCC("91000085", "违规已清除")
      status: statusList,
      // [
      //   {
      //     name: "履约",
      //     code: "91000080"
      //   },
      //   {
      //     name: "部分履约",
      //     code: "91000081"
      //   },
      //   {
      //     name: "违约",
      //     code: "91000082"
      //   },
      //   {
      //     name: "违规",
      //     code: "91000083"
      //   },
      //   {
      //     name: "终止",
      //     code: "91000084"
      //   },
      //   {
      //     name: "违规清除",
      //     code: "91000085"
      //   }
      // ], // 状态
      types: [], // 品种列表
      lsxzs: [], // 粮食性质列表
      lsxzObj: {},
      listLoading: false,
      tableData: [],
      pageForm: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      dialogVisible: false,
      selectData: [],
      config: {},
      buttonNameList: [],
    };
  },
  created() {
    this.varietys();
    this.lsxz();
    this.getresourceCode();
    this.getconfig();
  },
  computed: {
    myHeader() {
      return {
        token: getToken(),
      };
    },
  },
  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");
      });
    },
    handleDownload() {
      window.open(`${transaction}/turnoverdata/downloadTemplate`);
    },
    handleUploadSuccess(res) {
      if (res.infoCode === 200) {
        this.$message.success(res.msg);
        this.getList();
        return;
      }
      this.$message.error(res.msg);
    },
    handleClear(row) {
      let data = { cjbm: row.cjbm, ztbm: "91000085", ztmc: "违规清除" };
      this.updatestate(data);
    },
    handleSave() {
      let list = this.selectData.map((item) => ({
        cjbm: item.cjbm,
        ztbm: item.ztbm,
        ztmc: item.ztmc,
      }));
      let data = {
        dataList: list,
      };
      this.updatestate(data);
    },
    updatestate(data) {
      updatestate(data).then((res) => {
        if (res.infoCode == 200) {
          this.$message.success(res.msg);
          this.dialogVisible = false;
          this.getList();
          return;
        }
        this.$message.error(res.msg);
      });
    },
    handleSum(row, index) {
      let { ztmc, cjje } = row;
      if (ztmc && cjje) {
        if (ztmc == "违规") {
          this.$confirm("违规的客户，将影响下次交易的报名,是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              selectDataBak = JSON.parse(JSON.stringify(this.selectData));
              let { a, b, c, formula1, formula2 } = this.config;
              let 交易额 = cjje;
              var sum = "";
              if (ztmc == "履约") sum = eval(formula1).toFixed(2);
              if (ztmc == "部分履约") sum = eval(formula2).toFixed(2);
              if (ztmc == "违约") sum = "0";
              if (ztmc == "违规") sum = "0";
              if (ztmc == "终止") sum = "-0.5";
              row.hxdf = sum;
            })
            .catch(() => {
              row.ztmc = selectDataBak[index]["ztmc"];
            });
        }
      }
    },
    getconfig() {
      getconfig(1045).then((res) => {
        if (res.infoCode == 200) {
          if (res.data.length) {
            this.config = JSON.parse(res.data[0].configLastValue);
          }
        }
      });
    },
    handleSelectionChange(val) {
      this.hasSelect = !!val.length;
      this.selectData = val;
      selectDataBak = JSON.parse(JSON.stringify(this.selectData));
    },
    handleDialog() {
      this.selectData.forEach((item) => {
        item.frozenZt = item.ztmc == "违规";
      });
      this.dialogVisible = true;
    },
    async handleDel(row) {
      await this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      del({
        cjbm: row.cjbm,
      }).then((res) => {
        if (res.infoCode == 200) {
          this.$message.success(res.msg);
          this.getList();
        }
      });
    },
    handleAdd() {},
    doSearch() {
      this.pageForm.pageNum = 1;
      this.getList();
    },
    lsxz() {
      lsxz().then((res) => {
        if (res.infoCode === 200) {
          this.lsxzs = res.data;
          this.lsxzs.forEach((d) => {
            this.lsxzObj[d.dictCode] = d.dictName;
          });
        }
        // dictCode,dictName
      });
    },
    // 品种列表
    varietys() {
      varietys().then((res) => {
        if (res.infoCode === 200) {
          this.types = res.data;
        }
        // dictCode,dictName
      });
    },
    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"));
          this.cjrq = this.searchForm.cjrq;
        } else {
          //第一次进去此菜单时，保存上方默认的data
          sessionStorage.setItem("searchData", JSON.stringify(this.searchForm));
          sessionStorage.setItem("pageData", JSON.stringify(this.pageForm));
        }
      }
      this.listLoading = true;
      let pageNum = this.pageForm.pageNum;
      let pageSize = this.pageForm.pageSize;
      let cjrq = this.cjrq;
      let cjrqStart = null,
        cjrqEnd = null;
      if (cjrq && cjrq.length) {
        cjrqStart = cjrq[0];
        cjrqEnd = cjrq[1];
      }
      list({
        ...this.searchForm,
        cjrqStart,
        cjrqEnd,
        operaterType: 2,
        pageNum,
        pageSize,
      })
        .then((res) => {
          this.listLoading = false;
          if (res.infoCode === 200) {
            this.tableData = res.data.items;
            this.pageForm.total = res.data.total;
            return;
          }
          this.tableData = [];
          this.pageForm.total = 0;
        })
        .catch((err) => {
          this.listLoading = false;
          this.tableData = [];
          this.pageForm.total = 0;
        });
    },
    handleSizeChange(val) {
      this.pageForm.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageForm.pageNum = val;
      this.getList();
    },
  },
};
</script>
