<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>
      <template #parent_id="{}">
        <vxe-pulldown style="width:100%" ref="pulldownParent" transfer>
          <template #default>
            <vxe-input v-model="parentName" suffix-icon="vxe-icon-search" placeholder="选择上级分类" @keyup="pulldownKeyupEvent"
              @focus="pulldownFocusEvent" @suffix-click="pulldownSuffixClick"></vxe-input>
          </template>
          <template #dropdown>
            <div class="my-dropdown">
              <vxe-grid ref="gridParent" v-bind="gridParentOptions" @cell-click="pulldownCellClickEvent">
              </vxe-grid>
            </div>
          </template>
        </vxe-pulldown>
      </template>
    </vxe-form>


    <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/base/api.js';

export default {

  props: {
    dataId: {
    }

  },

  data() {

    // 页面数据变量
    var pageData = {

      actions: {
        create: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/sort/create`,
        update: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/sort/update`,
        get: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/sort/detail`,
        list: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/sort/list`,
      },

      parentName: '',
      gridParentOptions: {
        height: 400,
        id: 'datagrid_router_parent_1',

        proxyConfig: {
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为 
          props: {
            result: 'MesMaterialsSort', // 配置响应结果列表字段
            total: 'total' // 配置响应结果总页数字段
          },
          // 接收Promise
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: (options) => {
              const { page, sorts } = options;
              var params = {};
              params.page = page.currentPage;
              params.limit = page.pageSize;
              params.order_bys = [];
              params.search_rules = [];
              if (sorts) {
                sorts.forEach((v) => {
                  params.order_bys.push({
                    column: v.property,
                    order: v.order
                  })
                });
              }
              return this.loadParentGrid({ params });
            }
          }
        },
        sortConfig: {
        },
        treeConfig: {
          transform: true,
          expandAll: true,
          rowField: 'id',
          parentField: 'parent_id'
        },
        checkboxConfig: {
          reserve: true,
          highlight: true
        },
        columns: [
          { field: 'name', sortable: true, title: '分类名', showHeaderOverflow: true, treeNode: true },
          { field: 'code', sortable: true, title: '编号', showHeaderOverflow: true }
        ]
      },

      formOptions: {
        data: {
          ename:"",
          "name": "",
          "code": "",
          parent_id: "0"
        },

        titleWidth: 150,
        titleAlign: 'right',

        rules: {
          name: [
            { required: true, message: '请输入名称' }
          ]
        },

        items: [
          { field: 'name', title: '名称', span: 24, itemRender: { name: '$input', props: { placeholder: '请输入名称' } } }, 
          { field: 'code', title: '编号', span: 24, itemRender: { name: '$input', props: { placeholder: '请输入编号' } } },

          { title: '上级分类', span: 24, slots: { default: 'parent_id' } },
        ]
      }

    };

    pageData.gridParentOptions = Object.assign({}, this.$mk.config.defaults.gridOptions, pageData.gridParentOptions);
    pageData.formOptions = Object.assign({}, this.$mk.config.defaults.formOptions, pageData.formOptions);

    return pageData;
  },
  created() {
    if (this.dataId) {
      this.$mk.post({
        url: this.actions.get,
        loading: "加载中...",
        data: {
          id: this.dataId
        },
        useBigInt: true
      }).then(a => { 
        this.formOptions.data = a.data.mes_materials_sort;

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

  },
  // 函数
  methods: {

    parentNameInit() {
      this.treeLoading = true;
      this.$mk.post({
        url: this.actions.list, 
        data: {
          "page": 1,
          "limit": 10000,
          "end_time": 0,
          "start_time": 0,
          "order_bys": [
          ],
          "search_rules": [
          ]
        }
      }).then(r => {
          if(r.data.MesMaterialsSort){
            r.data.MesMaterialsSort.forEach(item=>{
              if(this.formOptions.data.parent_id && item.id.toString() == this.formOptions.data.parent_id.toString()){

                this.parentName = item.name;
              }

            })
          }

      });
    },

    loadParentGrid({ params }) {


      params.start_time = 0;
      params.end_time = 0;

      return this.$mk.getPagedData({ url: this.actions.list, data: params });
    },

    loadData() {
    },

    ok() {

      let save = () => {
        let action = !this.dataId ? this.actions.create : this.actions.update;
        let postdata = Object.assign({ id: this.dataId }, this.formOptions.data);

        if(postdata.parent_id == "0"){
          postdata.parent_id  = 0;
        }
        if(typeof(postdata.parent_id) == "string"){

          postdata.parent_id = parseInt(postdata.parent_id)
        }
        if(!postdata.ename){
          postdata.ename = "";
        }
        if(!postdata.create_uid){
          postdata.create_uid = 0;
        }
        if(!postdata.update_uid){
          postdata.update_uid = 0;
        }
        postdata.create_time = 0;
        postdata.update_time = 0;

        this.$mk.post({
          url: action,
          loading: "保存中...",
          data: postdata,
          useBigInt: true
        }).then(() => {
          this.$mk.success("保存成功");
          this.$emit("callback", { success: true });
        }).catch((a) => {
          this.$mk.error(a.data.msg);
        });
      };

      this.$refs.xForm.validate((a) => { 
        let count = 0;
        if (a) {
          for (let name in a) {
            a[name];
            count++;
          } 
        }
        if (count > 0) {
          this.$mk.error(`存在${count}项错误，请检查`);
        }
        else {
          save();
        }
      });


    },

    cancel() {
      this.$emit("callback", {});
    },


    pulldownFocusEvent() {
      this.$refs.pulldownParent.showPanel()
    },
    pulldownKeyupEvent() {

    },
    pulldownSuffixClick() {
      this.$refs.pulldownParent.togglePanel()
    },
    pulldownCellClickEvent({ row }) {
      this.formOptions.data.parent_id = row.id;
      this.parentName = row.name;
      this.$refs.pulldownParent.hidePanel()
    },
  },
  // 监听属性
  watch: {

  }
};

</script>
<style></style>
