<template>
  <div>
    <el-form :model="formData" :rules="formRules" ref="dataForm" label-width="120px">
      <el-row type="flex" justify="end">
        <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px">
          <el-button type="primary" @click.native="saveOrder('1')" :loading="loading">草稿保存</el-button>
          <el-button type="primary" @click.native="saveOrder('2')" :loading="loading">提交单据</el-button>
        </el-button-group>
      </el-row>

      <el-card style="margin-top: -5px;">
        <el-row>
          <el-col :span="11">
            <el-form-item label="单据编号:" prop="billNo">
              <el-input v-model="formData.billNo" auto-complete="off" :disabled="true" style="width: 90%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="询价发起时间：" prop="createTime">
              <el-date-picker
                :disabled="true"
                v-model="formData.createTime"
                type="datetime"
                placeholder="选择日期"
                style="width: 90%"
                :clearable="false"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="询价截止时间：" prop="validUntil">
              <el-date-picker
                v-model="formData.validUntil"
                type="datetime"
                placeholder="选择日期"
                style="width: 90%"
                :clearable="false"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="期望到货时间：" prop="arrivalTime">
              <el-date-picker
                v-model="formData.arrivalTime"
                type="datetime"
                placeholder="选择日期"
                style="width: 90%"
                :clearable="false"
                value-format="yyyy-MM-dd HH:mm:ss"
                :disabled-date="disabledArrivalDate"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row >
          <el-col :span="11">
            <el-form-item
              prop="fromCorp"
              label="供应商:"
              :rules="{ required: true, type: 'array', message: '请至少选择一个供应商', trigger: 'change' }"
            >
              <el-select
                v-model="formData.fromCorp"
                filterable
                remote
                :disabled="corpOrderIdDisabled"
                clearable
                reserve-keyword
                placeholder="请选择供应商"
                :remote-method="findMethod"
                style="width: 90%"
                multiple
              >
                <el-option
                  v-for="item in fromOptions"
                  :key="item.erpId"
                  :label="item.name"
                  :value="item.erpId"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="说明:" prop="remark">
              <el-input v-model="formData.remark" style="width: 90%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card>
        <el-row type="flex" justify="end">
          <el-button-group style="display: flex">
            <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px">
              <el-button type="primary" @click.native.stop="selectProductFunction()" :loading="loading">产品录入</el-button>
              <!--              <el-button type="primary" :loading="loading" @click.native.stop="selectApply()">选入申购单</el-button>-->
            </el-button-group>
          </el-button-group>
        </el-row>
        <el-table v-loading="loading" :data="codeArray" style="width: 100%;" :row-class-name="tableRowClassName" border
                  highlight-current-row max-height="300" height="300" ref="multipleTable">
          <el-table-column label="序号" type="index" width="60"></el-table-column>
          <el-table-column label="DI/物资编码" prop="nameCode" width="120"></el-table-column>
          <el-table-column label="物资名称" prop="productName"  width="160"></el-table-column>
          <el-table-column label="规格型号" prop="ggxh" ></el-table-column>
          <el-table-column label="注册/备案号" prop="zczbhhzbapzbh"></el-table-column>
          <el-table-column label="生产厂家" prop="productCompany"></el-table-column>


          <el-table-column width="100" label="数量">
            <template slot-scope="scope">
              <el-input size="small" v-model="scope.row.count"
                        placeholder="请输入数量"
                        type='number'
                        :disabled="scope.row.index !== selectedIndex"
                        oninput="value=value.replace(/[^\d]/g,'')"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="期望单价" prop="price"  width="100">
            <template slot-scope="scope">
              <el-input
                size="small"
                v-model="scope.row.price"
                placeholder="请输入期望单价"
                type="text"
                :disabled="scope.row.index !== selectedIndex"
                @input="handleInput(scope.row, $event)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="期望总价" prop="totalPrice"  width="100">
            <template slot-scope="scope">
              <!-- 直接在模板中计算总价 -->
              <span>{{ scope.row.price * scope.row.count | currencyFormatter }}</span>
            </template>
          </el-table-column>
          <el-table-column label="说明" width="300">
            <template slot-scope="scope">
              <el-input
                size="small"
                v-model="scope.row.remark"
                placeholder="请输入说明（最多50个字符）"
                type="text"
                :disabled="scope.row.index !== selectedIndex"
                @input="handleInputChange(scope.row)"
              ></el-input>
              <!-- 使用 v-if 判断是否需要显示 tooltip -->
              <el-tooltip
                class="item-tooltip"
                effect="dark"
                :content="scope.row.remark"
                placement="top"
                trigger="hover"
              >
              <i class="el-icon-info" slot="reference"></i> <!-- tooltip 的触发元素，通常是一个图标 -->
              </el-tooltip>
            </template>
          </el-table-column>

<!--          <el-table-column label="询价附件" prop="attachmentPath"  width="120"></el-table-column>-->

          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" :disabled="scope.row.index === selectedIndex" @click.stop="true"
                         @click.native="rowChange(scope.row)">编辑
              </el-button>
              <el-button type="text" size="small" :disabled="scope.row.index !== selectedIndex" @click.stop="true"
                         @click.native="tableCountChange(scope.row)">保存
              </el-button>
              <el-button type="text" size="small" @click.stop="true"
                         @click.native="deleteCodeArray(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>

    <el-dialog
      title="产品录入"
      :visible.sync="selectProductVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="85%"
      v-if="selectProductVisible"
      :append-to-body='true'
    >
      <purInquiryProducts
        :closeSelDialog="closeDialogC2"
        :purType="1"
        :pId="pId"
        :stockOrderLists="this.stockOrderLists"
      ></purInquiryProducts>
    </el-dialog>

  </div>
</template>

<script>
import draggable from "vuedraggable";
import {getBasicUnitMaintains} from "@/api/basic/basicUnitMaintain";
import {
  inserThrOrderWeb,
  delInquiryItem,
  selectPurInquiryDetail,
  updateItem
} from "@/api/purchase/purInquiryOffer";
import {parseTime} from "@/utils/coTools";
import purInquiryProducts from "@/views/purchase/purInquiryOffer/purInquiryOfferProducts";
import {findInvByUser} from "@/api/system/invSubWarehouse";
import { addPurInquiryId , selectPurInquiryDetail as listItem } from '@/api/purchase/purInquiryOffer'

export default {
  name: "idQuery",
  props: {
    pageType: {
      type: Object,
      required: true,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
    idQuery: {
      type: Object,
      required: true,
    },
    isChang: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      code: "",
      query: {
        orderIdFk: "",
        page: 1,
        limit: 1000,
      },
      fromOptions: [],
      typeList: [
        {name: '战略', code: 1},
        {name: '长期', code: 2},
        {name: '短期', code: 3}
      ],
      statusList: [
        {name: '草稿', code: 1},
        {name: '未审核', code: 2},
        {name: '已审核', code: 3}
      ],
      payTypeList: [
        {name: '银行', code: 1},
        {name: '微信', code: 2},
        {name: '支付宝', code: 3}
      ],
      formData: {
        id: null,
        code: null,
        name: "",
        fromCorp: [],
        remark: "",
        invCode: "",
        contractDate: null,
        status: null,
        type: null,
        startDate: null,
        endDate: null,
        amount: null,
        payAmount: null,
        payType: null,
        payDate: null,
        pageType: null,
      },
      pId: null,
      formRules: {},
      codeArray: [],
      stockOrderLists: [],
      total: 0,
      loading: false,
      index: null,
      formLoading: false,
      formVisible: false,
      deleteLoading: false,
      orderNo: null,
      statusMap: {
        1: "草稿",
        2: "未审核",
        3: "已审核",
      },
      typeMap: {
        1: "预入库",
        2: "普通采购",
      },
      orderEditor: true,
      sOptions: [],
      sValue: [],
      sList: [],
      sLoading: false,
      busTypes: [],
      currentRow: {},
      selectedIndex: "",
      selectProductVisible: false,
      thisData: {},
      storageList: [],
      invCodeList: [],
      invQueryData: {},
      selectApplyVisible: false,
      formattedPrice: '', // 用于显示和编辑的格式化价格
    };
  },

  watch: {
    isChang: function () {
      this.$emit("cancelDialog", this.pId);
    },
  },
  components: {
    draggable,
    purInquiryProducts,
    // SelectApplyListDialog
  },
  methods: {
    handleInputChange(row) {
      // 截断文本至最多50个字符，并存储完整文本到 remarkFull
      if (row.remark.length > 50) {
        row.remark = row.remark.slice(0, 50);
      } else {
      }
    },
    handleInput(row, event) {
      // 使用正则表达式来限制输入为数字和小数点
      const value = event.target.value;
      const cleaned = value.replace(/[^\d.]/g, '').replace(/(\..*?)\..*/g, '$1');
      // 去除开头的0（可选）
      const formatted = cleaned.replace(/^0+(?!\.)/, '');
      // 确保小数点后最多有两位（可选）
      const parts = formatted.split('.');
      parts[1] = parts[1] ? parts[1].slice(0, 2) : '';
      row.price = parts.join('.');

      // 如果需要，将格式化后的值转换为浮点数并更新 price 属性
      // 注意：这应该在失去焦点或用户完成输入后进行，以避免每次按键都触发更新
      if (event.isTrusted && !event.target.checkValidity()) {
        // 如果输入无效（例如，用户粘贴了非数字文本），则不更新 price
        return;
      }
      // 这里只是一个简单的转换，您可能需要根据实际情况进行更复杂的处理
      row.price = parseFloat(row.price.replace(/,/g, '')); // 假设用户不会输入逗号作为千位分隔符
    },
  productListChange() {
      this.getStockOrderDetailList()
    },
    //获取往来单位候选列表
    findMethod(query) {
      this.fromOptions = [];
      let cQuery = {
        key: query,
        corpType: 2,
        outType: null,
        page: 1,
        limit: 20,
      };
      getBasicUnitMaintains(cQuery)
        .then((response) => {
          this.loading = false;
          this.fromOptions = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
        });
    },
    saveOrder(status) {

      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.codeArray.length < 1) {
            this.$message.warning('未添加产品');
            return;
          }
          if (status === '1') {
            if (this.formData.status == 2 || this.formData.status == 3) {
              return this.$message.error("当前单据状态不可以进行草稿保存！");
            }
          }
          if (status === '2') {
            if (this.formData.status == 2 || this.formData.status == 3) {
              return this.$message.error("当前单据状态不可以进行提交审核！");
            }

        }
        if (status == "1") {
          this.submitFunction(status);
        } else {
          let tip = "是否确定提交订单?";
          this.$confirm(tip, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.submitFunction(status);
          }).catch(() => {
            this.loading = false;
          });
        }
      }
    }
)
;
},
disabledArrivalDate(time)
{
  return time.getTime() < new Date(this.formData.createTime).getTime()
}
,
submitFunction(status)
{
  let tMessage = status === '1' ? '保存' : '提交';
  this.loading = true;
  this.formData.id = this.pId;
  this.formData.pageType = this.pageType
  let tQuery = {
    editStatus: status,
    purInquiryEntity: this.formData,
    purInquiryItemEntities: this.codeArray,
    type: 1,
  }
  inserThrOrderWeb(tQuery)
    .then(response => {
      this.loading = false;
      if (response.code === 20000) {
        this.$message.success(tMessage + "成功");
        this.closeDialog(true);
      } else {
        this.$message.error(response.message);
      }
    })
    .catch(() => {
      this.loading = false;
    })
}
,
selectProductFunction()
{
  this.selectProductVisible = true;
  //当父id为空的时候生成id
  if (this.pId == null) {
    addPurInquiryId().then(response => {
      if (response.code === 20000) {
        this.pId = response.data
      }
    }).catch(() => {
      this.loading = false;
    })
  }
  this.stockOrderLists = this.codeArray;
}
,
setDeptCode(obj)
{
  this.formData.deptCode = this.invCodeList.find(item => item.code == obj).parentId;
}
,
closeDialogC2()
{
  this.selectProductVisible = false;
  this.selectApplyVisible = false;
  this.query.orderIdFk = this.pId
  selectPurInquiryDetail(this.query) //查找该单号下的所有条码
    .then((response) => {
      console.log(response)
      this.codeArray = response.data.list || [];
      this.total = response.data.total || 0;
      this.loading = false;
    })
    .catch(() => {
      this.loading = false;
      this.list = [];
      this.total = 0;
    });
}
,
rowChange(val)
{
  if (this.$isNotBlank(this.currentRow)) {
    this.currentRow.totalPrice =  this.currentRow.price * this.currentRow.count
    updateItem(this.currentRow);
    this.selectedIndex = null
  }

  this.currentRow = val;
  this.formattedPrice = val.price;
  this.selectedIndex = val.index;
}
,
tableCountChange(row)
{
  if (this.$isNotBlank(row)) {
    this.currentRow.totalPrice =  this.currentRow.price * this.currentRow.count
    updateItem(this.currentRow);
    this.selectedIndex = null
  }
}
,
tableRowClassName({row, rowIndex})
{
  row.index = rowIndex;
}
,
// 刷新表单
resetForm()
{
  if (this.$refs["dataForm"]) {
    // 清空验证信息表单
    this.$refs["dataForm"].clearValidate();
    // 刷新表单
    this.$refs["dataForm"].resetFields();
    this.getList();
  }
}
,
deleteCodeArray(index, row)
{
  this.detailLoading = true;
  this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    this.$refs.multipleTable.setCurrentRow();
    this.currentRow = {};
    this.selectedIndex = "";
    // console.log(this.orderEditor)
    // if (!this.orderEditor) {
    this.detailLoading = true;
    if (this.$isNotBlank(row.id)) {
      let delIds = [];
      delIds.push(row.id)
      delInquiryItem(delIds)
        .then(response => {
          this.detailLoading = false;
          if (response.code === 20000) {
            this.$message.success(response.data);
            this.getStockOrderDetailList();
            this.codeArray.splice(index, 1);
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(() => {
          this.detailLoading = false;
        })
    } else {
      this.$message.success('删除成功');
      this.codeArray.splice(index, 1);
    }
    // } else {
    //   this.$message.success('删除成功');
    //   this.codeArray.splice(index, 1);
    // }
  }).catch(() => {

  });
}
,
getStockOrderDetailList()
{
  this.loading = true;
  listItem(this.query) //查找该单号下的所有条码
    .then((response) => {
      this.codeArray = response.data.list || [];
      this.total = response.data.total || 0;
      this.loading = false;
    })
    .catch(() => {
      this.loading = false;
      this.list = [];
      this.total = 0;
    });
}
,
findSubInvs()
{
  this.invCodeList = [];
  let query = {
    filter: 3
  };
  findInvByUser(query)
    .then((response) => {
      this.invCodeList = response.data || [];
      if (this.invCodeList != null && this.invCodeList.length == 1) {
        this.formData.invCode = this.invCodeList[0].code;
        this.formData.deptCode = this.invCodeList[0].parentId;

      }
    })
    .catch(() => {
    });
}
,
selectApply()
{
  this.selectApplyVisible = true;
  //当父id为空的时候生成id
  if (this.pId == null) {
    addPlanId().then(response => {
      if (response.code === 20000) {
        this.pId = response.data
      }
    }).catch(() => {
      this.loading = false;
    })
  }
}
,
},
filters: {
  currencyFormatter(value) {
    // 假设您想将总价格式化为货币格式
    // 这里只是一个简单的示例，您可以使用库如 numeral.js 或 accounting.js 来实现更复杂的格式化
    return '￥' + value.toFixed(2);
  }
}
,
mounted()
{
  document.body.ondrop = function (event) {
    event.preventDefault();
    event.stopPropagation();
  };
}
,
created()
{
  this.findMethod()
  if (this.$isNotBlank(this.idQuery.id)) {
    this.query.limit = 1000;
    this.pId = this.idQuery.id;
    this.query.orderIdFk = this.idQuery.id;
    this.formData = this.idQuery.formData;
    this.orderEditor = true;
    this.sValue = this.formData.corpName;
    this.getStockOrderDetailList();
  } else {
    var date = new Date();
    this.formData = {
      id: null,
      billNo: null,
      remark: "",
      billType: "CGJH",
      deptCode: null,
      incCode: null,
      createTime: parseTime(
        date,
        "{y}-{m}-{d} {h}:{i}:{s}"
      ),
    };
    this.orderEditor = false;
  }
  this.findSubInvs();
  this.codeArray = [];
}
,
}
;
</script>
<style scoped>

.ao-text {
  width: 100%;
  font-size: 13px;
  font-family: "Microsoft YaHei";
  float: right;
  text-align: right;
  margin-top: 10px;
}

 .item-tooltip .el-tooltip__popper {
   /* 样式调整，如果需要的话 */
 }
</style>



