<template>
  <div class="borderless" v-loading="pageLoading">
    <div class="customer-head">
      <div class="customer-back">
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
          @click="backToList">返回列表
        </el-button>
      </div>
      <div class="add-customer-btn">
        <el-button type="primary" size="small" :disabled="form.status>0" v-if="detailData.status == 1"
          class="el-button--small-yh " @click.stop="openEdit">编辑
        </el-button>
        <el-button type="primary" @click="editCustomer" :loading="subLoading" v-if="detailData.status != 1"
          size="small">{{ form.id ? '修改数据' : '保存数据' }}
        </el-button>
        <el-dropdown style="padding: 0 6px;line-height: 0">
          <el-button type="primary" size="small" :loading="buttonLoading" :disabled="!form.id">
            审核处理<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :disabled="form.status>0" @click.native="auditCheck">审核数据</el-dropdown-item>
            <el-dropdown-item :disabled="form.status<1" @click.native="checkScheduleDialog = true">审核进度
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="customer-main">
      <trade-card title="基础信息">
        <avue-form ref="form" class="trading-form" v-model="form" :option="option">
          <template slot="purchaserId">
            <crop-select v-model="form.purchaserId" corpType="KH" :refresh="false" @getCorpData="getKHData"
              :disabled="detailData.status == 1"></crop-select>
          </template>
          <template slot="corpId">
            <crop-select v-model="form.corpId" corpType="GYS" :refresh="false" @getCorpData="getGYSData"
              :disabled="detailData.status == 1"></crop-select>
          </template>
          <template slot="storageId">
            <el-cascader v-model="form.storageId" :options="storagetreeList" :show-all-levels="false"
              :disabled="detailData.status == 1" :props="{ checkStrictly: true, emitPath: false, label: 'title' }"
              clearable @change="storagetreeChange">
            </el-cascader>
          </template>
        </avue-form>
      </trade-card>
      <trade-card title="出库明细">
        <avue-crud ref="crud" :data="itemsVOList" :option="tableOption" @row-del="rowDel" @saveColumn="saveColumn"
          @resetColumn="resetColumn" :cell-style="cellStyle">
          <template slot="menuLeft">
            <el-button type="primary" icon="el-icon-plus" size="small" :disabled="detailData.status == 1"
              @click.stop="addRow">录入明细
            </el-button>
            <el-button type="success" icon="el-icon-bottom" size="small" @click.stop="getTemplate">下载模板
            </el-button>
            <el-button type="info" icon="el-icon-top" size="small" :disabled="detailData.status == 1"
              @click.stop="addRow">导入
            </el-button>
            <el-button type="info" icon="el-icon-printer" size="small" @click.stop="openReport()">报表打印</el-button>
          </template>
          <template slot="oneCode" slot-scope="{ row, index }">
            <el-popover placement="right" width="160" trigger="click">
              <el-image style="width: 160px; height: 80px" :src="row.oneCode" :fit="fit"></el-image>
              <el-button v-if="row.oneCode" type="text" slot="reference">查看</el-button>
            </el-popover>
          </template>
          <template slot="qrCode" slot-scope="{ row, index }">
            <el-popover placement="right" width="300" trigger="click">
              <el-image style="width: 300px; height: 300px" :src="row.qrCode" :fit="fit"></el-image>
              <el-button v-if="row.qrCode" type="text" slot="reference">查看</el-button>
            </el-popover>
          </template>
          <template slot="menu" slot-scope="{ row, index }">
            <div style="display:flex;justify-content: center;">
              <el-button size="small" icon="el-icon-edit" type="text" @click="rowCell(row, index)"
                :disabled="disabled || detailData.status == 1">{{ row.$cellEdit ? "保存" : "修改" }}</el-button>
              <el-button size="small" icon="el-icon-delete" type="text" @click="rowDel(row, index)"
                :disabled="detailData.status == 1">删除</el-button>
                <!-- <el-button size="small" icon="el-icon-printer" type="text" @click="rowPrint(row, index)" :disabled="!row.id">
                打印</el-button> -->
            </div>
          </template>
        </avue-crud>
      </trade-card>
      <fee-info ref="feeInfo" :orderFeesList="orderFeesList" :disabled="detailData.status == 1"
        feeUrl="/blade-purchase-sales/entranceOrder/removeOrderFees" :optionType="'CMY'" :itemType="'D'"
        :inCropId="true" :tabShow="2" @beforeFinance="beforeFinance" :delType="2" :billingShow="false" />
      <upload-file ref="uploadFile" title="合同附件" :disabled="detailData.status == 1" :orderFilesList="orderFilesList"
        delUrl="" />
      <el-dialog append-to-body title="审批进度" class="el-dialogDeep" :visible.sync="checkScheduleDialog" width="40%"
        :close-on-click-modal="false" :destroy-on-close="true" :close-on-press-escape="false" v-dialog-drag>
        <check-schedule :checkId="form.id" :batchNo="batchNo" @choceScheduleFun="choceScheduleFun">
        </check-schedule>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { detail, submit, checkWarehousing, getStoragetree, getStorage, getAllgoods, financingExcess } from "@/api/purchasingManagement/inStock";
import tableOption from "./config/customerContact.json";
import feeInfo from "@/components/fee-info/main";
import checkSchedule from "../../../components/check/checkSchedule";
import uploadFile from "@/components/upload-file/main";
import { getToken } from "@/util/auth";
export default {
  name: "detailsPageEdit",
  data() {
    return {
      form: {},
      checkScheduleDialog: false,
      tableOption: {},
      option: {
        disabled: false,
        menuBtn: false,
        labelWidth: 100,
        column: [
          {
            label: "货权人",
            prop: "purchaserId",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 6
          },

          {
            label: "出库日期",
            prop: "stockTime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 6
          },
          {
            label: "仓库",
            prop: "storageId",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 6
          },
          {
            label: "提单号",
            prop: "billNo",
            span: 6
          },
          {
            label: "业务类型",
            prop: "businessType",
            type: "select",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dicData: [],
            span: 6
          },
          {
            label: "车船号",
            prop: "vehicleShipNumber",
            span: 6
          },
          {
            label: "供应商",
            prop: "corpId",
            span: 6
          },
          {
            label: "出库单号",
            prop: "sysNo",
            disabled: true,
            span: 6
          },
          {
            label: "审核状态",
            prop: "status",
            type: "select",
            dataType: 'number',
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dicData: [],
            disabled: true,
            span: 6
          },
          {
            label: "备注",
            prop: "orderRemark",
            type: "textarea",
            minRows: 2,
            span: 18
          },
        ]
      },
      itemsVOList: [],
      orderFeesList: [],
      orderFilesList: [],
      subLoading: false,
      pageLoading: false,
      batchNo: '',
      storagetreeList: []
    };
  },
  props: {
    detailData: {
      type: Object
    }
  },
  components: {
    feeInfo,
    checkSchedule,
    uploadFile
  },
  async created() {
    if (this.detailData.status == 1) {
      this.option.disabled = true;
    }
    if (this.detailData.id) {
      this.getDetail(this.detailData.id);
    }
    this.tableOption = await this.getColumnData(
      this.getColumnName(191),
      tableOption
    );
    getStoragetree().then(res => {
      this.storagetreeList = res.data.data;
    })
    this.getWorkDicts("approval_status").then(res => {
      this.findObject(this.option.column, "status").dicData =
        res.data.data;
    });
    this.getWorkDicts("CMY_business_type").then(res => {
      this.findObject(this.option.column, "businessType").dicData =
        res.data.data;
    });
    getAllgoods().then(res => {
      this.findObject(this.tableOption.column, "itemId").dicData =
        res.data.data;
    })
    this.getWorkDicts("unit").then(res => {
      this.findObject(this.tableOption.column, "unit").dicData =
        res.data.data;
    });
    if (this.$route.query.generateId) {
      this.getGenerate(this.$route.query.generateId);
    }
  },
  activated() {
    setTimeout(() => {
      if (this.$route.query.generateId) {
        this.getGenerate(this.$route.query.generateId);
      }
    }, 100);
  },
  methods: {
    cellStyle() {
      return "padding:0;height:40px;";
    },
    getStorage() {
      getStorage({ storageTypeId: this.form.storageId }).then(res => {
        this.findObject(this.tableOption.column, "storageId").dicData = res.data;
      })
    },
    storagetreeChange(row) {
      if (row) {
        if (this.itemsVOList.length > 0) {
          this.getStorage()
          this.itemsVOList.forEach(e => {
            e.storageId = null
          })
          this.$message.warning("请重新选择库区!")
        }
      } else {
        if (this.itemsVOList.length > 0) {
          this.findObject(this.tableOption.column, "storageId").dicData = []
          this.itemsVOList.forEach(e => {
            e.storageId = null
          })
          this.$message.warning("请重新选择库区!")
        }

      }
    },
    getKHData(row) {
      this.form.purchaser = row.cname
    },
    getGYSData(row) {
      this.form.corpName = row.cname
    },
    choceScheduleFun() {
      this.checkScheduleDialog = false
    },
    addRow() {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          this.itemsVOList.push({ $cellEdit: true });
          this.getStorage()
        } else {
          return false;
        }
      });

    },
    rowCell(row, index) {
      if (row.$cellEdit == true) {
        this.$set(row, "$cellEdit", false);
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
    rowSave(row) {
      this.$set(row, "$cellEdit", false);
    },
    rowDel(row) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.itemsVOList.splice(row.$index, 1);
      });
    },
    getDetail(id) {
      this.pageLoading = true;
      detail(id)
        .then(res => {
          this.form = res.data.data;
          this.itemsVOList = res.data.data.itemsVOList;
          this.orderFeesList = res.data.data.orderFeesList;
          this.orderFilesList = res.data.data.orderFilesList;
          this.getStorage()
        })
        .finally(() => {
          this.pageLoading = false;
        });
    },
    getGenerate(id) {
      this.pageLoading = true;
      detail(id)
        .then(res => {
          delete res.data.data.id
          delete res.data.data.createTime
          delete res.data.data.createUser
          delete res.data.data.createUserName
          delete res.data.data.sysNo
          delete res.data.data.status
          res.data.data.itemsVOList.forEach(e => {
            delete e.id
          })
          // res.data.data.orderFeesList.forEach(e => {
          //   delete e.id
          // })
          // res.data.data.orderFilesList.forEach(e => {
          //   delete e.id
          // })
          this.form = res.data.data;
          this.itemsVOList = res.data.data.itemsVOList;
          // this.orderFeesList = res.data.data.orderFeesList;
          // this.orderFilesList = res.data.data.orderFilesList;
          this.getStorage()
        })
        .finally(() => {
          this.pageLoading = false;
        });
    },
    //修改提交触发
    editCustomer(status) {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          let orderFeesList = this.$refs.feeInfo.submitData();
          this.subLoading = true;
          let data = {
            ...this.form,
            billType: 'CK',
            itemsVOList: this.itemsVOList,
            orderFeesList: orderFeesList,
            orderFilesList: this.orderFilesList
          };
          submit(data).then(res => {
            this.form = res.data.data;
            this.itemsVOList = res.data.data.itemsVOList;
            this.orderFeesList = res.data.data.orderFeesList;
            this.orderFilesList = res.data.data.orderFilesList;
            this.$message({
              type: "success",
              message: "保存成功!"
            });
          })
            .finally(() => {
              this.subLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    //请核
    auditCheck() {
      financingExcess({ id: this.form.purchaserId }).then(res => {
        if (res.data.data == '操作成功') {
          this.$confirm("确定审核此订单?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.buttonLoading = true
            const data = {
              id: this.form.id,
              checkType: 'CK',
              url: '/salesManagement/outStock/index',
              pageStatus: "this.$store.getters.entranceXsStatus",
              pageLabel: "出库管理",
              checkFlag: 2,
            }
            checkWarehousing(data).then(res => {
              if (res.data.success) {
                this.$message.success("操作成功!")
                this.viewDisabled = true
                this.approverDisabled = true
              }
            })
          }).finally(() => {
            this.buttonLoading = false
          })
        } else {
          this.$confirm("此订单余额不足，是否继续确认提交审核?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.buttonLoading = true
            const data = {
              id: this.form.id,
              checkType: 'CK',
              url: '/salesManagement/outStock/index',
              pageStatus: "this.$store.getters.entranceXsStatus",
              pageLabel: "出库管理",
              checkFlag: 2,
            }
            checkWarehousing(data).then(res => {
              if (res.data.success) {
                this.$message.success("操作成功!")
                this.viewDisabled = true
                this.approverDisabled = true
              }
            })
          }).finally(() => {
            this.buttonLoading = false
          })
        }
      })
    },
    getTemplate() {
      window.open(`/api/trade-purchase/woodHarvestingCloud/export-template?${this.website.tokenHeader}=${getToken()}`)
    },
    //返回列表
    backToList() {
      this.$emit("goBack");
    },
    openEdit() {
      this.detailData.status = 2;
      this.option.disabled = false;
      this.$refs.crud.refreshTable();
    },
    beforeFinance(feesData, callback) {
      let params = {}
      //暂时默认通过  之后优化
      params.valid = true
      params.parentId = this.form.id
      callback(params)
    },
    openReport(){
      this.$router.push(`/myiframe/urlPath?name=preview-木材库-出库单.ureport.xml&src=${this.website.reportUrl}/preview?_u=blade-木材库-出库单.ureport.xml&id=${this.form.id}`);
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(191),
        this.tableOption
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    async resetColumn() {
      this.tableOption = tableOption;
      const inSave = await this.delColumnData(
        this.getColumnName(191),
        tableOption
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$message.success("重置成功");
        //关闭窗口
        setTimeout(() => {
          this.$refs.crud.$refs.dialogColumn.columnBox = false;
        }, 1000);
      }
    }
  },
  watch: {
  }
};
</script>

<style lang="scss" scoped>
.trading-form ::v-deep .el-form-item {
  margin-bottom: 8px !important;
}

::v-deep .el-form-item__error {
  display: none !important;
}

::v-deep .select-component {
  display: flex !important;
}
</style>
