<template>
  <div class="detail-main">
    <h2
      v-if="$route.query.jylx == 1"
      style="
        text-align: center;
        font-weight: 600;
        margin-bottom: 10px;
        color: #4588db;
        font-size: 18px;
      "
    >
      货源表
    </h2>
    <h2
      v-else
      style="
        text-align: center;
        font-weight: 600;
        margin-bottom: 10px;
        color: #4588db;
        font-size: 18px;
      "
    >
      仓号表
    </h2>
    <el-form ref="dform" :model="dform">
      <el-table :data="dform.tableData" stripe border>
        <el-table-column
          type="index"
          align="center"
          label="序号"
          width="60"
        ></el-table-column>
        <el-table-column
          prop="dwmc"
          align="center"
          label="承储单位"
          min-width="160"
          label-class-name="require_star"
        >
          <template slot-scope="scope">
            <el-select
              :class="{ redbod: !scope.row.dwbm && isSubmit }"
              v-model="scope.row.dwbm"
              @change="handleCompanyChange($event, scope.row)"
              :disabled="isView"
              clearable
            >
              <el-option
                v-for="item in companies"
                :key="item.dwbm"
                :value="item.dwbm"
                :label="item.dwmc"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="ccdd"
          align="center"
          label="储存地点"
          label-class-name="require_star"
        >
          <template slot-scope="scope">
            <el-select
              v-if="$route.query.jylx == 1"
              v-model="scope.row.cfbm"
              filterable
              :disabled="isView"
              @change="
                (val) => {
                  ccddChange(val, scope.row);
                }
              "
              clearable
              :class="{ redbod: !scope.row.cfbm && isSubmit }"
            >
              <el-option
                v-for="(item, index) in scope.row.cfs"
                :key="index"
                :label="item.sscfmc ? item.sscfmc : item.cfbhmc"
                :value="item.sscfbh ? item.sscfbh : item.cfbh"
              ></el-option>
            </el-select>
            <el-select
              v-else
              v-model="scope.row.cfbm"
              filterable
              :disabled="isView"
              @change="
                (val) => {
                  ccddChange(val, scope.row);
                }
              "
              clearable
              :class="{ redbod: !scope.row.cfbm && isSubmit }"
            >
              <el-option
                v-for="(item, index) in scope.row.cfs"
                :key="index"
                :label="item.cfmc"
                :value="item.cfbh"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="pzmc"
          align="center"
          label="品种"
          show-overflow-tooltip
          label-class-name="require_star"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.pzmc }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="lssl"
          align="center"
          label="数量"
          label-class-name="require_star"
        >
          <template slot-scope="scope">
            <el-form-item
              v-if="$route.query.jylx == 0"
              :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>
            <el-form-item
              v-else
              :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
          v-if="$route.query.jylx == 1"
          prop="scnd"
          align="center"
          label="生产年度"
          label-class-name="require_star"
        >
          <template slot-scope="scope" class="cell">
            <span>{{ scope.row.scnd }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="$route.query.jylx == 1"
          align="center"
          :label="item"
          v-for="(item, index) in qtypes[type]"
          :key="index"
        >
          <!-- <template slot-scope="scope">{{ scope.row[qnames(item)] }}</template> -->
          <template slot-scope="scope">
            <el-input
              v-model="scope.row[qnames(item)]"
              :disabled="isView"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column
          v-if="$route.query.jylx == 1"
          prop="thqx"
          align="center"
          label="提货期限"
          width="140"
        >
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.thqx"
              type="date"
              value-format="yyyy-MM-dd"
              :disabled="isView"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="90" v-if="!isView">
          <template slot-scope="scope">
            <!-- <el-tooltip class="item" effect="light" content="删除" placement="top"> -->
            <el-button
              @click="handleDelRow(scope.$index)"
              type="text"
              size="small"
              >删除</el-button
            >
            <!-- class="operate_delete_btn iconfont iconshanchu" -->
            <!-- </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-form :model="detailForm">
      <el-row v-if="isConfirm">
        <el-form-item label="接受委托" label-width="150px" required>
          <el-radio-group v-model="detailForm.hyshjg" disabled 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 v-if="isConfirm">
        <el-form-item
          label="意见"
          label-width="150px"
          required
          class="textarea"
        >
          <el-input
            v-model="detailForm.hyyj"
            disabled
            :autosize="{ minRows: 3 }"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-row>
    </el-form>
    <el-row class="footer_btn">
      <el-button
        v-if="isConfirm"
        @click="handleConfirmAndSubmit"
        class="iconfont iconbaocun"
        type="primary"
        size="small"
      >
        保存并发布
        <!--确认并发布-->
      </el-button>
      <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,
} from "@/api/transaction/tradeEntrust/goodsSourceTable/index.js";
import {
  warehouseList,
  warehouseListNew,
  foodStocksListNew,
  organization,
} from "@/api/base";
import { qtypes, getType, qnames } from "@/utils/quality";
import { selectWareDetail } from "@/api/transaction/tradeEntrust/outInDepotPlan/index.js";

export default {
  data() {
    return {
      type: "小麦", // 当前品种类型, 归属qtypes里的
      qtypes: qtypes,
      isSubmit: false,
      planData: {
        showorfalse: true,
        pzbm: "",
        dwbm: "",
        lssl: "",
        scnd: "",
        sfbg: "",
        sf: "",
        remark: "",
        sjlx: 1, // 安排0, 货源1
        wtbm: "",
        ccdd: "",
        rz: "",
        zhaz: "",
        bwsl: "",
        szqw: "",
        thqx: "",
      },
      dform: {
        tableData: [],
      },

      rowData: {},
      companies: [],
      variety: [],
      detailForm: {
        sjlx: 1,
        wtbm: "",
      },
      isAdd: false,
      isView: false,
      isConfirm: false,
      jylx: "",
      cfs: [], // 仓房信息列表
      tipmsg: "保存成功",
    };
  },
  created() {
    // state 0 add 1 update 2 detail 3 confirm
    let { state, wtbm, jylx, wtfbm, wtfmc } = this.$route.query;
    this.wtfbm = wtfbm;
    this.wtfmc = wtfmc;
    this.detailForm.wtbm = wtbm;
    this.detailForm.jylx = jylx;
    this.jylx = jylx;
    this.planData.wtbm = wtbm;
    this.sjlx = 1;
    if (state == 0) {
      this.isAdd = true;
      this.dform.tableData.push({
        ...this.planData,
      });
    }
    this.getDetail(0);
    if (state != 0) this.getDetail(1);
    if (state == 2) {
      this.isView = true;
    } else {
      // this.getCompanies()
      this.getTypes();
    }
    if (state == 3) {
      this.isConfirm = true;
    }
  },
  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();
        }
      }
    },
    ccddChange(val, row) {
      console.log(val, "ccddChange");
      let cur =
        this.$route.query.jylx == 1
          ? row.cfs.filter((item) => item.cfbh == val)[0]
          : row.cfs.filter((item) => item.cfbh == val)[0];
      row.lssl = this.$route.query.jylx == 1 ? cur.lcds : cur.sjcr;
      row.ccdd = this.$route.query.jylx == 1 ? cur.cfbhmc : cur.cfmc;
    },
    async warehouseList(val, item, type, scnd) {
      let da = type ? { sskddm: val, lspzbm: type, lsnd: scnd } : { kddm: val };
      let res = type ? await foodStocksListNew(da) : await warehouseListNew(da);
      this.$set(item, "cfs", res.data);
    },
    qnames(val) {
      return qnames(val);
    },
    handleConfirmAndSubmit() {
      this.detailForm.hybzt = "91000018";
      this.detailForm.hybztmc = "已确认";
      this.update(true);
    },
    handleType(pzmc) {
      this.type = getType(pzmc);
    },
    getDetail(sjlx) {
      if (sjlx == 0) {
        selectWareDetail({
          wtbm: this.detailForm.wtbm,
          sjlx: sjlx, // 货源1, 安排0
          aplx: 0,
        }).then((res) => {
          if (res.infoCode === 200) {
            this.companies = res.data;
          }
        });
      } else {
        detail({
          wtbm: this.detailForm.wtbm,
          sjlx: sjlx, // 货源1, 安排0
          aplx: 1,
        }).then((res) => {
          if (res.infoCode === 200) {
            this.detailForm = res.data.entryAndExitOrderVO;
            this.dform.tableData = res.data.details;
            if (this.$route.query.state == 2 && this.detailForm.hyshjg) {
              this.isConfirm = true;
            }
            this.dform.tableData.map((item) => {
              this.handleCompanyChange(item.dwbm, item, "1");
            });
            if (res.data.details && res.data.details.length) {
              let _type = res.data.details[0].pzmc;
              this.handleType(_type);
            }
          }
        });
      }
    },
    handleSave() {
      this.$refs["dform"].validate((valid) => {
        if (valid) {
          this.detailForm = {
            ...this.detailForm,
            hybzt: "91000001",
            hybztmc: "待提交",
          };
          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.ccdd || !d.pzmc || !d.lssl || !d.scnd
          );
          if (isValid) {
            this.isSubmit = true;
            this.$message.warning("请先完成表格必填项再提交!!");
            return;
          }
          this.tipmsg = "提交成功";
          console.log(this.detailForm);
          this.detailForm = {
            ...this.detailForm,
            wtfbm: this.$route.query.wtfbm,
            url: `/transaction/tradePlan/goodsSourceTable/confirm`,
            itemQuery: JSON.stringify({
              state: "3",
              idKey: "wtbm",
              jyrq: this.$route.query.jyrq,
              lsxzbm: this.$route.query.lsxzbm,
              wtfbm: this.$route.query.wtfbm,
            }),
            itemQueryHaveDone: JSON.stringify({
              state: "2",
              idKey: "wtbm",
              jyrq: this.$route.query.jyrq,
              lsxzbm: this.$route.query.lsxzbm,
              wtfbm: this.$route.query.wtfbm,
            }),
            hybzt: "91000004",
            hybztmc: "已提交",
          };
          if (this.isAdd) {
            this.insert();
            return;
          }
          this.update();
        }
      });
    },
    insert() {
      this.dform.tableData.forEach((item) => {
        item.jylx = this.jylx;
        item.sjlx = 1;
        item.wtfbm = this.wtfbm;
        item.wtfmc = this.wtfmc;
      });
      insert({
        details: this.dform.tableData,
        entryAndExitOrderVO: { ...this.detailForm },
        aplx: 1,
      }).then((res) => {
        if (res.infoCode === 200) {
          this.$message.success(this.tipmsg);
          this.$router.push("index");
          return;
        }
        this.$message.error(res.msg);
      });
    },
    update(isPublish = false) {
      this.dform.tableData.forEach((item) => {
        item.jylx = this.jylx;
        item.sjlx = 1;
        item.wtfbm = this.wtfbm;
        item.wtfmc = this.wtfmc;
      });
      update({
        details: this.dform.tableData,
        entryAndExitOrderVO: { ...this.detailForm },
        aplx: 1,
      }).then((res) => {
        if (res.infoCode === 200) {
          this.$message.success(this.tipmsg);
          if (isPublish) {
            this.$router.push({
              path: "publish",
              query: {
                wtbm: this.detailForm.wtbm,
                jylx: this.detailForm.jylx,
              },
            });
            return;
          }
          this.$router.push("index");
          return;
        }
        this.$message.error(res.msg);
      });
    },
    handleBillChange(val, index) {
      this.dform.tableData[index].sf = val == 0 ? "是" : "否";
    },
    handleCompanyChange(val, item, flag) {
      let cur = this.companies.filter((item1) => item1.dwbm == val)[0];
      if (!flag) {
        cur.lssl = "";
        item = Object.assign(item, cur);
        let _type = cur.pzmc;
        this.handleType(_type);
      }

      if (this.$route.query.jylx == 1) {
        this.warehouseList(item.dwbm, item, item.pzbm, item.scnd);
      } else {
        this.warehouseList(item.dwbm, item);
      }
    },
    handleVarietyChange(val, index) {
      let cur = this.variety.filter((item) => item.dictName == val)[0];
      this.dform.tableData[index].pzbm = cur.dictCode;
    },
    handleAddRow() {
      this.dform.tableData.push({
        ...this.planData,
      });
    },
    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: 100%;
  padding: 20px 0;
  .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>
