<template>
  <div>
    <div class="customer-head">
      <div class="customer-back">
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                   @click="backToList(0)">返回列表
        </el-button>
      </div>
      <div class="add-customer-btn">
        <!--        <el-button class="el-button&#45;&#45;small-yh" style="margin-right: 10px" type="primary" size="small" v-if="!editButton"-->
        <!--                   @click="confirmEditing">编辑-->
        <!--        </el-button>-->
        <el-button
            class="el-button--small-yh"
            type="primary"
            size="small"
            @click="editCustomer">保存数据
        </el-button>
        <el-button
            class="el-button--small-yh"
            type="success"
            size="small"
            v-if="form.statusName == '待入库'"
            @click="complete">入库完成
        </el-button>
      </div>
    </div>
    <div style="margin-top: 50px">
      <trade-card title="基础信息">
        <avue-form :option="optionForm" v-model="form" ref="form"></avue-form>
      </trade-card>
      <trade-card title="明细信息">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="出库明细" name="sale_detail">
            <avue-crud :option="optionContacts" v-model="formContacts" ref="formContacts" :data="form.shipItemsList"
                       :key="key"
                       @row-save="rowSave"
                       @row-update="rowUpdate"
                       @resetColumn="resetColumnTwo('formContacts','optionContacts','optionContactsBack',274.1)"
                       @saveColumn="saveColumnTwo('formContacts','optionContacts','optionContactsBack',274.1)">
              <template slot-scope="{type,size,row,index,disabled}" slot="menu">
                <el-button
                    :size="size" :disabled="disabled" :type="type"
                    :icon="row.$cellEdit?'el-icon-plus':'el-icon-edit'"
                    @click="$refs.formContacts.rowEdit(row,index)"
                >编辑
                </el-button>
                <el-button icon="el-icon-delete" :size="size" :disabled="disabled" :type="type"
                           @click="rowDelBox(row,index)">删除
                </el-button>
              </template>
            </avue-crud>
          </el-tab-pane>
          <el-tab-pane label="订单信息" name="payment_details">
            <avue-crud :option="optionPaymentDetails" v-model="formContacts" ref="payment_details"
                       :data="form.shipVOList"
                       :key="key"
                       @resetColumn="resetColumnTwo('payment_details','optionPaymentDetails','optionPaymentDetailsBack',274.2)"
                       @saveColumn="saveColumnTwo('payment_details','optionPaymentDetails','optionPaymentDetailsBack',274.2)">
            </avue-crud>
          </el-tab-pane>
          <el-tab-pane label="历史记录" name="outbound_records">
            <avue-crud :option="optionOutboundRecords" v-model="formContacts" ref="outbound_records"
                       :data="form.historyList"
                       :key="key"
                       @resetColumn="resetColumnTwo('outbound_records','optionOutboundRecords','optionOutboundRecordsBack',274.3)"
                       @saveColumn="saveColumnTwo('outbound_records','optionOutboundRecords','optionOutboundRecordsBack',274.3)">
            </avue-crud>
          </el-tab-pane>
        </el-tabs>
      </trade-card>
    </div>
  </div>
</template>

<script>

import {getDetails, tradingBox, submit, warehousingComplete} from "@/api/tirePartsMall/purchasingManagement/warehouseEntryOrder";
import {dateFormat} from "@/util/date";

export default {
  name: "detailsPage",
  data() {
    return {
      activeName: "sale_detail",
      disabled: false,
      form: {
        shipItemsList: [],
        shipVOList: [],
        historyList: []
      },
      key: 0,
      optionForm: {
        disabled: false,
        menuBtn: false,
        labelWidth: 100,
        columnBtn: false,
        span: 8,
        column: [
          {
            label: "入库单号",
            prop: "ordNo",
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              }
            ],
          },
          {
            label: "来源单号",
            prop: "srcOrdNo"
          }, {
            label: "业务对象",
            prop: "customerId",
            type: 'select',
            props: {
              label: 'cname',
              value: 'id'
            },
            dicUrl: '/api/blade-sales-part/corpsDesc/listAll?corpType=GYS',
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              }
            ]
          }, {
            label: "仓库",
            prop: "storageId",
            search: true,
            overHidden: true,
            type: 'select',
            dicUrl: "/api/blade-sales-part/storageDesc/listAll",
            props: {
              label: 'cname',
              value: 'id'
            },
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              }
            ]
          }, {
            label: "商品数量",
            prop: "goodsTotalNum",
            search: false,
            overHidden: true,
            // width: 120,
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              }
            ]
          }, {
            label: "业务日期",
            prop: "createTime",
            type: "datetime",
            value: dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
            format: "yyyy-MM-dd HH:mm",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ]
          }, {
            label: '库管',
            prop: "stockClerkId",
            type: 'select',
            props: {
              label: 'realName',
              value: 'id'
            },
            dicUrl: '/api/blade-user/stockClerkList',
            rules: [{
              required: true,
              message: " ",
              trigger: "blur"
            }]
          }, {
            label: '备注',
            prop: "remarks",
            type: 'textarea',
            span: 16,
            minRows: 1
          }
        ]
      },
      formContacts: {},
      optionContacts: {},
      optionContactsBack: {
        align: "center",
        addBtn: true,
        addBtnText: "录入明细",
        refreshBtn: false,
        editBtn: false,
        delBtn: false,
        border: true,
        menuWidth: 120,
        stripe: true,
        index: true,
        menu: true,
        dialogTop: 25,
        dialogWidth: "80%",
        column: [{
          label: '物料编码',
          prop: 'goodsNo',
          width: 100
        }, {
          label: '商品名称',
          prop: 'goodsId',
          width: 200,
          overHidden: true,
          filterable: true,
          type: 'select',
          props: {
            label: 'cname',
            value: 'id'
          },
          dicUrl: '/api/blade-sales-part/goodsDesc/goodsListAll'
        }, {
          label: "品牌",
          prop: 'brandId',
          width: 100,
          overHidden: true,
          type: 'select',
          props: {
            label: 'cname',
            value: 'id'
          },
          dicUrl: '/api/blade-sales-part/brandDesc/listAll'
        }, {
          label: "规格型号",
          prop: "propertyName",
          overHidden: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: "花纹",
          prop: "pattern",
          overHidden: true
        }, {
          label: "商品描述",
          prop: "goodsDescription",
          overHidden: true
        }, {
          label: "批次号",
          prop: "dot",
          overHidden: true
        }, {
          label: "单位",
          prop: 'units',
          type: "select",
          props: {
            label: "dictValue",
            value: "dictValue"
          },
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=unit"
        }, {
          label: "单价",
          prop: "price",
          ovrHidden: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: "入库数量",
          prop: "goodsNum",
          ovrHidden: true
        }, {
          label: "实际数量",
          prop: "sendNum",
          overHidden: true,
        }, {
          label: "备注",
          prop: "remarks",
          overHidde: true
        }]
      },
      optionPaymentDetails: {},
      optionPaymentDetailsBack: {
        align: "center",
        addBtn: false,
        refreshBtn: false,
        editBtn: false,
        delBtn: false,
        border: true,
        menuWidth: 120,
        stripe: true,
        index: true,
        menu: false,
        column: [
          {
            label: "入库单号",
            prop: "billno",
            disabled: true
          },
          {
            label: "来源单号",
            prop: "ordNo",
            disabled: true
          },
          {
            label: "业务来源",
            prop: "stockTime",
            type: "date",
            searchRange: true,
            searchDefaultTime: [
              "00:00:00",
              "23:59:59"
            ],
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            overHidden: true
          },
          {
            prop: "itemId",
            label: "地址",
            type: "select",
            props: {
              label: "cname",
              value: "id"
            },
            dicData: [],
            overHidden: true,
            filterable: true,
            rules: [
              {
                required: true,
                message: "请选择",
                trigger: "blur"
              }
            ]
          },
          {
            prop: "length",
            label: "联系人",
            overHidden: true
          },
          {
            prop: "thickness",
            label: "电话",
            overHidden: true
          },
          {
            prop: "remarks",
            label: "备注",
            overHidden: true,
            cell: true
          }
        ]
      },
      optionOutboundRecords: {},
      optionOutboundRecordsBack: {
        align: "center",
        addBtn: false,
        refreshBtn: false,
        editBtn: false,
        delBtn: false,
        border: true,
        menuWidth: 120,
        index: true,
        stripe: true,
        menu: false,
        column: [{
          prop: "operatorName",
          label: "操作人",
          overHidden: true,
          showColumn: false,
          width: 120,
        }, {
          prop: "operateStatus",
          label: "状态",
          overHidden: true,
        }, {
          prop: "operateTime",
          label: "时间",
          overHidden: true,
          searchDefaultTime: ["00:00:00", "23:59:59"],
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
        }]
      }
    }
  },
  props: {
    onLoad: Object,
    detailData: Object
  },
  async created() {
    this.optionContacts = await this.getColumnData(this.getColumnName(274.1), this.optionContactsBack);
    this.optionPaymentDetails = await this.getColumnData(this.getColumnName(274.2), this.optionPaymentDetailsBack);
    this.optionOutboundRecords = await this.getColumnData(this.getColumnName(274.3), this.optionOutboundRecordsBack);
    this.key++
    if (this.onLoad.id && this.detailData.id) {
      this.refresh(this.onLoad.id, true)
    } else if (this.onLoad.id) {
      this.refresh(this.onLoad.id, true)
    }
  },
  methods: {
    complete() {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(255,255,255,0.7)'
          });
          warehousingComplete({
            ...this.form,
            bizTypeName: "SHGD"
          }).then(res => {
            this.$message.success("保存成功");
            this.refresh(res.data.data.id)
            loading.close();
          }).finally(() => {
            loading.close();
          });
        }
      })
    },
    //修改提交触发
    editCustomer() {
      if (this.form.shipItemsList.length == 0){
        return this.$message.warning('请明细不能为空')
      }
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(255,255,255,0.7)'
          });
          submit({
            ...this.form,
            bizTypeName: "SHGD"
          }).then(res => {
            this.$message.success("保存成功");
            this.refresh(res.data.data.id);
            loading.close();
          }).finally(() => {
            loading.close();
          });
        } else {
          return false;
        }
      });
    },
    refresh(id, type) {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(255,255,255,0.7)'
      })
      getDetails({id: id}).then(res => {
        this.form = res.data.data
        loading.close();
      }).catch(() => {
        loading.close();
      })
    },
    rowDelBox(row, index) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          if (row.id) {
            tradingBox(row.id).then(res => {
              this.form.shipItemsList.splice(index, 1);
              this.$message.success("操作成功!");
            });
          } else {
            this.form.shipItemsList.splice(index, 1);
            this.$message.success("操作成功!");
          }
        }
      )
      ;
    },
    rowSave(form, done, loading) {
      console.log(form)
      done(form)
    },
    rowUpdate(form, index, done, loading) {
      console.log(form)
      done(form);
    },
    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口b
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    backToList(type) {
      this.$emit("backToList", type);
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 8px !important;
}
</style>
