<template>
  <div class="c-purchase-form">
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="申请人">
        <el-input v-model="form.applyer" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="申请时间">
        <el-input v-if="step !== 'addOutbound' && step !== 'modifyapply'" v-model="form.applyTime"
                  :disabled="canNotEdit">>
        </el-input>
        <!-- <el-date-picker v-else type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"
                        v-model="form.applytime" style="width: 100%;"></el-date-picker> -->
      </el-form-item>
      <el-form-item label="领料单号">
        <el-input v-model="form.deliveryId" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="所在仓库">
        <el-input v-model="form.storageId" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="出库类型">
        <el-input v-model="form.ckType" :disabled="true"></el-input>
<!--        <el-select v-model="form.ckType" placeholder="请选择出库类型" :disabled="canNotEdit">-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.outbound_type"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          ></el-option>-->
<!--        </el-select>-->
      </el-form-item>
      <el-form-item label="物料列表">
        <el-table
          :data="form.itemList"
          stripe
          :key="keys"
          style="width: 160%"
          :summary-method="getSummaries"
          show-summary>
          <el-table-column
            prop="goodsId"
            label="物料编号"
            width="120"
            align="center">
          </el-table-column>
          <el-table-column
            prop="goodsName"
            label="物料名称"
            width="100"
            align="center">
          </el-table-column>
          <el-table-column
            prop="shelvesNum"
            label="出库数量"
            width="240"
            align="center"> <!-- 增加列宽度 -->
            <template slot-scope="scope">
              <div v-if="!scope.row.edit">
                {{ scope.row.shelvesNum }}
                <!-- 只有当 taskName 是 '处理待办' 时才显示修改按钮 -->
                <el-button size="mini" @click="activateEdit(scope.row)" v-if="taskName === '处理待办'">修改</el-button>
              </div>
              <div v-else style="display: flex; align-items: center; justify-content: space-between;">
                <el-input
                  size="small"
                  v-model="scope.row.shelvesNum"
                  :disabled="taskName !== '处理待办'"
                  style="flex: 1;">
                </el-input>
                <!-- 确保 taskName 是 '处理待办' 且 scope.row.edit 为 true 时，显示保存和取消按钮 -->
                <el-button size="mini" @click="confirmEdit(scope.row)" v-if="taskName === '处理待办' && scope.row.edit">保存</el-button>
                <el-button size="mini" @click="cancelEdit(scope.row)" v-if="taskName === '处理待办' && scope.row.edit">取消</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="recoil"
            label="物料描述"
            align="center">
          </el-table-column>
          <el-table-column
            prop="price"
            label="价格"
            align="center">
          </el-table-column>
          <el-table-column
            prop="originalShelvesNum"
            label="需求数量"
            align="center">
          </el-table-column>
          <el-table-column
            prop="total"
            label="库存数量"
            align="center">
          </el-table-column>
          <el-table-column
            prop="goodsTo"
            label="物资流向"
            width="100"
            align="center">
          </el-table-column>
          <el-table-column
            prop="specification"
            label="规格型号"
            width="100"
            align="center">
          </el-table-column>
          <el-table-column
            prop="unit"
            label="单位"
            width="50"
            align="center">
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            width="50">
          </el-table-column>
        </el-table>
      </el-form-item>

      <template v-if="step === 'deptmanager' || step === 'managerName'  || step === 'crossDeptManager'">
        <el-form-item label="审批结果">
          <el-radio-group v-model="form.result">
            <el-radio label="true">同意</el-radio>
            <el-radio label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input type="textarea" v-model="form.comment"></el-input>
        </el-form-item>
      </template>
      <template v-if="step == 'addOutbound'">
        <el-form-item label="拒绝原因">
          <el-input type="textarea" v-model="form.comment" placeholder="请输入拒绝原因"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="reject">关闭流程</el-button>
          <!--              <el-button type="danger" @click="cancel">撤销</el-button>-->
        </el-form-item>
      </template>
      <template v-if="step === 'deptmanager' || step === 'managerName'  || step === 'crossDeptManager'">
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>
      </template>
      <template v-if="step==='modifyapply'">
        <el-form-item label="是否重新申请">
          <el-radio-group v-model="form.reapply">
            <el-radio label="true">是</el-radio>
            <el-radio label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>
      </template>
    </el-form>
    <el-dialog
      title="确认修改"
      :visible.sync="showConfirmDialog"
      width="30%"
      @close="showConfirmDialog = false">
      <span>修改后会影响需求数量，是否继续？</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="showConfirmDialog = false">取消</el-button>
    <el-button type="primary" @click="handleSave">确定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>


import {addOutbound, updateOutbound} from "@/views/function/api/outbound";
import {updateOrderdetail} from "@/api/system/orderdetail";

const keyMap = {
  addOutbound: "addOutbound",
  deptmanager: "approve",
  managerName: "agree",
  crossDeptManager: "crossAgree",
  // 请假流程中拒绝过程,回到申请人进行修改
  modifyapply: "modifyapply",
};
export default {
  dicts: ['outbound_type'],
  props: {
    step: {
      type: String,
      default: ""
    },
    formInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        result: "true",
        applyer: "",
        applyTime: "",
        itemList: [],
        ckType: "",
        comment: "",
        reapply: "true",
        deliveryId: "",
      },
      keys:0,
      ckType: "",
      id:0,
      showConfirmDialog: false,
      currentEditingRow: null,
      taskName:''
    };
  },
  watch: {
    formInfo(newFormValue) {
      this.form.applyer = newFormValue.applyer;
      this.form.applyTime = newFormValue.applyTime;
      // this.form.storageId = newFormValue.storageId;
      let items = JSON.parse(newFormValue.itemList);
      for (let i in items) {
        this.form.itemList.push(items[i]);
      }
      const types = this.dict.type.outbound_type.filter(item => item.value = newFormValue.ckType)
      if(types.length > 0) {
        this.form.ckType = types[0].label;
      }
      this.form.deliveryId = newFormValue.deliveryId;
      this.form.comment = newFormValue.comment;
      // 假设 form.itemList 是你加载的数据数组
      this.form.storageId = '';
      this.form.itemList.forEach(item => {
        item.originalShelvesNum = item.shelvesNum; // 在加载数据时保存原始值
        item.edit = false
        if(this.form.storageId == ''){
          this.form.storageId = item.storageShortName
        }
      });
      console.log(this.form.itemList,'看看数据')
    }
  },
  computed: {
    canNotEdit() {
      return this.step !== "addOutbound" && this.step !== "modifyapply";
    }
  },

  mounted() {
    // 获取通过params传递的row对象
    const rowData = this.$route.params.row;
    console.log('Row Data:', rowData);

    // 获取通过query传递的id
    const idFromQuery = this.$route.query.id;
    this.id = this.$route.query.id;

    // 获取其他查询参数
    const isAll = this.$route.query.isAll;
    this.taskName = this.$route.query.taskName;
    console.log('Is All:', isAll);
  },

  methods: {
    onSubmit() {
      const params = {
        ...this.form
      };
      if (this.step !== "modifyapply") {
        params[keyMap[this.step]] = this.form.result;
      }
      this.$emit("submit", params)
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      const uniqueGoodsIds = new Set(data.map(row => row.goodsId)); // 使用 Set 来存储唯一的 goodsId
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
        } else if (column.property === 'shelvesNum') {
          const total = data.reduce((acc, row) => acc + parseFloat(row.shelvesNum), 0);
          sums[index] = total;
        } else if (column.property === 'price') {
          const total = data.reduce((acc, row) => acc + parseFloat(row.shelvesNum * row.price), 0);
          if(isNaN(total)){
            sums[index] = '-';
          }else{
            sums[index] = total
          }

        }  else if (column.property === 'goodsId') {
          sums[index] = uniqueGoodsIds.size; // 将 goodsId 列的总计设置为唯一 goodsId 的数量
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    reject() {
      var data = "";
      // if(this.step == "deptmanager"){
      //   data = "startOutbound";
      // }else if(this.step == "managerName"){
      //   data = "sid-36006ACD-7D4E-4B39-ABAD-68368747EEFB";
      // }
      console.log("comment:", this.form)
      console.log("comment:", this.step)
      if (this.form.comment == "" || this.form.comment == undefined) {
        this.$modal.msgError("请说明拒绝原因！");
        return;
      }
      const params = {
        rejectReason: this.form.comment,
        sid: "startOutbound"
      };

      this.$emit("reject", params)
    },
    cancel() {
      this.$emit("cancel")
    },

    activateEdit(row) {
      this.$set(row, 'edit', true);
      this.keys ++
      console.log(row,"修改了")
    },
    cancelEdit(row) {
      this.$set(row, 'edit', false);
      this.keys ++
    },

    handleSave() {
      // Serialize the itemList to a JSON string
      let serializedItemList = JSON.stringify(this.form.itemList);

      // First update the outbound details
      updateOutbound({id: this.id, itemList: serializedItemList}).then(res => {
        this.$message.success("修改成功!");

        // Upon successful update, proceed to update order details
        updateOrderdetail({id: this.currentEditingRow.id, shelvesNum: this.currentEditingRow.shelvesNum}).then(response => {
          this.$message.success("订单详情更新成功!");
        }).catch(error => {
          this.$message.error("订单详情更新失败: " + error.message);
        });

        // Reset editing state and close the dialog
        this.$set(this.currentEditingRow, 'edit', false);
        this.showConfirmDialog = false;
      }).catch(error => {
        this.$message.error("修改失败: " + error.message);
      });
    },

    confirmEdit(row) {
      if (parseInt(row.shelvesNum) > parseInt(row.total)) {
        this.$message.error("出库数量不能大于库存数量");
        return;
      }
      this.showConfirmDialog = true;
      this.$set(row, 'edit', false);
      this.keys ++
      this.currentEditingRow = row;
    },
  }
};
</script>

<style scoped>
.goodsList {
  overflow: auto;
  resize: none; /* 防止用户调整textarea大小 */
  /*width: 300px; !* 设置一个宽度 *!*/
  /*height: 150px; !* 设置一个高度 *!*/
}

.el-table {
  border: 0px !important;
}

</style>
