<template>
  <div class="detail-main">
    <h2
      style="
        text-align: center;
        font-weight: 700;
        margin-bottom: 10px;
        font-size: 18px;
        color: #4588db;
      "
    >
      出入库安排
    </h2>
    <el-form ref="dform" :model="dform">
      <el-table :data="dform.tableData" stripe border>
        <el-table-column
          type="index"
          align="center"
          label="序号"
          width="70"
        ></el-table-column>
        <el-table-column
          prop="dwmc"
          align="center"
          label="承储单位"
          min-width="160"
          label-class-name="require_star"
        >
          <template slot-scope="scope">
            <el-form-item>
              <el-select
                v-model="scope.row.dwmc"
                @change="handleCompanyChange($event, scope.$index)"
                :disabled="isView"
                :class="{ redbod: !scope.row.dwmc && isSubmit }"
                filterable
              >
                <el-option
                  v-for="item in companies"
                  :key="item.kddm"
                  :value="item.kdmc"
                  :label="item.kdmc"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="pzmc"
          align="center"
          label="品种"
          label-class-name="require_star"
        >
          <template slot-scope="scope">
            <el-form-item>
              <el-select
                v-model="scope.row.pzmc"
                @change="handleVarietyChange($event, scope.$index)"
                :disabled="isView"
                :class="{ redbod: !scope.row.pzmc && isSubmit }"
                filterable
              >
                <el-option
                  v-for="item in variety"
                  :key="item.dictCode"
                  :value="item.dictName"
                  :label="item.dictName"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="lssl"
          align="center"
          label="数量"
          label-class-name="require_star"
        >
          <template slot-scope="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.lssl'"
              :rules="{
                required: false,
                validator: checkds,
                trigger: ['change', 'blur'],
              }"
            >
              <el-input
                v-model="scope.row.lssl"
                :disabled="isView"
                :class="{ redbod: !scope.row.lssl && isSubmit }"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="scnd"
          align="center"
          label="生产年度"
          width="120px"
          label-class-name="require_star"
        >
          <template slot-scope="scope" class="cell">
            <el-form-item>
              <el-date-picker
                type="year"
                value-format="yyyy"
                v-model="scope.row.scnd"
                style="width: 100%"
                :disabled="isView"
                :class="{ redbod: !scope.row.scnd && isSubmit }"
              ></el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="sfbg" align="center" label="财务账变更">
          <template slot-scope="scope">
            <el-form-item>
              <el-select v-model="scope.row.sfbg" :disabled="isView">
                <el-option
                  v-for="item in [
                    { code: 0, name: '是' },
                    { code: 1, name: '否' },
                  ]"
                  :key="item.name"
                  :value="item.code"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="remark" align="center" label="备注">
          <template slot-scope="scope">
            <el-form-item>
              <el-input
                v-model="scope.row.remark"
                :disabled="isView"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="90px"
          v-if="!isView"
        >
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="light"
              content="删除"
              placement="top"
            >
              <el-button
                @click="handleDelRow(scope.$index)"
                type="primary"
                class="operate_delete_btn iconfont iconshanchu"
                size="small"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <el-row v-if="!isView">
      <div class="add-table-item">
        <el-tooltip class="item" effect="light" content="新增" placement="top">
          <el-button
            @click="handleAddRow"
            type="text"
            class="iconfont iconzengjia"
          ></el-button>
        </el-tooltip>
      </div>
    </el-row>
    <el-row class="footer_btn">
      <el-button
        type="primary"
        v-if="!isView"
        size="small"
        @click="handleSave"
        class="iconfont iconbaocun"
        >保存</el-button
      >
      <el-button
        type="primary"
        v-if="!isView"
        size="small"
        @click="handleSubmit"
        class="iconfont icontijiao"
        >提交</el-button
      >
      <el-button
        type="primary"
        size="small"
        @click="$router.push('index')"
        class="iconfont iconfanhui"
        >返回</el-button
      >
    </el-row>
  </div>
</template>

<script>
import {
  companies,
  varietys,
  insert,
  update,
  detail,
  selectWareDetail,
} from "@/api/transaction/tradeEntrust/outInDepotPlan/index.js";
// import { VueEditor } from "vue2-editor";

export default {
  // components: {
  //   VueEditor
  // },
  data() {
    return {
      isSubmit: false,
      planData: {
        pzbm: "",
        dwbm: "",
        lssl: "",
        scnd: "",
        sfbg: "",
        remark: "",
        sjlx: 0, // 安排0, 货源1
        wtbm: "",
        jylx: "",
      },
      dform: {
        tableData: [],
      },

      rowData: {},
      companies: [],
      variety: [],
      form: {
        apzt: "",
        apztmc: "",
        wtbm: "",
      },
      isAdd: false,
      isView: false,
      tipMsg: "",
    };
  },
  created() {
    // state 0 add 1 update 2 detail
    let { state, wtbm, jylx } = this.$route.query;
    this.form.wtbm = wtbm;
    this.planData.wtbm = wtbm;
    this.planData.jylx = jylx;
    if (state == 0) {
      this.isAdd = true;
      this.dform.tableData.push(this.planData);
    } else {
      this.getDetail();
    }
    if (state == 2) {
      this.isView = true;
    } else {
      this.getCompanies();
      this.getTypes();
    }
  },
  methods: {
    checkds(rule, value, callback) {
      // console.log(rule, value, "value");
      if (!value) {
        callback();
      } else {
        if (!/^\d{1,10}(\.\d{1,3})?$/.test(value)) {
          callback(new Error("不符合格式"));
        } else {
          callback();
        }
      }
    },
    getDetail() {
      selectWareDetail({
        wtbm: this.form.wtbm,
        aplx: 0,
        // jylx:this.planData.jylx,
        sjlx: 0,
      }).then((res) => {
        if (res.infoCode === 200) {
          this.dform.tableData = res.data;
        }
      });
    },
    handleSave() {
      this.$refs["dform"].validate((valid) => {
        if (valid) {
          // var isValid = this.dform.tableData.some(
          //   d => !d.dwmc || d.sfbg === "" || !d.pzmc || !d.lssl || !d.scnd
          // );
          // if (isValid) {
          //   this.isSubmit = true;
          //   this.$message.warning("表格内有填写才能保存!!");
          //   return;
          // }
          this.form = {
            ...this.form,
            apzt: "91000001",
            apztmc: "待提交",
          };
          this.tipMsg = "保存成功!";

          if (this.isAdd) {
            this.insert();
            return;
          }
          this.update();
        }
      });
    },
    handleSubmit() {
      this.$refs["dform"].validate((valid) => {
        if (valid) {
          var isValid = this.dform.tableData.some(
            (d) => !d.dwmc || !d.pzmc || !d.lssl || !d.scnd
          );
          // || d.sfbg === ""
          if (isValid) {
            this.isSubmit = true;
            this.$message.warning("请先完成表格必填项再提交!!");
            return;
          }
          this.form = {
            ...this.form,
            apzt: "91000004",
            apztmc: "已提交",
            hybzt: "91000049",
            hybztmc: "待安排",
            wtfbm: this.$route.query.wtfbm,
            url: `/transaction/tradeEntrust/goodsSourceTable/plan`,
            itemQuery: JSON.stringify({
              state: "0",
              idKey: "wtbm",
              jylx: this.$route.query.jylx,
              wtfmc: "天津市粮食储备有限公司",
              wtfbm: this.$route.query.wtfbm,
              jyrq: this.$route.query.jyrq,
              lsxzbm: this.$route.query.lsxzbm,
            }),
            itemQueryHaveDone: JSON.stringify({
              state: "2",
              idKey: "wtbm",
              jylx: this.$route.query.jylx,
              wtfmc: "天津市粮食储备有限公司",
              wtfbm: this.$route.query.wtfbm,
              jyrq: this.$route.query.jyrq,
              lsxzbm: this.$route.query.lsxzbm,
            }),
          };
          this.tipMsg = "提交成功!";

          if (this.isAdd) {
            this.insert();
            return;
          }
          this.update();
        }
      });
    },
    insert() {
      insert({
        details: this.dform.tableData,
        entryAndExitOrderVO: this.form,
        aplx: 0,
      }).then((res) => {
        if (res.infoCode === 200) {
          this.$message.success(this.tipMsg);
          this.$router.push("index");
          return;
        }
        this.$message.error(res.msg);
      });
    },
    update() {
      update({
        details: this.dform.tableData,
        entryAndExitOrderVO: this.form,
        aplx: 0,
      }).then((res) => {
        if (res.infoCode === 200) {
          this.$message.success(this.tipMsg);
          this.$router.push("index");
          return;
        }
        this.$message.error(res.msg);
      });
    },
    handleCompanyChange(val, index) {
      let cur = this.companies.filter((item) => item.kdmc == val)[0];
      this.dform.tableData[index].dwbm = cur.kddm;
    },
    handleVarietyChange(val, index) {
      let cur = this.variety.filter((item) => item.dictName == val)[0];
      this.dform.tableData[index].pzbm = cur.dictCode;
    },
    handleAddRow() {
      if (this.dform.tableData.length < 1) {
        this.dform.tableData.push({
          ...this.planData,
        });
      } else {
        this.dform.tableData.push({
          // ...this.planData
          pzbm: "",
          dwbm: "",
          lssl: "",
          scnd: "",
          sfbg: "",
          remark: "",
          sjlx: 0, // 安排0, 货源1
          wtbm: this.$route.query.wtbm,
          jylx: "",
        });
      }
    },
    handleDelRow(index) {
      this.dform.tableData.splice(index, 1);
    },
    getCompanies() {
      companies().then((res) => {
        this.companies = res.data;
      });
    },
    getTypes() {
      varietys(11).then((res) => {
        this.variety = res.data;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.detail-main {
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  .el-table /deep/ .cell.require_star:before {
    content: "*";
    color: red;
  }
  .add-table-item {
    text-align: right;
    margin-right: 36px;

    .iconfont {
      font-size: 20px;
      font-weight: bold;
      cursor: pointer;
    }
  }
  .redbod /deep/ input {
    border: 1px solid red;
  }

  .footer_btn {
    text-align: center;
    margin: 20px 0;
  }
}
</style>
