<template>
  <div class="page-body">

    <div class="approvedbg" v-if="pageStatus == 'approved'"></div>
    <div class="voucher-toolbar">
      <div class="voucher-toolbar-left">
        <a-button @click="pageVoucherAdd">新增</a-button>

        <a-dropdown :disabled="pageStatus == 'approved'">
          <a-menu slot="overlay" @click="handleMenuClick">
            <a-menu-item key="TP_outSourceOrder">
              订单
            </a-menu-item>
          </a-menu>
          <a-button> 选单
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
        <a-button type="primary" @click="ok" :disabled="pageStatus == 'approved'">保存</a-button>
        <a-button @click="pageApproved" type="primary" :disabled="!this.getDataId() || pageStatus == 'approved'">审批
        </a-button>
        <a-button @click="pageUnapproved" :disabled="!this.getDataId() || pageStatus != 'approved'">弃审</a-button>
        <a-button @click="pageVoucherDelete" :disabled="!this.getDataId() || pageStatus == 'approved'">删除</a-button>

        <a-button @click="pageComplete" :disabled="!this.getDataId() || pageStatus != 'approved'">完成</a-button>

        <a-button @click="pageClose" :disabled="!this.getDataId() || pageStatus != 'approved'">关闭</a-button>

        <a-button :disabled="!this.getDataId()" @click="pageExport" v-if="false">导出</a-button>
        <a-button :disabled="!this.getDataId()" @click="pagePrint" v-if="false">打印</a-button>
      </div>
      <div class="voucher-toolbar-right">
        <a-button-group>
          <a-button @click="pageSearch">
            <a-icon type="search" />
          </a-button>
          <a-button   @click="pageNext">
            <a-icon type="left" />
          </a-button>
          <a-button   @click="pagePrev">
            <a-icon type="right" />
          </a-button>
        </a-button-group>
      </div>
    </div>

    <vxe-form :data="options.formOptions.data" ref="xForm" :title-width="options.formOptions.titleWidth"
      :title-align="options.formOptions.titleAlign" :rules="options.formOptions.rules" :items="options.formOptions.items"
      titleColon>
    </vxe-form>



    <vxe-table border show-overflow keep-source ref="xTable" :height="table1Height" :data="detailsData"
      @pulldownSelected="onPulldownSelected" @popupSelected="onPopupSelected" :export-config="{}"
      @edit-closed="afterEditEvent" @edit-actived="beforeEditEvent"
      :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: beforeEditMethod }">
      <vxe-column width="70" v-if="pageStatus != 'approved'">
        <template #default="{ row }">
          <div class="oplinks2">
            <a @click.stop="pageAdd(row)" title="新增">
              <a-icon class="icon" type="plus-circle" />
            </a>
            <a @click.stop="pageDelete(row)" title="删除">
              <a-icon class="icon" type="delete" />
            </a>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="工序管理" width="120" v-if="dataId">
        <template #default="{ row }">
          <div class="oplinks2" v-if="dataId && row.materials_id">
            <a-button @click.stop="pageShowProcesses({row})">工序设置</a-button>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="contract_number" title="合同号" width="160" :edit-render="{ name: '$input' }"></vxe-column>
      <vxe-column field="materials_code" title="料品编码" width="160"></vxe-column>
      <vxe-column field="materials_name" title="料品名称" width="160" :params="editorMaterials"
        :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
      <vxe-column field="unit_name" title="单位名" width="160"></vxe-column>

      <vxe-column field="process_route" title="工艺路线" width="160" :params="editor_process_route"
        :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

      <vxe-column field="molding_type" title="成型方式" width="160" :params="editor_molding_type"
        :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

      <vxe-column field="production_num" title="布产数量" width="160"
        :edit-render="{ name: '$input', props: { type: 'integer' } }"></vxe-column>
      <vxe-column field="batch_num" title="批次数量" width="160"
        :edit-render="{ name: '$input', props: { type: 'integer' } }"></vxe-column>
      <vxe-column field="remark" title="备注" width="160" :edit-render="{ name: '$input' }"></vxe-column>



    </vxe-table>





    <vxe-modal class="vxe-table--ignore-clear" v-model="showProcesses" width="900" height="800" :show-footer="true"
      @confirm="confirmProcesses" min-width="600" min-height="400" show-zoom resize transfer>
      <template #title>
        <span>工序管理</span>
      </template>
      <template #default>

        <vxe-table border show-overflow keep-source ref="xTable2" :height="table2Height" :data="detailsData2"
          @pulldownSelected="onPulldownSelected2" @popupSelected="onPopupSelected2" :export-config="{}"
          @edit-closed="afterEditEvent2" @edit-actived="beforeEditEvent2"
          :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: beforeEditMethod2 }">
          <vxe-column width="70" v-if="pageStatus != 'approved'">
            <template #default="{ row }">
              <div class="oplinks2">
                <a @click.stop="pageAdd2(row)" title="新增">
                  <a-icon class="icon" type="plus-circle" />
                </a>
                <a @click.stop="pageDelete2(row)" title="删除">
                  <a-icon class="icon" type="delete" />
                </a>
              </div>
            </template>
          </vxe-column>

          <vxe-column field="step_name" title="工序" width="160" :params="editorProcesses"
            :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>



        </vxe-table>

      </template>
    </vxe-modal>
  </div>
</template>

<script>
import BASE_URL from '@/services/mes/api.js';
import JSONbig from 'json-bigint'

export default {

  i18n: require('./i18n'),
  components: {},
  props: {
    pageMode: {
      type: String,
      default: "edit"
    }
  },

  data() {

    let pageData = {
      dataId: null,
      actions: {
      },
      prevId: null,
      nextId: null,

      table1Height: 400,
      table2Height: 400,
      detailsData: [
      ],
      deletedDetailsData: [

      ],

      currentRow :null,
      showProcesses:false,

      detailsData2: [
      ],
      deletedDetailsData2: [

      ],


      pageStatus: '',
      editorMaterials: {
        dataType: "mapper",
        mapper: [
          { field: "materials_id", fromField: "id" },
          { field: "materials_code", fromField: "code" },
          { field: "materials_name", fromField: "name" },
          { field: "unit_name", fromField: "unit" },
        ],
        showField: "materials_name",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesMaterials',
        dataUrl: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/list`,
        popup: {
          page: () => import("../../MesMaterials/MesMaterials/List")
        }
      },
      editorProcesses: {
        dataType: "mapper",
        mapper: [
          { field: "step_id", fromField: "id" }, 
          { field: "step_name", fromField: "name" } 
        ],
        showField: "step_name",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesProcesses',
        dataUrl: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/list`,
        popup: {
          page: () => import("../../MesProcesses/MesProcesses/List")
        }
      },
      editor_process_route: {
        dataType: "string",
        valueField: "name",
        textField: "name",
        listdataFieldName: 'MesEnumValue',
        actionParams: {
          search_rules_enum: [
            {
              column: "code",
              mode: "=",
              value: "10"
            }
          ]
        },
        dataUrl: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/list`
      },
      editor_molding_type: {
        dataType: "string",
        valueField: "name",
        textField: "name",
        listdataFieldName: 'MesEnumValue',
        actionParams: {
          search_rules_enum: [
            {
              column: "code",
              mode: "=",
              value: "1"
            }
          ]
        },
        dataUrl: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/list`
      },
      options: {}
    };

    return pageData;
  },

  computed: {
    desc() {
      return this.$t('editPageDesc')
    }
  },


  created() {

    this.optionsInit();
    this.pageInit();
    this.heightInit();
  },
  onload() {
    if (this.$route.params.id) {
      this.dataId = this.$route.params.id;
    }
  }, 
  // 函数
  methods: {


    optionsInit() {
      // 页面数据变量
      var pageData = {
        // 当前项目名称
        currentConfigName: "",
        // 当前项目ID
        currentBeid: 0,

        detailDataFieldName: "mes_production_order",

        actions: {
          get: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/detail`,
          create: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/create`,
          update: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/update`,

        },

        keyName: 'id',
        // 是否编辑模式
        isEdit: false,
        // 表单数据
        formOptions: {
          data: {
          },
          // 标题宽度
          titleWidth: 150,
          // 标题对齐方式
          titleAlign: 'right',

          // 表单校验规则
          rules: {

            start_time: [
              { required: true, message: '请输入预计开始日期' }
            ]
          },
          // 表单项
          items: [
            {
              field: 'production_number', title: '单据编号', span: 6, itemRender: {
                name: '$input',
                props: { radonly: true, disabled: true, placeholder: '自动编号' }

              }
            },
            { field: 'start_time', dataRule: { type: "timestamp" }, title: '预计开始日期', span: 6, itemRender: { name: '$input', props: { type: 'date' } } },


          ]
        },
        // 新增模式表单项
        addModeItems: [

        ],


      };

      pageData.formOptions.items.forEach(item => {

        pageData.formOptions.data[item.field] = '';
      })

      // 合并表单数据及配置
      pageData.formOptions = Object.assign({}, this.$mk.config.defaults.formOptions, pageData.formOptions);

      this.options = pageData;
    },



    heightInit() {

      this.$nextTick(() => {
        let h = this.$mk.getWindowSize().height - this.$mk.getOffsetTop(this.$refs.xTable.$el) - 180;

        this.table1Height = h;
      });

    },

    getDefaultData() {
      let data = {};
      this.options.formOptions.items.forEach(item => {
        data[item.field] = item.defaultValue || "";
      });
      return data;
    },

    setPageReadonly(readonly) {
      this.options.formOptions.items.forEach(item => {
        if (item.itemRender && item.itemRender.name == "$select") {
          item.itemRender.props.disabled = readonly;
        }
        if (item.itemRender && item.itemRender.props) {
          item.itemRender.props.readonly = readonly;
        }

      });
    },
    pageInit() {

      this.pageStatus = '';
      this.deletedDetailsData = [];
      // 获取路由的id参数
      let dataId = this.getDataId();
      // 如果有id参数，说明是编辑模式
      if (dataId) {
        this.$mk.post({
          url: this.options.actions.get,
          loading: "加载中...",
          data: {
            id: this.getDataId_BigInt()
          },
          useBigInt: true
        }).then(a => {

          let detailDataFieldName = this.options.detailDataFieldName;

          if (a.data[detailDataFieldName].create_time) {
            a.data[detailDataFieldName].create_time = new Date(a.data[detailDataFieldName].create_time * 1000);
          }
          if (a.data[detailDataFieldName].update_time) {
            a.data[detailDataFieldName].update_time = new Date(a.data[detailDataFieldName].update_time * 1000);
          }
          if (a.data[detailDataFieldName].start_time) {
            a.data[detailDataFieldName].start_time = new Date(a.data[detailDataFieldName].start_time * 1000);
          }


          this.options.formOptions.data = a.data[detailDataFieldName];

          if (a.data[detailDataFieldName].audit_status == 1) {
            this.pageStatus = 'approved';
          }

          this.detailsData = JSON.parse(JSON.stringify(a.data[detailDataFieldName].production_order_materials || []));

          this.detailsDataInit();
          this.$forceUpdate()
        }).catch((a) => {
          this.detailsDataInit();
          this.$mk.error(a.data.msg);
        });

        this.options.isEdit = true;

        this.$forceUpdate()
      } else {

        this.options.formOptions.data = this.getDefaultData();
        this.detailsData = [];
        this.pageStatus = '';
        this.setPageReadonly(this.pageStatus == 'approved');

        this.detailsDataInit();
      }
    },

    detailsDataInit() {
      for (let i = this.detailsData.length; i < 100; i++) {
        this.detailsData.push({});
      }
    },
    detailsDataInit2() {
      for (let i = this.detailsData2.length; i < 50; i++) {
        this.detailsData2.push({});
      }
    },

    // 获取路由的id参数
    getDataId() {
      return this.dataId;
    },
    getDataId_BigInt() {
      let dataId = this.getDataId();
      if(!dataId) return 0;
      if(typeof(dataId) == "object"){
        return dataId;
      }
      return this.$mk.toBigInt(dataId);
    },

    // 返回
    back() {
      this.isEdit = this.options.isEdit;
      // 如果是新增模式，关闭当前页面
      if (!this.isEdit) {
        this.$closePage({
          closeRoute: this.options.addPageUrl
        });
      } else {
        this.$closePage({
          closeRoute: this.options.editPageUrl
        });
      }
      // 打开列表页面
      this.$openPage(this.options.listPageUrl)
    },

    // 保存
    ok() {

      let save = () => {


        // 如果是新增模式，提交新增接口 如果是编辑模式，提交编辑接口
        let action = !this.dataId ? this.options.actions.create : this.options.actions.update;


        // 如果是新增模式，提交的数据中加入id 如果是编辑模式，提交的数据中不加入id
        let postdata = Object.assign({}, this.options.formOptions.data);
        // 如果是编辑模式
        if (this.isEdit) {
          // postdata = { MesUnit: postdata }
        }

        if (this.dataId) {
          postdata.id = this.getDataId_BigInt();
        }

        let ds = JSONbig.parse(JSONbig.stringify(this.detailsData));

        ds = ds.filter(item => item.materials_id);
        if (!ds.length) {
          this.$mk.error(`数据行为空`);
          return;
        }

        ds.forEach(item => {

          if (this.dataId) {
            item.production_order_id = this.getDataId_BigInt();
          }
          delete item._X_ROW_KEY;

          if (item.id) {
            item.id = this.$mk.toBigInt(item.id);
          }

          item.materials_id = this.$mk.toBigInt(item.materials_id);
          item.production_num = parseInt(item.production_num);
          item.batch_num = parseInt(item.batch_num);

        })

        console.log(ds)


        if (this.dataId) {
          postdata.production_order_materials = {
            insertList: [],
            updateList: [],
            deleteList: []
          };

          ds.forEach(item => {
            if (item.id) {
              postdata.production_order_materials.updateList.push(item);
            }
            else {
              postdata.production_order_materials.insertList.push(item);
            }
          });

          this.deletedDetailsData.forEach(item => {
            postdata.production_order_materials.deleteList.push(item);
          })


        } else {
          postdata.production_order_materials = ds;


        }

        delete postdata.production_order_association_order;
        delete postdata.reorder_staff;
        delete postdata.update;
        delete postdata.create;
        delete postdata.production_department;
        delete postdata.audit_staff_appoint;




        // 格式化提交的数据
        this.$mk.formatFormData({ data: postdata, rules: this.options.formOptions.items });

        console.log(postdata)

        // 提交数据
        this.$mk.post({
          url: action,
          loading: "保存中...",
          data: postdata,
          useBigInt: true,
        }).then((a) => { // 成功回调
          console.log(a)
          if (a.code == 200) {
            this.$mk.success(a.msg || "保存成功");
            if (!this.dataId) {
              this.dataId = a.data.id;

            }

            this.pageInit();
          } else {
            this.$mk.error(a.msg || "保存失败"); // 显示错误信息
          }

        }).catch((a) => { // 失败回调
          console.log(a)
          this.$mk.error(a.msg); // 显示错误信息
        });


      };


      // 验证表单
      this.$mk.validateForm({ form: this.$refs.xForm }).then(() => { // 验证表单
        save(); // 提交保存
      }).catch(count => { // 验证失败
        this.$mk.error(`存在${count}项错误，请检查`);
      });


    },


    // 取消 返回
    cancel() {
      this.back();
    },

    pageExport() {


    },

    pagePrint() {

    },
    pageSearch() {
      let { width, height } = this.$mk.getWindowSize();
      this.$mk.dialog.open({
        page: () => import("./List"),
        title: "选择单据",
        showFooter: true,
        width: width * 0.9,
        height: height * 0.9,
        callback: ({ data }) => {

          if (data && data[0]) {
            this.dataId = data[0].id;
            this.pageInit();
          }
        }
      })
    },

    pageNext() {

      this.$mk.post({
          url: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/switch`, 
          data: {
            id: this.getDataId_BigInt(),
            next: 1
          },
          useBigInt: true
        }).then(a => {
          if (a.code == "200") {
            this.dataId = a.data.mes_production_order_detail_response.mes_production_order.id;
            this.pageInit();
          }
          else {
            this.$mk.error(a.msg);
          }
        });


    },
    pagePrev() {
      this.$mk.post({
          url: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/switch`, 
          data: {
            id: this.getDataId_BigInt(),
            next: 0
          },
          useBigInt: true
        }).then(a => {
          if (a.code == "200") {
            this.dataId = a.data.mes_production_order_detail_response.mes_production_order.id;
            this.pageInit();
          }
          else {
            this.$mk.error(a.msg);
          }
        });
    },
    pageApproved() {
      let dataId = this.getDataId();
      if (!dataId) {
        return;
      }


      let sendApproved = () => {
        this.$mk.post({
          url: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/approve`,
          loading: '审批中...',
          data: {
            id: this.getDataId_BigInt(),
            audit_remark: ''
          },
          useBigInt: true
        }).then(a => {
          if (a.code == "200") {
            this.$mk.success("审批成功");
            this.pageInit();
          }
          else {
            this.$mk.error(a.msg);
          }
        });
      }

      sendApproved("");

    },
    pageUnapproved() {
      let dataId = this.getDataId();
      if (!dataId) {
        return;
      }
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/cancelApprove`,
        loading: '弃审中...',
        data: {
          id: this.getDataId_BigInt(),
          audit_remark: ''
        },
        useBigInt: true
      }).then(a => {
        if (a.code == "200") {
          this.$mk.success("弃审成功");
          this.pageInit();

        } else {
          this.$mk.error(a.msg);
        }
      });
    },
    pageComplete() {
      let dataId = this.getDataId();
      if (!dataId) {
        return;
      }
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/complete`,
        loading: '操作中...',
        data: {
          id: this.getDataId_BigInt(),
          audit_remark: ''
        },
        useBigInt: true
      }).then(a => {
        if (a.code == "200") {
          this.$mk.success(a.msg || "操作成功");
          this.pageInit();

        } else {
          this.$mk.error(a.msg);
        }
      });
    },
    pageClose() {
      let dataId = this.getDataId();
      if (!dataId) {
        return;
      }
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/close`,
        loading: '操作中...',
        data: {
          id: this.getDataId_BigInt(),
          audit_remark: ''
        },
        useBigInt: true
      }).then(a => {
        if (a.code == "200") {
          this.$mk.success(a.msg || "操作成功");
          this.pageInit();

        } else {
          this.$mk.error(a.msg);
        }
      });
    },
    pageVoucherAdd() {
      this.dataId = null;
      this.pageInit();
    },
    handleMenuClick(e) {
      let { width, height } = this.$mk.getWindowSize();
      if (e.key == 'TP_outSourceOrder') {
        this.$mk.dialog.open({
          page: () => import("./List"),
          title: "选择订单",
          showFooter: true,
          width: width * 0.9,
          height: height * 0.9,
          callback: ({ data }) => {
            console.log(data)
          }
        })
      }
    },
    pageVoucherDelete() {
      let dataId = this.getDataId();
      if (!dataId) {
        return;
      }
      this.$mk.confirm('您确定要删除吗？').then(type => {
        if (type == 'confirm') {
          this.$mk.post({
            url: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/mes/production/order/detele`,
            loading: "删除中...",
            data: {
              id: this.getDataId_BigInt()
            },
            useBigInt: true
          }).then(a => {
            if (a.code == "200") {
              this.$mk.success("删除成功");
              this.dataId = null;
              this.pageInit();
            } else {
              this.$mk.error(a.message);
            }
          });
        }
      });

    },
    pageShowProcesses({row}){
        this.currentRow = row;

        console.log(row)
        if(!this.dataId){
          return;
        }
        if(!row.materials_id){ 
          this.$mk.error("未设置料品");
          return;
        }
        this.$mk.post({
          url: `${BASE_URL.BASE_URL}/MesProductionOrder/v1/production/order/processes/list`,
          loading: "加载中...",
          data: {
            "page": 1,
            "limit": 10000,
            "start_time": 0,
            "end_time": 0,
            "search_rules": [
              {
                column: "materials_id",  
                mode: "=",  
                value: row.materials_id.toString()
              },
              {
                column: "production_order_id",  
                mode: "=",  
                value: this.dataId.toString()
              }
            ],
            "order_bys": [
            ]
          } 
        }).then(a => {
           
          this.deletedDetailsData2 = [];
          this.detailsData2 = JSON.parse(JSON.stringify(a.data.ProductionOrderProcesses || []));

          this.showProcesses = true;
        this.detailsDataInit2();
        });

    },

    pageAdd(row) {
      const $table = this.$refs.xTable
      const record = {
      }
      if (row) {

        this.detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.detailsData.push(record)
      }
    },

    pageDelete(row) {
      const $table = this.$refs.xTable;
      if (row.id) {
        this.deletedDetailsData.push(this.$mk.toBigInt(row.id))
      }
      this.detailsData.splice($table.getRowSeq(row) - 1, 1);
    },
    beforeEditMethod({ column, row }) {

      if (this.pageStatus == "approved") {
        return false;
      }
      if (row.SourceTableID && column.field != "Quantity") {
        return false;
      }
      return true;
    },
    afterEditEvent({ column, row }) {
      if (column.field == "Quantity" || column.field == "Price") {
        row.Amount = parseInt(row.Quantity || 0) * parseFloat(row.Price || 0);

      }

      if (column.field == "specification") {
        row.specification = this.specification;
      }
    },
    beforeEditEvent({ column, row }) {
      if (this.pageStatus == "approved") {
        return false;
      }
      if (row.SourceTableID && column.field != "Quantity") {
        return false;
      }
      if (column.field == "specification") {
        this.specification = row.specification;
      }
    },

    onPulldownSelected({ row, name, params }) {
      if (name == 'ag_inventory') {
        this.updateToGrid(row, this.detailsData[params.$rowIndex]);

        setTimeout(() => {
          this.$refs.xTable.clearEdit();
        }, 50);
      }

    },
    onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
      if (name == 'ag_inventory') {

        for (let i = params.$rowIndex, ri = 0; i < params.$rowIndex + rows.length; i++, ri++) {
          if (i == this.detailsData.length) {
            let newrow = {
            };
            this.detailsData.push(newrow);
          }
          let inv = rows[ri];

          this.updateToGrid(inv, this.detailsData[i]);
        }

        setTimeout(() => {
          this.$refs.xTable.clearEdit();
        }, 50);


      }




    },


    
    pageAdd2(row) {
      const $table = this.$refs.xTable2
      const record = {
      }
      if (row) {

        this.detailsData2.splice($table.getRowSeq(row), 0, record);
      } else {
        this.detailsData2.push(record)
      }
    },

    pageDelete2(row) {
      const $table = this.$refs.xTable2;
      if (row.id) {
        this.deletedDetailsData2.push(this.$mk.toBigInt(row.id))
      }
      this.detailsData2.splice($table.getRowSeq(row) - 1, 1);
    },
    beforeEditMethod2({ column, row }) {

      if (this.pageStatus == "approved") {
        return false;
      }
      if (row.SourceTableID && column.field != "Quantity") {
        return false;
      }
      return true;
    },
    afterEditEvent2({ column, row }) {
      if (column.field == "Quantity" || column.field == "Price") {
        row.Amount = parseInt(row.Quantity || 0) * parseFloat(row.Price || 0);

      }

      if (column.field == "specification") {
        row.specification = this.specification;
      }
    },
    beforeEditEvent2({ column, row }) {
      if (this.pageStatus == "approved") {
        return false;
      }
      if (row.SourceTableID && column.field != "Quantity") {
        return false;
      }
      if (column.field == "specification") {
        this.specification = row.specification;
      }
    },

    onPulldownSelected2({ row, name, params }) {
      if (name == 'ag_inventory') {
        this.updateToGrid(row, this.detailsData[params.$rowIndex]);

        setTimeout(() => {
          this.$refs.xTable.clearEdit();
        }, 50);
      }

    },
    onPopupSelected2({ rows, name, params }) {
      console.log(rows, name, params);
      if (name == 'ag_inventory') {

        for (let i = params.$rowIndex, ri = 0; i < params.$rowIndex + rows.length; i++, ri++) {
          if (i == this.detailsData.length) {
            let newrow = {
            };
            this.detailsData.push(newrow);
          }
          let inv = rows[ri];

          this.updateToGrid(inv, this.detailsData[i]);
        }

        setTimeout(() => {
          this.$refs.xTable.clearEdit();
        }, 50);


      }
    },

    confirmProcesses(){
      let ds = this.detailsData2.filter(a=>a.step_id);
      
      var postdata = {
          insertList: [],
          updateList: [],
          deleteList: this.deletedDetailsData2
        };

        ds.forEach(item => {
          delete item._X_ROW_KEY;

          item.production_order_id = this.getDataId_BigInt();
          item.materials_id = this.$mk.toBigInt(this.currentRow.materials_id); 
          item.step_id = this.$mk.toBigInt(item.step_id);
          
          
          if (item.id) {
            item.id = this.$mk.toBigInt(item.id);
            postdata.updateList.push(item);
          } else {
            postdata.insertList.push(item);
          }
        })
        this.$mk.post({
          url:  `${BASE_URL.BASE_URL}/MesProductionOrder/v1/production/order/processes/batchHandle`,
          data: postdata,
          useBigInt: true
        }).then(a => {
          if (a.code == "200") {

            this.$mk.success("保存成功");
            

          } else {
            this.$mk.error(a.message);
          }


        }).catch((a) => {
          this.$mk.error(a.data.msg);
        });

    }
  },
  // 监听属性
  watch: {

  }
};

</script>
 
<style>
.page-body {
  background: white;
  padding: 8px;
}

.oplinks2 svg {
  width: 18px;
  height: 18px;
}

.oplinks2 i {
  margin-left: 5px;
}
</style>
