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

    <vxe-form :data="formOptions.data" ref="xForm" :title-width="formOptions.titleWidth"
      :title-align="formOptions.titleAlign" :rules="formOptions.rules" :items="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="60">
        <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 field="mes_materials" title="子件" width="160" :params="editorMaterials" formatter="formatRef"
        :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
      <vxe-column field="mes_warehouse" title="预出仓库" width="160" :params="editorWarehouse" formatter="formatRef"
        :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
      <vxe-column field="sub_qty" title="需用数量" width="120" :edit-render="{ name: '$input', props: { type: 'integer' } }">
      </vxe-column>
      <vxe-column field="loss_rate" title="损耗率%" width="120" formatter="formatPercentage"
        :edit-render="{ name: '$input', props: { type: 'integer' } }">
      </vxe-column>
    </vxe-table>

    <div class="mk-toolbar" v-if="isEdit">

    </div>

    <div class="footerbar">
      <a-button type="primary" @click="ok">确定</a-button>
      <a-button @click="cancel">取消</a-button>
    </div>

  </div>
</template>

<script>
import BASE_URL from '@/services/mes/api.js'; 

export default {

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

  },

  data() {

    //let _this = this;
    // 页面数据变量
    var pageData = {
      // 当前项目名称
      currentConfigName: "",
      // 当前项目ID
      currentBeid: 0,

      uploadDefaultImg: null,
      detailDataFieldName: "mes_bom",

      actions: {
        get: `${BASE_URL.BASE_URL}/MesBom/v1/mes/bom/detail`,
        create: `${BASE_URL.BASE_URL}/MesBom/v1/mes/bom/create`,
        update: `${BASE_URL.BASE_URL}/MesBom/v1/mes/bom/update`,
        detailsData: `${BASE_URL.BASE_URL}/MesBom/v1/mes/bom/sub/list`,
        saveDetails: `${BASE_URL.BASE_URL}/MesBom/v1/mes/bom/sub/batchHandle`,
      },

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

        // 表单校验规则
        rules: {

          mes_materials: [
            { required: true, message: '请输入父件' }
          ],
          version: [
            { required: true, message: '请输入版本号' }
          ]

        },
        // 表单项
        items: [
          {
            title: '父件', span: 12,
            field: 'mes_materials',
            dataRule: {
              fromField: "id",
              saveField: "material_id" // 如果表单项存储的是对象，将从fromField中取得值保存到saveField
            },
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "object",
                  valueField: "id",
                  textField: "name",
                  listdataFieldName: 'MesMaterials',
                  dataUrl: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/list`
                }
              }
            }
          },
          {
            title: '默认仓库', span: 12,
            field: 'mes_warehouse',
            dataRule: {
              fromField: "id",
              saveField: "warehouse_id" // 如果表单项存储的是对象，将从fromField中取得值保存到saveField
            },
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "object",
                  valueField: "id",
                  textField: "warehouse_name",
                  listdataFieldName: 'MesWarehouse',
                  searchFieldNames: ['warehouse_name'],
                  columns: [ // 表格列
                    { field: 'warehouse_name', title: '名称' },   // 字段名称，字段标题
                    { field: 'code', title: '编码' }   // 字段名称，字段标题
                  ],
                  dataUrl: `${BASE_URL.BASE_URL}/MesWarehouse/v1/mes/warehouse/list`
                }
              }
            }
          },
          { field: 'version', title: '版本号', span: 12, itemRender: { name: '$input' } },
          { field: 'is_default', title: '是否默认', span: 12, itemRender: { name: '$switch', props: { openLabel: '是', openValue: 1, closeValue: 0, closeLabel: '否' } } },

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

      ],


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

      ],
      editorMaterials: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesMaterials',
        dataUrl: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/list`
      },
      editorWarehouse: {
        dataType: "object",
        valueField: "id",
        textField: "warehouse_name",
        listdataFieldName: 'MesWarehouse',
        searchFieldNames: ['warehouse_name'],
        columns: [ // 表格列
          { field: 'warehouse_name', title: '名称' },   // 字段名称，字段标题
          { field: 'code', title: '编码' }   // 字段名称，字段标题
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MesWarehouse/v1/mes/warehouse/list`
      },


    };


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

    return pageData;
  },

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


  created() {


    // 获取路由的id参数
    let dataId = this.getDataId();

    // 如果有id参数，说明是编辑模式
    if (dataId) { 
      this.$mk.post({
        url: this.actions.get,
        loading: "加载中...",
        data: {id : this.$mk.toBigInt(dataId)},
        useBigInt : true
      }).then(a => {
        // =============================== 时间字段判断 自动生成 Start ===============================

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

        // =============================== 时间字段判断 自动生成 End ===============================
        this.formOptions.data = a.data[this.detailDataFieldName];

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

      this.isEdit = true;

      this.detailsDataLoad(dataId);

    } else {
      // 如果没有id参数，说明是新增模式
      this.addModeItems.forEach(item => {
        this.formOptions.items.push(item);
      })

      this.detailsDataInit();
    }



    this.heightInit();

  },
  // 函数
  methods: {



    detailsDataLoad(id) {

      this.$mk.post({
        url: this.actions.detailsData,
        loading: "加载中...",
        data: {
          "page": 1,
          "limit": 10000,
          "start_time": 0,
          "end_time": 0,
          "search_rules": [
            {
              column: "bom_id", // 字段名
              mode: "=", // 搜索模式
              value: id.toString()
            }
          ],
          "order_bys": [
          ]
        },
        useBigInt: true
      }).then(a => {

        this.detailsSourceData = a.data.MesBomSub || [];
        this.detailsData = JSON.parse(JSON.stringify(a.data.MesBomSub || []));
 
        this.detailsDataInit();
      });
    },

    heightInit() {

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

        this.table1Height = h;
      });

    },
    detailsDataInit() {
      for (let i = this.detailsData.length; i < 10; i++) {
        this.detailsData.push({});
      }
    },
    // 获取路由的id参数
    getDataId() {
      let dataId = this.dataId;
      if (this.$route.params.id) {
        dataId = this.$route.params.id;
      }
      if (!dataId) {
        dataId = 0;
      }
      return dataId;
    },
    getDataId_BigInt() {
      let dataId = this.getDataId();
      return this.$mk.toBigInt(dataId);
    },


    // 返回
    back() {
      // 如果是新增模式，关闭当前页面
      if (!this.isEdit) {
        this.$closePage({
          closeRoute: "/MesBom/MesBomAdd"
        });
      } else {
        // 如果是编辑模式，关闭当前页面
        this.$closePage({
          closeRoute: "/MesBom/MesBomUpdate"
        });
      }
      // 打开列表页面
      this.$openPage('/MesBom/MesBomList')
    },



    // 保存
    ok() {

      let hasDetails = false;
      let includeMainMaterials = false;
      this.detailsData.forEach(item => {
          if (item.mes_materials && item.mes_materials.id) {
            hasDetails = true;

            if(this.formOptions.data.mes_materials
             && this.formOptions.data.mes_materials.id 
            && this.formOptions.data.mes_materials.id.toString() == item.mes_materials.id.toString()){
              includeMainMaterials = true;
            }
          }

        });



      let saveDetails = (dataId) => {
 
         dataId = dataId || this.getDataId_BigInt();
        let ds = [];

        this.detailsData.forEach(item => {
          if (item.mes_materials && item.mes_materials.id) {
            let o = {};
            o.material_id = this.$mk.toBigInt(item.mes_materials.id);
            if (item.mes_warehouse) {
              o.warehouse_id = this.$mk.toBigInt(item.mes_warehouse.id);
            } else {
              o.warehouse_id = 0;
            }
            o.sub_qty = parseFloat(item.sub_qty || 0);
            o.loss_rate = parseFloat(item.loss_rate || 0);
            if (item.id) {
              o.id = this.$mk.toBigInt(item.id);
            }
            ds.push(o);
          }

        });


        console.log(ds);

        var postdata = {
          insertList: [],
          updateList: [],
          deleteList: this.deletedDetailsData
        };

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

          item.bom_id = dataId;
          if (item.id) {
            postdata.updateList.push(item);
          } else {
            postdata.insertList.push(item);
          }
        })
        this.$mk.post({
          url: this.actions.saveDetails,
          data: postdata,
          useBigInt: true
        }).then(a => {
          if (a.code == "200") {

            this.$mk.success("保存成功");
            if (!this.isEdit) { // 如果是新增模式，关闭当前页面
              this.back();
            }

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


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


        // 如果是新增模式，提交新增接口 如果是编辑模式，提交编辑接口
        let action = !this.isEdit ? this.actions.create : this.actions.update;
        // 如果是新增模式，提交的数据中加入id 如果是编辑模式，提交的数据中不加入id
        let postdata = Object.assign({}, this.formOptions.data);
        // 如果是编辑模式
        if (this.isEdit) {
          // postdata = { BathroomParts: postdata }
        } 
        // 格式化提交的数据
        this.$mk.formatFormData({ data: postdata, rules: this.formOptions.items });



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

           
            saveDetails(a.data.id);

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


        });


      };


      
      

      // 验证表单
      this.$mk.validateForm({ form: this.$refs.xForm }).then(() => { // 验证表单
 
        if(!hasDetails){
          this.$mk.error(`子件不能为空`);
        }
        else if(includeMainMaterials){
          this.$mk.error(`子件不能跟父件一样`);
        }
        else{
          save(); // 提交保存
        }
      
    
      }).catch(count => { // 验证失败
        this.$mk.error(`存在${count}项错误，请检查`);
      });


    },


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


    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 (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 (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);


      }

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

  }
};

</script>


<style scoped lang="less">
.page-body {
  padding: 30px;
  background: @base-bg-color;
}

.formtabs .ant-tabs-tabpane {
  /* background: white; */
  padding: 12px;
}

.gridPanel {
  height: calc(100vh - 600px);
}

.footerbar {
  padding-left: 10px;
}

.imagePanel {
  cursor: pointer;
  padding: 10px;
  width: 100px;

  img {
    width: 80px;
    height: 80px;
  }
}

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

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