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

    <div class="approvedbg" v-if="pageStatus == 'approved'"></div>

    <div class="voucher-toolbar">
      <div class="voucher-toolbar-left">



        <a-button type="primary" @click="ok"  >保存</a-button>
        <a-button @click="pageApproved" type="primary" :disabled="!this.getDataId() || pageStatus == 'approved'">审批
        </a-button>

        <a-button @click="back">关闭</a-button>

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

    <a-tabs>
      <a-tab-pane key="1" tab="订单明细">

        <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" 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 field="mold_scheme" title="模型" width="160" :params="editor_scheme" formatter="formatRef"
            :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
          <vxe-column field="production_type" title="布产类型" width="160" :params="options_production_type"
            formatter='formatEnum'
            :edit-render="{ name: '$select', props: { options: options_production_type } }"></vxe-column>

          <vxe-column field="mold_master_user_detail" title="师傅" width="160" :params="editor_staff" formatter="formatRef"
            :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

          <vxe-column field="manufacture_cycle" title="制作周期" width="160" formatter="formatDate"
            :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
          <vxe-column field="draw_start_time" title="预计开始画图时间" width="160" formatter="formatDate"
            :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
          <vxe-column field="split_design_time" title="分模设计时间预计" width="160" formatter="formatDate"
            :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
          <vxe-column field="draw_time" title="出图时间预计" width="160" formatter="formatDate"
            :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
          <vxe-column field="draw2D_time" title="出2D时间预计" width="160" formatter="formatDate"
            :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
          <vxe-column field="draw3D_time" title="出3D时间预计" width="160" formatter="formatDate"
            :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
          <vxe-column field="horizontal_frame_time" title="横架到厂日期预计" width="160" formatter="formatDate"
            :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
          <vxe-column field="inlay_deep_hole_time" title="镶件深孔钻到厂日期预计" width="160" formatter="formatDate"
            :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
        </vxe-table>
      </a-tab-pane>

    </a-tabs>


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

    </div>



  </div>
</template>

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

export default {

  name: '',
  components: {},
  props: {
    pageMode: {
      type: String,
      default: "edit"
    },
    dataId: {
    }

  },

  data() {
    //收款状态 0未收款 1已收款

    const options_paid_status = [{ value: 0, label: '未收款' }, { value: 1, label: '已收款' }];

    //let _this = this;
    // 页面数据变量
    var pageData = {

      options_paid_status: options_paid_status,
      options_production_type: [{ value: '1', label: '正常布产' }, { value: '2', label: '委托布产' }],
      // 当前项目名称
      currentConfigName: "",
      // 当前项目ID
      currentBeid: 0,

      pageStatus: '',

      uploadDefaultImg: null,

      
      detailDataFieldName: "mold_order",

      actions: {
        get: `${BASE_URL.BASE_URL}/MoldOrder/v1/mold/order/detail`,
        create: `${BASE_URL.BASE_URL}/MoldOrder/v1/mold/order/create`,
        update: `${BASE_URL.BASE_URL}/MoldOrder/v1/mold/order/update`
      },

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

        // 表单校验规则
        rules: {

          code: [
            { required: true, message: '请输入订单编码' }
          ],
          name: [
            { required: true, message: '请输入名称' }
          ],
        },
        // 表单项
        items: [
          { field: 'code', title: '订单编码', span: 6, itemRender: { name: '$input', props: { } } },
          { field: 'name', title: '客户名称', span: 6, itemRender: { name: '$input', props: { } } },
          { field: 'contact', title: '联系人', span: 6, itemRender: { name: '$input', props: { } } },
          { field: 'phone', title: '联系电话', span: 6, itemRender: { name: '$input', props: { } } },

          { field: 'salesman', title: '业务员姓名', span: 6, itemRender: { name: '$input', props: { } } },
          { field: 'contract_no', title: '合同号', span: 6, itemRender: { name: '$input' , props: { }} },
          { field: 'contract_start_time', dataRule: { type: "timestamp" }, title: '合同开始日期', span: 6, itemRender: { name: '$input', props: { type: "date" } } },
          { field: 'contract_end_time', dataRule: { type: "timestamp" }, title: '合同结束日期', span: 6, itemRender: { name: '$input', props: { type: "date" } } },

          { field: 'amount', dataRule: { type: 'number' }, title: '订单金额', span: 6, itemRender: { name: '$input', props: { type: 'number' } } },
          { field: 'paid_amount', dataRule: { type: 'number' }, title: '付款金额', span: 6, itemRender: { name: '$input', props: { type: 'number' } } },
          { field: 'paid_ratio', dataRule: { type: 'number' }, title: '付款比例', span: 6, itemRender: { name: '$input', props: { type: 'number' } } },

          { field: 'paid_status', dataRule: { type: 'integer' }, title: '付款状态', span: 6, itemRender: { name: '$select', props: { options: options_paid_status } } },




          { field: 'remark', title: '备注', span: 24, itemRender: { name: '$input', props: { } } },


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

      ],


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

      ],
      editor_scheme: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MoldScheme',
        mapper: [
          { fromField: "id", field: "mold_id" }
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MoldScheme/v1/mold/scheme/list`
      },
      editor_staff: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesStaff',
        mapper: [
          { fromField: "id", field: "mold_master_uid" }
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MesStaff/v1/mes/staff/list`
      },


    };


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

    return pageData;
  },

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


  created() {


    this.pageInit();


    this.heightInit();

  },
  // 函数
  methods: {
    pageInit() {

      // 获取路由的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 => {


          this.formOptions.data = this.$mk.formatDetailData({ data: a.data[this.detailDataFieldName], rules: this.formOptions.items });
          console.log(this.formOptions.data)
          this.detailsData = JSON.parse(JSON.stringify(a.data[this.detailDataFieldName].order_molds || []));
          if (a.data[this.detailDataFieldName].auditor_uid) {
            this.pageStatus = 'approved';
          }
          this.setPageReadonly(this.pageStatus == 'approved');
          this.detailsDataInit();

        });

        this.isEdit = true;


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



    },

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

      });
    },




    heightInit() {

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

        this.table1Height = h;
      });

    },
    detailsDataInit() {
      for (let i = this.detailsData && 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: "/Mold/MoldOrderAdd"
        });
      } else {
        // 如果是编辑模式，关闭当前页面
        this.$closePage({
          closeRoute: "/Mold/MoldOrderUpdate"
        });
      }
      // 打开列表页面
      this.$openPage('/Mold/MoldOrder')
    },



    // 保存
    ok() {



      let save = () => {


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


        postdata.order_molds = this.$mk.getPostFieldValue({
          rowFilter: (row) => { return row.id || row.mold_id },
          dataId: this.getDataId_BigInt(),
          list: this.detailsData,
          deletedList: this.deletedDetailsData,
          fieldName: 'order_id',
          dataRule: [
            { field: 'id', type: 'bigint' },
            { field: 'production_type', type: 'integer' },
            { field: 'manufacture_cycle', type: 'timestamp' },
            { field: 'draw_start_time', type: 'timestamp' },
            { field: 'split_design_time', type: 'timestamp' },
            { field: 'draw_time', type: 'timestamp' },
            { field: 'draw2D_time', type: 'timestamp' },
            { field: 'draw3D_time', type: 'timestamp' },
            { field: 'horizontal_frame_time', type: 'timestamp' },
            { field: 'inlay_deep_hole_time', type: 'timestamp' },
            { field: 'update_uid', type: 'bigint' },
            { field: 'mold_id', type: 'bigint' },
            { field: 'mold_master_uid', type: 'bigint' },


            { field: 'create_uid', type: 'bigint' }
          ]
        });

        // 格式化提交的数据
        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") {


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

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


        });


      };





      // 验证表单
      this.$mk.validateForm({ form: this.$refs.xForm }).then(() => { // 验证表单

        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 (this.pageStatus == "approved") {
        return false;
      }
      console.log(column, row);
      return true;
    },
    afterEditEvent({ column, row }) {
      console.log(column, row);
    },
    beforeEditEvent({ column, row }) {
      console.log(column, row);
    },
    onPulldownSelected({ row, name, params }) {
      console.log(row, name, params);

    },
    onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },

    pageApproved() {
      let dataId = this.getDataId();
      if (!dataId) {
        return;
      }


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

      sendApproved("");

    },

  },
  // 监听属性
  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>
