<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="info" @click="getData" size="small">刷新资料
        </el-button>
        <el-button type="primary" size="small" :disabled="form.status>0"
          class="el-button--small-yh " @click.stop="openEdit">编辑
        </el-button>
        <el-button type="primary" @click="editCustomer" :loading="subLoading" v-if="detailData.status != 3"
          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 v-if="roleName=='admin'" :disabled="form.status!=5" @click.native="revokeCheck">撤销审核
            </el-dropdown-item>
            <el-dropdown-item :disabled="form.status<3" @click.native="checkScheduleDialog = true">审核进度
            </el-dropdown-item>
            <el-dropdown-item v-if="$route.query.check" :disabled="form.status<3" @click.native="check">审批数据
            </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
              :props="{ checkStrictly: true, emitPath: false, label: 'title' }" clearable @change="storagetreeChange">
            </el-cascader>
          </template>
          <template slot-scope="{column}" slot="storageIdLabel">
            <span style="color: #409EFF;cursor: pointer" @click.stop="addData('storage')">{{column.label}}</span>
          </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="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>
            </div>
          </template>
          <template slot="storageIdHeader" slot-scope="{column}">
            <span style="color: #409EFF;cursor: pointer" @click.stop="addData(column.prop)">{{column.label}}</span>
          </template>
          <template slot="itemIdHeader" slot-scope="{column}">
            <span style="color: #409EFF;cursor: pointer" @click.stop="addData(column.prop)">{{column.label}}</span>
          </template>
          <template slot="inventoryForm" slot-scope="{ row,disabled }">
            <el-input-number size="small" v-model="row.inventory" @change="calculateChange(row)" :controls="false"
              style="width:100%" placeholder="请输入"></el-input-number>
          </template>
        </avue-crud>
      </trade-card>
      <containerTitle title="上传附件"></containerTitle>
      <c-upload typeUpload="CD" deleteUrl="/api/trade-purchase/woodHarvestingCloud/removeByFileId"
        :data="orderFilesList" display :enumerationValue="85.6" :disabled="detailData.status == 1"></c-upload>

      <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>
      <el-dialog append-to-body title="审批" class="el-dialogDeep" :visible.sync="checkDialog" width="50%"
        :close-on-click-modal="false" :destroy-on-close="true" :close-on-press-escape="false" v-dialog-drag>
        <check :checkData="checkData" :checkDetail="false" :idList="[]" @choceCheckFun="choceCheckFun">
        </check>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { detail, submit, checkWarehousing, getStoragetree, getStorage, getAllgoods, revokeWarehousing, 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 { getCurrentDate } from "@/util/date";
import { getToken } from "@/util/auth";
import { number } from "echarts";
import check from "@/components/check/check";
export default {
  name: "detailsPageEdit",
  data() {
    return {
      checkData: {},
      checkDialog: false,
      form: {},
      checkScheduleDialog: false,
      tableOption: {},
      option: {
        disabled: false,
        menuBtn: false,
        labelWidth: 100,
        column: [
          {
            label: "盘点日期",
            prop: "stockTime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm",
            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: "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: [],
      orderFilesList: [],
      subLoading: false,
      pageLoading: false,
      batchNo: '',
      storagetreeList: [],
      roleName: localStorage.getItem("roleName")
    };
  },
  props: {
    detailData: {
      type: Object
    }
  },
  components: {
    feeInfo,
    checkSchedule,
    uploadFile,
    check
  },
  async created() {
    if (this.detailData.status == 1) {
      this.option.disabled = true;
    }
    if (this.detailData.id) {
      this.getDetail(this.detailData.id);
    }
    if (this.detailData.generateId) {
      this.getGenerate(this.detailData.generateId);
    }
    this.tableOption = await this.getColumnData(
      this.getColumnName(197),
      tableOption
    );
    getStoragetree().then(res => {
      this.storagetreeList = res.data.data;
    })
    this.getWorkDicts("financing_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;
    });
    this.getAllWorkDicts()
  },
  methods: {
    check() {
      this.checkData = this.$route.query.check
      this.checkDialog = true
    },
    //关闭审核
    choceCheckFun() {
      this.checkDialog = false;
    },
    getData() {
      getAllgoods().then(res => {
        this.findObject(this.tableOption.column, "itemId").dicData =
          res.data.data;
      })
      getStoragetree().then(res => {
        this.storagetreeList = res.data.data;
      })
      this.getStorage()
    },
    getAllWorkDicts() {
      getAllgoods().then(res => {
        this.findObject(this.tableOption.column, "itemId").dicData =
          res.data.data;
      })
    },
    cellStyle() {
      return "padding:0;height:40px;";
    },
    calculateChange(row) {
      row.balanceMoney = (Number(row.price?row.price:0) * Number(row.inventory?row.inventory:0)).toFixed(2)
      row.surplusLoss = (Number(row.inventory ? row.inventory : 0) - Number(row.storageInQuantity ? row.storageInQuantity : 0)).toFixed(2)
    },
    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(() => {
        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.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.stockTime
          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.stockTime = getCurrentDate()
          res.data.data.itemsVOList.forEach(e => {
            e.surplusLoss = (Number(e.inventory ? e.inventory : 0) - Number(e.storageInQuantity ? e.storageInQuantity : 0)).toFixed(2)
            e.srcItemId = e.id
            delete e.id
          })
          this.form = res.data.data;
          this.itemsVOList = res.data.data.itemsVOList.filter(item => item.isIssue == 3);
          this.getStorage()
        })
        .finally(() => {
          this.pageLoading = false;
        });
    },
    //修改提交触发
    editCustomer(status) {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          this.itemsVOList.forEach((e, index) => {
            e.sort = Number(index) + 1
          })
          this.subLoading = true;
          let data = {
            ...this.form,
            billType: 'PD',
            itemsVOList: this.itemsVOList,
            orderFilesList: this.orderFilesList
          };
          delete data.orderFeesList
          submit(data).then(res => {
            this.form = res.data.data;
            this.itemsVOList = res.data.data.itemsVOList;
            this.orderFilesList = res.data.data.orderFilesList;
            this.$message({
              type: "success",
              message: "保存成功!"
            });
          })
            .finally(() => {
              this.subLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    //请核
    auditCheck() {
      this.$confirm("确定审核此订单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.subLoading = true
        const data = {
          id: this.form.id,
          checkType: 'PD',
          url: '/InventoryManagement/inventory/index',
          pageStatus: "this.$store.getters.entranceXsStatus",
          pageLabel: "库内盘点",
          checkFlag: 3,
        }
        checkWarehousing(data).then(res => {
          if (res.data.success) {
            this.$message.success("操作成功!")
          }
        }).finally(() => {
          this.subLoading = false
          this.getDetail(this.form.id)
        })
      })
    },
    revokeCheck() {
      this.$confirm("确定撤销审核此订单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.subLoading = true;
        let data = {
          ...this.form,
          billType: 'PD',
          itemsVOList: this.itemsVOList,
          orderFilesList: this.orderFilesList
        };
        revokeWarehousing(data).then(res => {
          if (res.data.success) {
            this.$message.success("操作成功!")
          }
        }).finally(() => {
          this.subLoading = false
          this.getDetail(this.form.id)
        })
      })
    },
    addData(row) {
      console.log(row)
      if (row == 'purchaserId') {
        this.$router.push(`/basicData/customerInformation/index`);
      } else if (row == 'corpId') {
        this.$router.push(`/basicData/customerManagement/supplierMaterial/index`);
      } else if (row == 'storage') {
        this.$router.push(`/basicData/basicStorageType/index`);
      } else if (row == 'storageId') {
        this.$router.push(`/basicData/basicStorageDesc/index`);
      } else if (row == 'itemId') {
        this.$router.push(`/basicData/commodityType/index`);
      }
    },
    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();
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(197),
        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(197),
        tableOption
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.getAllWorkDicts()
        this.getStorage()
        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;
}

::v-deep .el-table .cell {
  padding: 0 2px !important;
}

::v-deep .avue-crud .el-table .el-form-item__label {
  left: -1px;
}
</style>
