<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">保存数据
        </el-button>
        <el-dropdown style="padding: 0 6px;line-height: 0">
          <el-button type="primary" size="small" :loading="subLoading" :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" v-loading="subLoading">
      <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" @row-save="rowSave" @row-update="addUpdate">
          <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="excelBox = true">导入
            </el-button>
          </template>
          <template slot="headerSerial">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click.stop="addRow"
              :disabled="detailData.status == 1" circle></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="storageInQuantityForm" slot-scope="{ row }">
            <el-input-number size="small" v-model="row.storageInQuantity" @change="calculateChange(row)"
              :controls="false" style="width:100%" placeholder="请输入"></el-input-number>
          </template>
          <template slot="priceForm" slot-scope="{ row }">
            <el-input-number size="small" v-model="row.price" @change="calculateChange(row)" :controls="false"
              style="width:100%" placeholder="请输入"></el-input-number>
          </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 style="display:flex;flex-direction: column;justify-content: center;margin-left: 10px;">
                <el-tooltip effect="dark" content="向上移动" placement="top">
                  <i v-if="index != 0" :disabled="detailData.status == 1" class="el-icon-arrow-up"
                    @click="moveUp(row, index)" style="color:#409EFF;"></i>
                </el-tooltip>
                <el-tooltip effect="dark" content="向下移动" placement="bottom"> <i v-if="index != (itemsVOList.length - 1)"
                    :disabled="detailData.status == 1" class="el-icon-arrow-down" @click="moveDown(row, index)"
                    style="color:#409EFF;"></i></el-tooltip>
              </div>
            </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="'C'"
        :inCropId="true" :tabShow="3" @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>
    <el-dialog title="导入" append-to-body :close-on-click-modal="false" :visible.sync="excelBox" width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter" :upload-error="uploadError">
        <template slot="excelTemplate">
          <el-button type="primary" @click="getTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
      <p style="text-align: center;color: #DC0505">
        温馨提示 第一次导入时请先下载模板
      </p>
    </el-dialog>
  </div>
</template>

<script>
import { detail, submit, checkWarehousing, getStoragetree, getStorage, getAllgoods, delItem } 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";
import { contrastObj, contrastList } from "@/util/contrastData";
export default {
  name: "detailsPageEdit",
  data() {
    return {
      subLoading: false,
      buttonLoading: false,
      form: {},
      excelBox: false,
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }, {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/trade-purchase/woodHarvestingCloud/import"
          }
        ]
      },
      excelForm: {},
      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: [],
      pageLoading: false,
      batchNo: '',
      storagetreeList: [],
      oldform: {},
      olditemsVOList: [],
      oldorderFeesList: [],
      oldorderFilesList: [],
    };
  },
  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(189),
      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;
    });
  },
  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) {
      console.log(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, unit: '1' });
          this.getStorage()
        } else {
          return false;
        }
      });

    },
    rowCell(row, index) {
      this.$refs.crud.rowCell(row, index)
    },
    rowSave(form, done) {
      done()
    },
    addUpdate(form, index, done, loading) {
      done()
    },
    rowDel(row) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id) {
          delItem({ itemId: row.id }).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.itemsVOList.splice(row.$index, 1);
          });
        } else {
          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.oldform = this.deepClone(res.data.data);
          this.olditemsVOList = this.deepClone(res.data.data.itemsVOList);
          this.oldorderFeesList = this.deepClone(res.data.data.orderFeesList);
          this.oldorderFilesList = this.deepClone(res.data.data.orderFilesList);
          this.getStorage()
        })
        .finally(() => {
          this.pageLoading = false;
        });
    },
    rowPrint(row) {
      this.$router.push(`/myiframe/urlPath?name=preview-木材管理-入库垛卡.ureport.xml&src=${this.website.reportUrl}/preview?_u=blade-木材管理-入库垛卡.ureport.xml&id=${row.id}`);
    },
    //修改提交触发
    editCustomer(status) {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          for (let i = 0; i < this.itemsVOList.length; i++) {
            if (this.itemsVOList[i].$cellEdit) {
              return this.$message.error('请保存明细')
            }
          }
          let orderFeesList = this.$refs.feeInfo.submitData();
          this.subLoading = true;
          this.buttonLoading = false;
          let data = {
            ...this.form,
            billType: 'RK',
            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.oldform = this.deepClone(res.data.data);
            this.olditemsVOList = this.deepClone(res.data.data.itemsVOList);
            this.oldorderFeesList = this.deepClone(res.data.data.orderFeesList);
            this.oldorderFilesList = this.deepClone(res.data.data.orderFilesList);
            this.$message({
              type: "success",
              message: "保存成功!"
            });
            if (status == "goBack") {
              this.$emit("goBack");
            }
          })
            .finally(() => {
              this.subLoading = false;
              this.buttonLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    //请核
    auditCheck() {
      let orderFeesList = this.$refs.feeInfo.submitData();
      if (orderFeesList.length == 0) {
        this.$confirm("没有应付费用,是否继续提交?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.$confirm("确定审核此订单?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.buttonLoading = true
            const data = {
              id: this.form.id,
              checkType: 'RK',
              url: '/purchasingManagement/inStock/index',
              pageStatus: "this.$store.getters.entranceXsStatus",
              pageLabel: "入库管理",
              checkFlag: 1,
            }
            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: 'RK',
            url: '/purchasingManagement/inStock/index',
            pageStatus: "this.$store.getters.entranceXsStatus",
            pageLabel: "入库管理",
            checkFlag: 1,
          }
          checkWarehousing(data).then(res => {
            if (res.data.success) {
              this.$message.success("操作成功!")
              this.viewDisabled = true
              this.approverDisabled = true
            }
          })
        }).finally(() => {
          this.buttonLoading = false
        })
      }


    },
    calculateChange(row) {
      row.storageAmount = (row.storageInQuantity ? row.storageInQuantity : 0) * (row.price ? row.price : 0)
    },
    beforeFinance(feesData, callback) {
      let params = {}
      //暂时默认通过  之后优化
      params.valid = true
      params.parentId = this.form.id
      callback(params)
    },
    getTemplate() {
      window.open(`/api/trade-purchase/woodHarvestingCloud/export-template?${this.website.tokenHeader}=${getToken()}`)
    },
    uploadAfter(res, done, loading, column) {
      if (!res.message){
        res.forEach(item => this.itemsVOList.push({
          ...item,
          $cellEdit: true
        }))
        this.excelBox = false
        done();
      }else {
        loading()
      }
    },
    //返回列表
    backToList() {
      let orderFeesList = this.$refs.feeInfo.submitData();
      if (
        contrastObj(this.form, this.oldform) ||
        contrastList(this.itemsVOList, this.olditemsVOList) ||
        contrastList(orderFeesList, this.oldorderFeesList) ||
        contrastList(this.orderFilesList, this.oldorderFilesList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.editCustomer("goBack");
          })
          .catch(() => {
            this.$emit("goBack");
          });
      } else {
        this.$emit("goBack");
      }
    },
    openEdit() {
      this.detailData.status = 2;
      this.option.disabled = false;
      this.$refs.crud.refreshTable();
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(189),
        this.tableOption
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    moveUp(row, index) {
      this.itemsVOList[index] = this.itemsVOList.splice(index - 1, 1, row)[0]
    },
    moveDown(row, index) {
      this.itemsVOList[index] = this.itemsVOList.splice(index + 1, 1, row)[0]
    },
    async resetColumn() {
      this.tableOption = tableOption;
      const inSave = await this.delColumnData(
        this.getColumnName(189),
        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>
