<template>
  <div class="content-detail">
    <el-form :model="detailForm" ref="detailForm" label-width="130px">
      <h3
        style="
          text-align: center;
          font-weight: 600;
          margin-bottom: 20px;
          font-size: 18px;
          color: #4588db;
        "
      >
        交易委托
      </h3>
      <el-row>
        <el-col :span="11">
          <el-form-item label="交易性质" required>
            <el-radio-group
              v-model="detailForm.jylx"
              :disabled="isView"
              @change="handleTradeTypeChange"
              class="input-w"
            >
              <el-radio :label="0">采购</el-radio>
              <el-radio :label="1">销售</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="品种" required prop="pzbm">
            <el-select
              v-model="detailForm.pzbm"
              :rules="[
                { required: true, message: '请选择品种', trigger: ['change'] },
              ]"
              clearable
              placeholder="请选择品种"
              @change="hanldeTypesChange"
              :disabled="isView"
              class="input-w"
            >
              <el-option
                v-for="item in variety"
                :key="item.dictCode"
                :label="item.dictName"
                :value="item.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="委托编号" required>
            <el-input
              v-model="detailForm.wtbh"
              disabled
              class="input-w"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="委托方" required>
            <el-input
              v-model="detailForm.wtfmc"
              disabled
              class="input-w"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- wtfbm -->
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="交割日期" required prop="jgrq">
            <el-date-picker
              v-model="detailForm.jgrq"
              :rules="[
                {
                  required: true,
                  message: '请选择交割日期',
                  trigger: ['change'],
                },
              ]"
              :disabled="isView"
              type="date"
              value-format="yyyy-MM-dd"
              class="input-w"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="交易日期" required prop="jyrq">
            <el-date-picker
              v-model="detailForm.jyrq"
              :rules="[
                {
                  required: true,
                  message: '请选择交易日期',
                  trigger: ['change'],
                },
              ]"
              :disabled="isView"
              type="date"
              value-format="yyyy-MM-dd"
              class="input-w"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showorfals">
        <!-- <el-form-item label="损耗计算方式"  required>
          <el-radio-group
            v-model="detailForm.jsfs"
            :disabled="isView"
            @change="handleWayChange"
            class="input-w"
          >
            <el-radio :label="0">先算</el-radio>
            <el-radio :label="1">后算</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-col :span="11">
          <el-form-item label="粮食性质" required>
            <el-select
              v-model="detailForm.lsxzbm"
              clearable
              placeholder="请选择粮食性质"
              @change="hanldePropertyChange"
              :disabled="isView"
              class="input-w"
            >
              <el-option
                v-for="item in properties"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="width: 80%; margin: 0 auto">
        <!-- <el-input v-model="detailForm.wbnr" type="textarea" :autosize="{minRows:5}" :disabled="isView"></el-input> -->
        <quill-editor v-model="detailForm.wbnr" id="detailText"></quill-editor>
      </el-row>
      <el-row v-if="showfj">
        <el-col :span="12">
          <el-form-item label="轮换协议" required>
            <el-upload
              :disabled="isView"
              :on-success="handleSuccess"
              class="upload-demo"
              :action="fileUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :file-list="fileList"
              style="width: 95%"
            >
              <el-button
                type="primary"
                size="small"
                class="iconfont iconshangchuan"
                v-if="!isView"
                >上传</el-button
              >
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="承诺书">
            <el-upload
              :disabled="isView"
              :on-success="handleSuccess1"
              class="upload-demo"
              :action="fileUrl"
              :on-preview="handlePreview1"
              :on-remove="handleRemove"
              :before-remove="beforeRemove1"
              :file-list="fileList1"
              style="width: 95%"
            >
              <el-button
                type="primary"
                size="small"
                class="iconfont iconshangchuan"
                v-if="!isView"
                >上传</el-button
              >
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="接受委托" required>
          <el-radio-group
            v-model="detailForm.sfjs"
            :disabled="!isConfirm"
            @change="handleRefuse"
            class="input-w"
          >
            <el-radio :label="0">确认</el-radio>
            <el-radio :label="1">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item
          label="意见"
          prop="yj"
          :rules="{ required: true, message: '请填写意见', trigger: 'blur' }"
        >
          <el-input
            v-model="detailForm.yj"
            :autosize="{ minRows: 3 }"
            type="textarea"
            :disabled="!isConfirm"
            style="width: 500px"
          ></el-input>
        </el-form-item>
      </el-row>
    </el-form>
    <el-row style="text-align: center; margin-top: 20px">
      <el-button
        v-if="!isView"
        @click="handleSave"
        class="iconfont iconbaocun"
        type="primary"
        size="small"
        >保存</el-button
      >
      <el-button
        v-if="isConfirm"
        @click="handleConfirm"
        class="iconfont iconbaocun"
        type="primary"
        size="small"
      >
        保存
        <!--确认-->
      </el-button>
      <el-button
        v-if="isConfirm"
        @click="handleConfirmAndSubmit"
        class="iconfont iconfabu"
        type="primary"
        size="small"
        v-show="isNoRefuse"
      >
        保存并发布
        <!--确认并发布-->
      </el-button>
      <el-button
        v-if="!isView"
        @click="handleSubmit"
        class="iconfont icontijiao"
        type="primary"
        size="small"
        >提交</el-button
      >
      <el-button
        @click="$router.push('index')"
        class="iconfont iconfanhui"
        type="primary"
        size="small"
        >返回</el-button
      >
    </el-row>
  </div>
</template>

<script>
import {
  varietys,
  insert,
  update,
  detail,
} from "@/api/transaction/tradePlan/outInDepotEntrust/index.js";
import { fileInfo } from "@/api/transaction/registrationFee/transactionSignup/index";
import { VueEditor } from "vue2-editor";
import { FileApi } from "@/api/index";

export default {
  components: {
    VueEditor,
  },
  mounted() {
    this.$nextTick(() => {
      document
        .querySelector(".ql-editor")
        .setAttribute("contenteditable", "false");
    });
  },
  data() {
    return {
      showorfals: true,
      detailForm: {
        jylx: 0,
        jsfs: 0,
        sfjs: 0, // 接受委托
        wtbh: new Date().getFullYear() + "CG",
        wtfmc: window.sessionStorage.getItem("orgName"),
        wtfbm: window.sessionStorage.getItem("orgCode"),
        tbr: window.sessionStorage.getItem("userName"),
        tbr: window.sessionStorage.getItem("userName"),
        jsfsmc: "先算",
        jylxmc: "采购",
        wbnr: "",
      },
      variety: [], // 品种列表
      properties: [
        { label: "市级储备粮", value: "2" },
        { label: "区级储备粮", value: "3" },
        { label: "贸易粮", value: "4" },
      ], // 粮食性质列表
      isEdit: false,
      isView: false,
      isConfirm: false,
      wtbm: "", // 主键
      isNoRefuse: true,
      showfj: false,
      fileList: [],
      fileList1: [],
    };
  },
  created() {
    if (this.$route.query.state == 2) {
      // this.showorfals = false
    }
    // 0 新增 1 修改 2 详情查看 3 确认 4 发布 5 公告
    let { state, wtbm } = this.$route.query;
    this.wtbm = wtbm;
    if (state == 1) this.isEdit = true;
    if (state == 2) {
      this.isView = true;
    }
    if (state == 3) {
      this.isView = true;
      this.isConfirm = true;
    }
    if (state != 0) this.getDetail();
    this.getTypes();
  },
  methods: {
    handleRefuse() {
      if (this.detailForm.sfjs == 1) {
        this.detailForm.zt = "91000008";
        this.detailForm.ztmc = "已驳回";
        this.detailForm.apzt = "91000008";
        this.detailForm.apztmc = "已驳回";
      } else {
        this.detailForm.zt = "91000018";
        this.detailForm.ztmc = "已确认";
        this.detailForm.apzt = "91000049";
        this.detailForm.apztmc = "待安排";
      }
      this.isNoRefuse = !this.detailForm.sfjs;
    },
    hanldePropertyChange(val) {
      var cur = this.properties.filter((item) => item.value == val)[0];
      this.detailForm.lsxzmc = cur.label;
    },
    async checkInput() {
      await this.$refs.detailForm.validate((valid) => {
        if (!valid) this.$message.warning("请先完成必填项");
        this.isValid = valid;
      });
    },
    async handleConfirmAndSubmit() {
      await this.checkInput();
      if (!this.isValid) return;
      this.detailForm.url = `/transaction/tradeEntrust/outInDepotPlan/plan`;
      this.detailForm.itemUrlHaveDone = `/transaction/tradeEntrust/outInDepotPlan/planDetail`;

      this.detailForm.itemQuery = JSON.stringify({
        state: "0",
        idKey: "wtbm",
        jylx: this.detailForm.jylx,
        wtfbm: this.detailForm.wtfbm,
      });
      this.detailForm.itemQueryHaveDone = JSON.stringify({
        state: "2",
        idKey: "wtbm",
        jylx: this.detailForm.jylx,
        wtfbm: this.detailForm.wtfbm,
      });
      this.update(true);
    },
    async handleConfirm() {
      await this.checkInput();
      if (!this.isValid) return;
      // console.log(this.detailForm);
      this.detailForm.url = `/transaction/tradeEntrust/outInDepotPlan/plan`;
      this.detailForm.itemUrlHaveDone = `/transaction/tradeEntrust/outInDepotPlan/planDetail`;
      this.detailForm.itemQuery = JSON.stringify({
        state: "0",
        idKey: "wtbm",
        jylx: this.detailForm.jylx,
        wtfbm: this.detailForm.wtfbm,
        jyrq: this.detailForm.jyrq,
        lsxzbm: this.detailForm.lsxzbm,
      });
      this.detailForm.itemQueryHaveDone = JSON.stringify({
        state: "2",
        idKey: "wtbm",
        jylx: this.detailForm.jylx,
        wtfbm: this.detailForm.wtfbm,
        jyrq: this.detailForm.jyrq,
        lsxzbm: this.detailForm.lsxzbm,
      });
      this.update();
    },
    async getDetail() {
      var res = await detail(this.wtbm);
      if (res && res.infoCode === 200) {
        this.detailForm = res.data;
        if (!res.data.sfjs) {
          this.detailForm.sfjs = 0;
        }
        if (this.detailForm.jylx == 1 && this.detailForm.lsxzbm == 2) {
          this.showfj = true;
        }
        if (this.detailForm.wtfj) {
          fileInfo(this.detailForm.wtfj).then((res) => {
            this.fileList = res.data;
          });
        }
        if (this.detailForm.cnfj) {
          fileInfo(this.detailForm.cnfj).then((res) => {
            this.fileList1 = res.data;
          });
        }
        this.handleRefuse();
      }
    },
    handleWayChange(val) {
      this.detailForm.jsfsmc = val == 0 ? "先算" : "后算";
    },
    hanldeTypesChange(val) {
      var type = this.variety.filter((item) => item.dictCode == val)[0];
      this.detailForm.pzmc = type.dictName;
    },
    handleTradeTypeChange(val) {
      this.detailForm.jylxmc = val == 0 ? "采购" : "销售";
      var year = new Date().getFullYear();
      this.detailForm.wtbh = year + (val == 0 ? "CG" : "XS");
    },
    handleSave() {
      this.detailForm.zt = "91000001";
      this.detailForm.ztmc = "待提交";
      if (this.isEdit) {
        this.update();
        return;
      }
      this.insert();
    },
    insert() {
      insert({
        ...this.detailForm,
      }).then((res) => {
        if (res.infoCode === 200) {
          this.$message.success(res.msg);
          this.$router.push("index");
          return;
        }
        this.$message.error(res.msg);
      });
    },
    update(isPublish = false) {
      this.$refs["detailForm"].validate((valid) => {
        if (valid) {
          update({
            ...this.detailForm,
          }).then((res) => {
            if (res.infoCode === 200) {
              if (this.detailForm.sfjs != 1) {
                this.$message.success("确认成功!");

                if (isPublish) {
                  this.$router.push({
                    path: "publish",
                    query: {
                      state: 0,
                      wtbm: this.wtbm,
                    },
                  });
                  return;
                }
              } else {
                this.$message.success("驳回成功！");
              }

              this.$router.push("index");
              return;
            }
            this.$message.error(res.msg);
          });
        } else {
          this.$message.warning("请先完成必填项");
        }
      });
    },
    handleSubmit() {
      this.detailForm.zt = "91000004";
      this.detailForm.ztmc = "已提交";
      if (this.isEdit) {
        this.update();
        return;
      }
      this.insert();
    },
    getTypes() {
      varietys(11).then((res) => {
        this.variety = res.data;
      });
    },
    handleSuccess(res, file, fileList) {
      this.fileList = fileList;
      this.$message.success("上传成功！");
    },
    handleRemove(res, file) {
      this.fileList = file;
    },
    handlePreview(file, fileList) {
      window.location.href = `${FileApi}/file/download?id=${
        file.response ? file.response.data.id : file.id
      }`;
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`, "提示");
    },

    handleSuccess1(res, file, fileList) {
      this.fileList1 = fileList;
      this.$message.success("上传成功！");
    },
    handleRemove1(res, file) {
      this.fileList1 = file;
    },
    handlePreview1(file, fileList) {
      window.location.href = `${FileApi}/file/download?id=${
        file.response ? file.response.data.id : file.id
      }`;
    },
    beforeRemove1(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`, "提示");
    },
  },
};
</script>

<style lang="scss" scoped>
.content-detail {
  padding: 20px;
  width: 95%;
  margin: 0 auto;

  .input-w {
    width: 90%;
  }

  .textarea {
    width: 100%;

    /deep/ .el-form-item__content {
      min-width: 50%;
    }
  }
  #detailText /deep/ .ql-toolbar.ql-snow {
    display: none;
  }
  #detailText /deep/ .ql-container.ql-snow {
    border: 1px solid #ccc !important;
  }
}
</style>
