<template>
  <div class="content-main">
    <h2
      style="
        font-weight: 600;
        font-size: 20px;
        text-align: center;
        margin-bottom: 10px;
      "
    >
      交易细则编制
    </h2>
    <el-form
      width="100%"
      label-width="120px"
      :model="formQuery"
      ref="formQuery"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="细则标题:"
            :rules="{
              required: true,
              message: '请填写细则标题',
              trigger: 'blur',
            }"
            prop="xzbt"
          >
            <el-input
              clearable
              style="width: 91%"
              :disabled="showType || !detailF"
              v-model="formQuery.xzbt"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="粮食性质:">
            <el-radio-group
              v-model="formQuery.lsxzbm"
              :disabled="showType || !detailF"
            >
              <el-radio label="2">市级储备粮</el-radio>
              <el-radio label="3">区级储备粮</el-radio>
              <el-radio label="4">贸易粮</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <!-- <el-form-item label="正文:" style="margin: 0;">
                <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="formQuery.zgyq"></el-input>
          </el-form-item>-->

          <el-form-item
            label="正文:"
            :rules="{
              required: true,
              message: '请填写正文',
              trigger: ['blur', 'change'],
            }"
            prop="xzzw"
            id="container"
            :disabled="showType"
            @input="handleEditorChange"
          >
            <vue-editor
              v-model="formQuery.xzzw"
              @input="handleEditorChange"
              ref="editor"
              v-if="!showType"
            ></vue-editor>
            <div
              v-if="showType"
              v-html="formQuery.xzzw"
              style="
                border: 1px solid #ccc;
                border-radius: 2px;
                padding: 5px;
                min-height: 100px;
              "
            ></div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22" style="margin-top: 15px">
          <el-form-item label="附件:" prop="fjid" class="upload_dom">
            <!-- :rules="{required:true,message:'请上传附件'}" -->
            <el-upload
              :action="fileApi"
              :limit="1"
              :with-credentials="true"
              initEditableDiv
              :headers="myHeader"
              :fileList="fileList"
              :on-remove="handleFileRemove"
              :on-success="handleFileSuccess"
              :on-error="handlerError"
              :on-preview="handlePreview"
              :on-exceed="handleExceed"
              :disabled="showType"
            >
              <el-button size="small" type="primary" :disabled="showType"
                >点击上传</el-button
              >
              <el-input type="hidden" v-model="formQuery.fjid"></el-input>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="编制人员:"
            :rules="{
              required: true,
              message: '请填写编制人员',
              trigger: 'change',
            }"
            prop="bzr"
          >
            <el-input
              clearable
              style="width: 90%"
              :disabled="showType || !detailF"
              v-model="formQuery.bzr"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="编制时间:" prop="bzsj" label-width="80px">
            <el-date-picker
              type="date"
              placeholder="编制时间"
              :disabled="showType"
              v-model="formQuery.bzsj"
              style="width: 100%"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="userType">
        <div style="text-align: center">
          <!-- 新增保存           -->
          <el-button
            type="primary"
            v-if="!showType"
            v-show="newUp && newOps"
            @click="scalePlanSave"
            size="small"
            class="iconfont iconbaocun"
            >保存</el-button
          >
          <!-- 修改保存           -->
          <el-button
            type="primary"
            v-if="!showType"
            @click="scalePlanUpdateDetaisl"
            v-show="opp || newAlls || uio"
            size="small"
            class="iconfont iconbaocun"
            >保存</el-button
          >
          <!-- 修改上报 -->
          <!-- -->
          <el-button
            type="primary"
            v-if="!showType"
            v-show="opp || newAlls || pop"
            @click="scalePlanIssuedDetails"
            size="medium"
            class="iconfont iconfabu"
            >发布</el-button
          >
          <!-- 新增上报           -->
          <!--   -->
          <el-button
            type="primary"
            v-if="!showType"
            v-show="newUp && newOps"
            @click="newScalePlan"
            size="medium"
            class="iconfont iconfabu"
            >发布</el-button
          >
          <!--  -->
          <el-button
            type="primary"
            size="small"
            @click="scalePlanReturn"
            class="iconfont iconfanhui"
            >返回</el-button
          >
        </div>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  findByPid,
  findByGroupId,
  getDataGroups,
  getScalePlanDrawUpDetail,
  getScalePlanDrawUpAdd,
  getScalePlanCityOptions,
  getScalePlanInsert,
  getScalePlanDetails,
  getScalePlanInitDetails,
  getScalePlanIssued,
  findByCode,
  getScalePlanUpdate,
  fileInfo,
  getMores,
  downloadFile,
  showMaterialInfo,
} from "@/api/transaction/trading/tradingRules/index";
import { getNowDate } from "@/utils/index";
import { VueEditor } from "vue2-editor";
import { FileApi } from "@/api/index";
import { getToken } from "@/utils/auth";

export default {
  components: {
    VueEditor,
  },
  computed: {
    myHeader() {
      return {
        token: getToken(),
      };
    },
  },
  data() {
    return {
      contenteditable: true,
      fileList: [], // 文件列表
      wjids: "",
      fileApi: FileApi + "/file/upload",
      uio: false,
      pop: false,
      newOps: true,
      opp: false,
      newAlls: false,
      newUp: false,
      detailF: true,
      dtimeYear: "",
      dtime: "",
      moreList: [],
      orgCode: "",
      orgName: "",
      listLoading: true,
      detailLoading: false,
      disabledFlag: true,
      dialogTableVisible: false,
      showType: false,
      updateType: false,
      userType: true,
      // showPlanDrawUp: false,
      formQuery: {
        lsxzmc: "",
        lsxzbm: "",
        bzr: "",
        bzsj: getNowDate(),
        endDate: "",
        fbzt: 0,
        fbztmc: "",
        fjid: "",
        remark: "",
        startDate: "",
        status: 0,
        xzbm: "",
        xzbt: "",
        xzzw: "",
      },
      addItemForm: {},
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      cityOptions: [],
      fileList: [],
      ownTableData: [],
      superiorTableData: [],
      djOptions: [],
      pz0ptions: [],
      qualityTable: [],
      storageQualityTable: [],
      isValid: false, // 验证表单
    };
  },
  created() {
    if (this.$route.query.type == "show") {
      this.showType = true;
      this.contenteditable = false;
      this.detailF = false;
      this.scalePlanDetails(this.$route.query.xzbm);
    }
    if (this.$route.query.type == "update") {
      this.pop = true;
      this.showType = false;
      this.detailF = false;
      this.scalePlanDetails(this.$route.query.xzbm);
    }
    if (this.$route.query.type == "newSa") {
      this.newAlls = false;
      this.newUp = true;
      this.showType = false;
    }
    if (this.$route.query.type == "updateSave") {
      this.uio = true;
      this.pop = true;
      this.showType = false;
      this.scalePlanDetails(this.$route.query.xzbm);
    }
  },
  methods: {
    async checkInput() {
      await this.$refs.formQuery.validate((valid) => {
        if (!valid) this.$message.warning("请先完成必填项");
        this.isValid = valid;
      });
    },
    handleEditorChange() {
      if (this.formQuery.xzzw.length) {
        this.$nextTick(() => {
          var el = document.querySelector("#container .el-form-item__error");
          if (el) el.style.display = "none";
        });
      } else {
        this.$nextTick(() => {
          var el = document.querySelector("#container .el-form-item__error");
          if (el) el.style.display = "block";
        });
      }
    },
    handleFileRemove(file, fileList) {
      this.wjids = "";
      this.formQuery.fjid = "";
      this.$nextTick(() => {
        var el = document.querySelector(".upload_dom .el-form-item__error");
        if (el) el.style.display = "block";
      });
    },
    handleFileSuccess(res, file) {
      if (res.infoCode == 200) {
        this.wjids = res.data.id;
        this.formQuery.fjid = res.data.id;
        this.$message.success("上传成功！");
        this.$nextTick(() => {
          var el = document.querySelector(".upload_dom .el-form-item__error");
          if (el) el.style.display = "none";
        });
        return;
      }
      this.fileList = [];
      this.$message.error(res.msg || "上传失败,请重试");
    },
    handleExceed(file, fileList) {
      this.$message.warning(`当前限制上传数量为1`);
    },
    handlerError() {
      this.$message.error("上传失败,请重试");
    },
    //新增发布
    async newScalePlan() {
      await this.checkInput();
      if (!this.isValid) return;
      if (this.formQuery.lsxzbm == 2) {
        this.formQuery.lsxzmc = "市级储备粮";
      }
      if (this.formQuery.lsxzbm == 3) {
        this.formQuery.lsxzmc = "区级储备粮";
      }
      if (this.formQuery.lsxzbm == 4) {
        this.formQuery.lsxzmc = "贸易粮";
      }
      let data = {
        ...this.formQuery,
        fbztmc: "已发布",
        fbzt: 1,
        remark: "",
      };

      //新增保存可以了
      getScalePlanDrawUpAdd(data).then((res) => {
        if (res.infoCode == "200") {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.$router.push({
            name: "tradingRules",
          });
        } else {
          this.$message({
            message: "保存失败",
            type: "error",
          });
        }
      });
    },
    //查看详情
    scalePlanDetails(xzbm) {
      let data = {
        xzbm: xzbm,
      };
      getScalePlanDetails(data).then((res) => {
        this.formQuery = res.data;
        if (res.infoCode == "200") {
          this.wjids = res.data.fjid || "";
          if (this.wjids) {
            this.getFileDetail();
          }
          if (this.showType) {
            var editor = document.querySelector(".ql-editor");
            if (editor) editor.setAttribute("contenteditable", false);
          }
        }
      });
    },
    getFileDetail() {
      downloadFile(this.wjids)
        .then((res) => {
          if (res.infoCode == 200) {
            this.fileList = [
              {
                url: res.data.link,
                name: res.data.name,
              },
            ];
            return;
          }
          this.$message.error("获取文件信息失败");
        })
        .catch((err) => {
          this.$message.error("获取文件信息失败");
        });
    },
    handlePreview(file, fileList) {
      document.location.href = `${FileApi}/file/download?id=${this.wjids}`;
    },
    //删除ok......
    deleteInfo(index) {
      this.$confirm("此操作将删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ownTableData.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //保存按钮
    async scalePlanSave() {
      // await this.checkInput()
      // if (!this.isValid) return
      this.formQuery.fjid = this.wjids;
      if (this.formQuery.lsxzbm == 2) {
        this.formQuery.lsxzmc = "市级储备粮";
      }
      if (this.formQuery.lsxzbm == 3) {
        this.formQuery.lsxzmc = "区级储备粮";
      }
      if (this.formQuery.lsxzbm == 4) {
        this.formQuery.lsxzmc = "贸易粮";
      }
      let data = {
        ...this.formQuery,
        fbztmc: "暂存",
        fbzt: 0,
        xzbm: null,
        remark: "ssss",
      };

      //新增保存可以了
      getScalePlanDrawUpAdd(data).then((res) => {
        if (res.infoCode == "200") {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.$router.push({
            name: "tradingRules",
          });
        } else {
          this.$message({
            message: "保存失败",
            type: "error",
          });
        }
      });
    },
    //修改按钮
    async scalePlanUpdateDetaisl(xzbm) {
      // await this.checkInput()
      // if (!this.isValid) return
      this.scalePlanUpdate(xzbm);
    },
    // //修改保存按钮
    scalePlanUpdate(xzbm) {
      this.scalePlanDetails(xzbm);
      this.formQuery.fjid = this.wjids;
      let datas = {
        ...this.formQuery,
        fbztmc: "暂存",
        fbzt: 0,
        remark: "ssss",
        bzsj: this.dtime,
      };
      getScalePlanUpdate(datas).then((res) => {
        if (res.infoCode == "200") {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.$router.push({
            name: "tradingRules",
          });
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
      });
    },
    async scalePlanIssuedDetails(xzbm) {
      await this.checkInput();
      if (!this.isValid) return;
      this.showType = true;
      this.scalePlanIssued(xzbm);
    },
    // //修改发布
    scalePlanIssued(xzbm) {
      this.scalePlanDetails(xzbm);
      let datas = {
        ...this.formQuery,
        fbztmc: "已发布",
        fbzt: 1,
        remark: "ssss",
        bzsj: this.dtime,
      };
      getScalePlanUpdate(datas).then((res) => {
        console.log(res, "ressss");

        if (res.infoCode == "200") {
          this.$message({
            message: "发布成功",
            type: "success",
          });
          this.$router.push({
            name: "tradingRules",
          });
        } else {
          this.$message({
            message: "发布失败",
            type: "error",
          });
        }
      });
    },
    scalePlanReturn() {
      this.$router.push({
        name: "tradingRules",
      });
      this.formQuery = {};
    },

    // getScalePlanDrawUpOptions() {
    //   findByPid("114").then(res => {
    //     this.pz0ptions = res.data
    //   })
    //   findByGroupId("LSDJ").then(res => {
    //     this.djOptions = res.data
    //   })
    // },
    // scalePlanDrawUpAdd() {
    //   let data = {}

    //   this.storageQualityTable.forEach(item => {
    //     data[item['remark']] = item[item['remark']]
    //   })
    //   this.qualityTable.forEach(item => {
    //     data[item['remark']] = item[item['remark']]
    //   })
    //   let orgCode = sessionStorage.getItem('orgCode')
    //   data.lsdjbm = this.addItemForm.lsdjbm
    //   data.lsdjmc = this.addItemForm.lsdjmc
    //   data.lspzbm = this.addItemForm.lspzbm
    //   data.lspzmc = this.addItemForm.lspzmc
    //   data.jhsl = this.addItemForm.jhsl
    //   data.wcqx = this.addItemForm.wcqx
    //   data.zlbm = this.addItemForm.zlbm
    //   data.sjbm = orgCode
    //   getScalePlanDrawUpAdd(data).then(res => {
    //     if (res.infoCode == "200") {
    //       this.$message({
    //         message: '保存成功',
    //         type: 'success'
    //       });
    //       data.zlbm = res.data.zlbm
    //       this.ownTableData.push(data)
    //       this.dialogTableVisible = false
    //     } else {
    //       this.$message({
    //         message: '保存失败',
    //         type: 'error'
    //       });
    //     }
    //   })
    // },
    // changePzmc(value) {
    //   this.getScalePlanDrawUpPzOptions(value)

    //   this.pz0ptions.forEach(i => {
    //     if (i.id == value) {
    //       this.addItemForm.lspzmc = i.groupName
    //     }
    //   })
    // },
    // changeLsdj(value) {
    //   this.getScalePlanDrawUpDjOptions(value)
    //   this.djOptions.forEach(i => {
    //     if (i.dictCode == value) {
    //       this.addItemForm.lsdjmc = i.dictName
    //     }
    //   })
    // },

    /*计划制定 End*/
  },
};
</script>

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

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

// .iconfont {
//   font-size: 13px;
// }

.dialog-footer {
  text-align: center;
  display: inline-block;
  width: 100%;
}

.tableWrap {
  position: relative;
}

.transferTable .tdTitle {
  width: 84px;
}

.transferTable {
  width: 400px;
  display: inline-block;
  margin-left: 110px;
}

.qualityTableTitle {
  position: absolute;
  top: 0;
  left: 0;
  margin-left: 10px;
}
</style>
