<template>
  <div class="detail-content">
    <div class="sub-title">场次基本情况</div>
    <el-form ref="dform" :model="dform" label-width="7em">
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="委托编号:"
            prop="wtbh"
            :rules="{
              required: saveClose,
              validator: checkinput,
              trigger: ['change', 'blur'],
              message: '请选择委托编号',
            }"
          >
            <el-select
              v-model="dform.wtbh"
              clearable
              class="w90"
              @change="handleWtChange"
              :disabled="isView"
            >
              <el-option
                v-for="(item, index) in wtOpts"
                :key="index"
                :label="item.wtbh"
                :value="item.wtbm"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="场次:"
            prop="apcc"
            :rules="[
              {
                validator: checkCC,
                required: saveClose,
                trigger: ['change', 'blur'],
                message: '请输入',
              },
            ]"
          >
            <el-input
              v-model="dform.apcc"
              clearable
              class="w90"
              :disabled="isView"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易性质:">
            <el-select v-model="dform.jylx" disabled class="w90">
              <el-option label="采购" :value="0"></el-option>
              <el-option label="销售" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="交易时间:"
            prop="jyrq"
            :rules="{
              required: saveClose,
              validator: checkinput,
              trigger: ['change', 'blur'],
              message: '请选择交易时间',
            }"
          >
            <el-date-picker
              type="date"
              v-model="dform.jyrq"
              clearable
              class="w90"
              :disabled="isView"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品       种:">
            <el-input v-model="dform.pz" disabled class="w90"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数       量:">
            <el-input v-model="dform.sl" disabled class="w90"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易类型:">
            <el-select v-model="dform.jyxz" :disabled="isView" class="w90">
              <el-option label="竞价" value="0"></el-option>
              <el-option label="定向" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="手续费类型:"
            prop="sxfType"
            :rules="{
              required: saveClose,
              validator: checkinput,
              trigger: ['change', 'blur'],
              message: '请选择手续费类型',
            }"
          >
            <el-select
              v-model="dform.sxfType"
              clearable
              class="w90"
              :disabled="isView"
            >
              <el-option
                v-for="(item, index) in ['双边', '委托方', '客户']"
                :key="index"
                :label="item"
                :value="String(index)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="手续费率:"
            prop="sxfl"
            :rules="{
              required: saveClose,
              validator: checkmoneyzxf,
              trigger: ['change', 'blur'],
            }"
          >
            <el-input
              v-model="dform.sxfl"
              @change="sxflChange"
              clearable
              class="w90"
              :disabled="isView"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手续费:" prop="sxf">
            <el-input
              v-model="dform.sxf"
              clearable
              class="w90"
              :disabled="isView"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="交易保证金:"
            prop="jybzj"
            :rules="{
              required: saveClose,
              validator: checkmoney,
              trigger: ['change', 'blur'],
            }"
          >
            <el-input
              :disabled="isView"
              clearable
              class="w90"
              v-model="dform.jybzj"
              v-bind:value="
                String(dform.jybzj).indexOf('.') > -1
                  ? Number(dform.jybzj).toFixed(2)
                  : dform.jybzj
              "
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="履约保证金:"
            prop="lybzj"
            :rules="{
              required: saveClose,
              validator: checkmoney,
              trigger: ['change', 'blur'],
            }"
          >
            <el-input
              :disabled="isView"
              clearable
              class="w90"
              v-model="dform.lybzj"
              v-bind:value="
                String(dform.lybzj).indexOf('.') > -1
                  ? Number(dform.lybzj).toFixed(2)
                  : dform.lybzj
              "
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="sub-title">标的详情</div>
    <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
        label="标的号"
        prop="bdh"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="承储单位"
        prop="ccdw"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="仓号"
        prop="cfbm"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="品种"
        prop="pz"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="数量"
        prop="sl"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="生产年度"
        prop="scnd"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" prop align="center">
        <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"
          >
            <el-button
              type="primary"
              size="small"
              @click="delInfo(scope.$index)"
              class="operate_delete_btn iconfont iconshanchu"
              v-if="!isView"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="btn-footer">
      <el-button
        type="primary"
        icon="iconfont iconbaocun"
        v-if="!isView"
        @click="handleSubmit('待发布')"
        >保存</el-button
      >
      <el-button
        type="primary"
        icon="iconfont iconfabu"
        v-if="!isView"
        @click="handleSubmit('已发布')"
        >发布</el-button
      >
      <el-button
        type="primary"
        icon="iconfont iconfanhui"
        @click="$router.push('index')"
        >返回</el-button
      >
    </el-row>
  </div>
</template>
<script>
import {
  selectwtList,
  selectEntryAndExitOrder,
  selectEntryAndExitOrderBySite,
  selectCode,
  insertCC,
  updateCC,
  selectCC,
  valiCode,
} from "@/api/transaction/trading/fieldInfo/index";
import { NumberToChinese, ChineseToNumber } from "@/utils/num2cn";
const log = console.log.bind(console);
export default {
  data() {
    return {
      dform: { apcc: "", sxf: "", sxfl: "", jybzj: "", lybzj: "" },
      tableData: [],
      isView: false,
      wtOpts: [],
      isAdd: false,
      msg: "",
      isUpdate: false,
      ccbm: null,
      saveClose: true,
    };
  },
  created() {
    let { state, ccbm, type } = this.$route.query;
    this.ccbm = ccbm;
    this.isAdd = state == 0;
    this.isView = type == "show";
    this.isUpdate = type = "update";
    if (this.isAdd) {
      this.selectCode();
    }
    this.selectwtList();
    if (!this.isAdd) {
      this.getDetail(ccbm);
    }
  },
  methods: {
    sxflChange(val) {
      if (val && this.dform.sl) {
        console.log(this.dform.sl, val);
        this.dform.sxf = val * Number(this.dform.sl);
        console.log(this.dform.sxf);
      }
    },
    async checkCC(rule, val, cb) {
      this.dform.apcc = val.trim();
      if (!val) {
        cb(new Error("请输入场次"));
      } else {
        cb();
      }
      // let reg = /第[一二三四五六七八九]?千?[零一二三四五六七八九]?百?[零一二三四五六七八九]?十?[一二三四五六七八九]?万?[零一二三四五六七八九]?千?[零一二三四五六七八九]?百?[零一二三四五六七八九]?十?[一二三四五六七八九]?场/;
      // if (reg.test(val)) {
      //   let canUse = await this.handleCheckCC(val);
      //   if (canUse) {
      //     cb();
      //   } else if (canUse == "") {
      //     cb(new Error("获取场次是否被使用失败"));
      //   } else {
      //     cb(new Error("当前输入场次已经被使用"));
      //   }
      // } else {
      //   cb(new Error("请输入正确的场次"));
      // }
    },
    async handleCheckCC(val) {
      let reg = /第(.*)场/;
      let cnCode = val.replace(reg, "$1");
      cnCode = cnCode == "十" ? "一十" : cnCode;
      cnCode = cnCode == "十万" ? "一十万" : cnCode;
      console.log("cnCode", cnCode);
      let code = ChineseToNumber(cnCode);
      console.log("code", code);
      let res = await valiCode({ ccbm: this.ccbm, cccode: code });
      return res.data;
    },
    checkmoney(rule, value, callback) {
      if (!value) {
        if (this.saveClose) {
          callback(new Error("请输入"));
        } else {
          callback();
        }
      } else {
        if (!/^\d{1,10}(\.\d{1,2})?$/.test(value)) {
          callback(new Error("限数字,限 10 字符"));
        } else {
          callback();
        }
      }
    },
    checkmoneyzxf(rule, value, callback) {
      if (!value) {
        if (this.saveClose) {
          callback(new Error("请输入"));
        } else {
          callback();
        }
      } else {
        if (!/^\d{1,2}(\.\d{1,4})?$/.test(value)) {
          callback(new Error("限数字,最多保留4位小数"));
        } else {
          callback();
        }
      }
    },
    checkinput(rule, value, callback) {
      if (!value) {
        if (this.saveClose) {
          callback(new Error("请输入"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    async getDetail(ccbm) {
      let res = await selectCC(ccbm);
      if (res.infoCode == 200) {
        this.tableData = res.data.deatils;
        let ee = res.data.entryAndExitOrderVO;
        this.dform = {
          ...res.data.siteVO,
          ...ee,
          pz: ee.pzmc,
        };
        this.getSL();
      }
    },
    handleSubmit(zt) {
      if (zt == "待发布") {
        this.saveClose = false;
        this.$refs.dform.validate((valid) => {
          if (valid) {
            let isValidSelected = this.wtOpts.find(
              (d) => d.wtbh == this.dform.wtbh
            );
            if (!isValidSelected) {
              this.dform.wtbh = "";
              this.$message.warning(
                "当前委托编号可以已经发布, 请换一个新的委托编号再提交!"
              );
              return;
            }
            this.dform.cczt = zt;
            this.dform.marks = JSON.stringify(this.tableData);
            this.msg = zt == "待发布" ? "保存成功!" : "发布成功!";
            this.dform.tradeMarkVOList = this.tableData;
            if (this.isAdd) {
              this.insert();
            } else {
              this.update();
            }
          }
        });
      } else {
        this.saveClose = true;
        this.$refs.dform.validate((valid) => {
          if (valid) {
            let isValidSelected = this.wtOpts.find(
              (d) => d.wtbh == this.dform.wtbh
            );
            if (!isValidSelected) {
              this.dform.wtbh = "";
              this.$message.warning(
                "当前委托编号可以已经发布, 请换一个新的委托编号再提交!"
              );
              return;
            }
            this.dform.cczt = zt;
            this.dform.marks = JSON.stringify(this.tableData);
            this.msg = zt == "待发布" ? "保存成功!" : "发布成功!";
            this.dform.tradeMarkVOList = this.tableData;
            if (this.isAdd) {
              this.insert();
            } else {
              this.update();
            }
          } else {
            this.$message.warning("请先完成必填项!");
          }
        });
      }
    },
    async insert() {
      let res = await insertCC(this.dform);
      if (res.infoCode == 200) {
        this.$message.success(this.msg);
        this.$router.push("index");
      } else {
        this.$message.error(res.msg);
      }
    },
    async update() {
      let res = await updateCC(this.dform);
      if (res.infoCode == 200) {
        this.$message.success(this.msg);
        this.$router.push("index");
      } else {
        this.$message.error(res.msg);
      }
    },
    async selectCode() {
      let res = await selectCode();
      let code = res.data;
      let codeCn = NumberToChinese(code);
      this.dform.cccode = code;
      this.dform.apcc = `第${codeCn}场`;
    },
    getSL() {
      this.dform.sl = this.tableData.reduce((a, d) => a + +d.sl, 0) || 0;
      this.dform.sl = Math.floor(this.dform.sl * 100) / 100;
    },
    async handleWtChange(val) {
      if (val == "") {
        this.tableData = [];
        return;
      }
      let res = await selectEntryAndExitOrderBySite(val);
      let cur = res.data.entryAndExitOrderVO;
      let details = res.data.deatils;
      this.dform.orderVO = cur;
      this.tableData = details;
      this.dform = {
        ...this.dform,
        pz: cur.pzmc,
        jyrq: cur.jyrq,
        wtbm: cur.wtbm,
        jylx: cur.jylx,
        wtbh: cur.wtbh,
      };
      this.getSL();
    },
    selectwtList() {
      selectEntryAndExitOrder().then((res) => {
        if (res.infoCode == 200) {
          this.wtOpts = res.data;
        }
      });
    },

    showInfo(row) {
      this.$router.push({
        path: "transObj",
        query: {
          apbm: row.apbm,
          wtbm: row.wtbm,
          bdbm: row.bdbm,
          type: "show",
        },
      });
    },
    delInfo(index) {
      if (this.tableData.length == 1) {
        this.$message.warning("至少保留一条标的信息!");
        return;
      }
      this.$confirm("此操作将删除当前信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableData.splice(index, 1);
          this.getSL();
        })
        .catch((err) => {});
    },
    rules(label, isChange) {
      return {
        required: this.saveClose,
        message: isChange ? "请选择" + label : "请输入" + label,
        trigger: ["change", "blur"],
      };
    },
  },
};
</script>
<style lang="scss" scoped>
.detail-content {
  padding: 20px;
}
.w90 {
  width: 90% !important;
}
.sub-title {
  width: 98%;
  text-align: center;
  font-size: 1em;
  line-height: 2.5em;
  color: #fff;
  background-color: #49a2fa;
  box-sizing: border-box;
  margin-bottom: 20px;
  position: relative;
}
.btn-footer {
  text-align: center;
  margin: 20px;
}
</style>
