<script>
import useColumns from "./columns";
import { toOA } from "@/api/purchase/purchaseDemand.js";
import { REFER } from "@/components/popover-select/api";
import {
  addOrder,
  getOrderDetail,
  editOrder,
  submitOrder,
  againToNC,
} from "@/api/purchase/transferOrder.js";
export default {
  name: "AddTransfer",
  props: {
    addType: {
      type: String,
      default: "add",
    },
    dict: {
      type: Object,
    },
    data: {
      tyep: Object,
    },
  },
  components: {
    ElSuperForm: () => import("@/components/super-form/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
    ReservedButton: () => import("../reserved/index.vue"),
  },
  data() {
    const {
      FormColumns,
      TabColumns,
      TabColumns: [
        {
          item: { key: tabName },
        },
      ],
    } = useColumns();
    const params = this.$init.params([...TabColumns, ...FormColumns]);
    const rules = this.$init.rules([...TabColumns, ...FormColumns]);
    return {
      rules,
      params: {
        ...params,
        dwCsFlag: null,
        swCsFlag: null,
      },
      tabName,
      TabColumns,
      FormColumns,
      size: "mini",
      width: "100%",
      count: 0,
      loading: false,
      visible: false,
      control: false,
    };
  },
  computed: {
    title: {
      get() {
        const { addType } = this.$props;
        if (addType === "edit") {
          return "编 辑";
        } else if (addType === "see") {
          return "查 看";
        } else {
          return "新 增";
        }
      },
      set() {},
    },
    tabInfo: {
      get() {
        const {
          stAllotMaterialList,
          stAllotReceiveDeliverList,
          stAllotReceiveExecuteList,
          stAllotReceiveExpenseList,
        } = this.params;
        return {
          stAllotMaterialList: stAllotMaterialList.filter(
            ({ delFlag }) => delFlag !== "2"
          ),
          stAllotReceiveDeliverList,
          stAllotReceiveExecuteList,
          stAllotReceiveExpenseList,
        };
      },
      set() {},
    },
    tableHeight: {
      get() {
        return window.innerHeight - 430;
      },
      set() {},
    },
  },
  watch: {
    // 调出库存组织
    "params.deliveryInventoryOrgName": {
      handler: function (nVal, oVal) {
        this.control &&
          (this.params = {
            ...this.params,
            deliveryWarehouse: null,
            deliveryWarehouseCode: null,
            deliveryWarehouseName: null,
            deliveryDept: null,
            deliveryDeptCode: null,
            deliveryDeptName: null,
          });
      },
    },
    // 调入库存组织
    "params.storageInventoryOrgName": {
      handler: function (nVal, oVal) {
        this.control &&
          (this.params = {
            ...this.params,
            storageWarehouse: null,
            storageWarehouseName: null,
            stAllotMaterialList: this.params["stAllotMaterialList"].map(
              (item) => ({
                ...item,
                storageDept: null,
                storageDeptCode: null,
                storageDeptName: null,
              })
            ),
          });
      },
    },
    // 调出仓库
    "params.deliveryWarehouseName": {
      handler: function (nVal, oVal) {
        this.control &&
          (this.params = {
            ...this.params,
            stAllotMaterialList: this.params["stAllotMaterialList"].map(
              (item) => ({
                ...item,
                deliveryAllocation: null,
                deliveryAllocationCode: null,
                deliveryAllocationName: null,
              })
            ),
          });
      },
    },
    // 调入仓库
    "params.storageWarehouseName": {
      handler: function (nVal, oVal) {
        this.control &&
          (this.params = {
            ...this.params,
            stAllotMaterialList: this.params["stAllotMaterialList"].map(
              (item) => ({
                ...item,
                storageAllocation: null,
                storageAllocationCode: null,
                storageAllocationName: null,
              })
            ),
          });
      },
    },
  },
  methods: {
    setVisible(prop) {
      this.visible = prop;
    },
    //
    hide() {
      const {
        FormColumns,
        TabColumns,
        TabColumns: [
          {
            item: { key: tabName },
          },
        ],
      } = useColumns();
      this.params = {
        ...this.$init.params([...TabColumns, ...FormColumns]),
        dwCsFlag: null,
        swCsFlag: null,
      };
      this.control = false;
      this.tabName = tabName;
      this.TabColumn = TabColumns;
      this.$refs["superForm"].clearValidate();
      this.visible = false;
      this.$emit("refresh");
    },
    //
    async beforeOpen() {
      const { data, addType } = this.$props;
      if (!data.id) {
        // 新增
        const { name, nickName } = this.$store.state.user;
        this.params = {
          ...this.params,
          status: "0",
          createBy: name,
          createByName: nickName,
          billDate: new Date().Format("yyyy-MM-dd"),
          createTime: new Date().Format("yyyy-MM-dd HH:mm:ss"),
        };
        this.control = true;
        this.useRowAdd(this.tabName);
      } else {
        await this.fetchItem(data);
        this.$nextTick(async () => {
          // 复制
          if (addType === "add") {
            const { name, nickName } = this.$store.state.user;
            this.params = {
              ...this.params,
              id: "",
              code: "",
              oaId: "",
              ncCode: "",
              status: "0",
              sendNcRes: "",
              updateBy: "",
              updateByName: "",
              updateTime: "",
              storageCode: "",
              deliveryCode: "",
              createBy: name,
              createByName: nickName,
              billDate: new Date().Format("yyyy-MM-dd"),
              createTime: new Date().Format("yyyy-MM-dd HH:mm:ss"),
              stAllotMaterialList: this.params.stAllotMaterialList.map(
                (item) => ({
                  ...item,
                  id: "",
                  allotId: "",
                  allotDate: "",
                  deliveryCode: "",
                  storageCode: "",
                  createBy: name,
                  createByName: nickName,
                  updateBy: null,
                  updateByName: null,
                  createTime: new Date().Format("yyyy-MM-dd HH:mm:ss"),
                  updateTime: null,
                })
              ),
            };
          }
          this.control = true;
          // 调入/出货位禁用——根据调入/出仓库
          const { deliveryWarehouse, storageWarehouse } = this.params;
          this.params.dwCsFlag = await this.fetchWarehouse(deliveryWarehouse);
          this.params.swCsFlag = await this.fetchWarehouse(storageWarehouse);
        });
      }
    },
    // 查询仓库
    async fetchWarehouse(id) {
      try {
        let { code, rows } = await REFER(
          {
            type: "WAREHOUSE_PARAM",
            search: "",
            id,
            isPage: true,
          },
          { pageNum: 1, pageSize: 10 }
        );
        return rows[0] ? rows[0].csFlag : null;
      } catch (error) {}
    },
    //
    async fetchItem(prop) {
      try {
        this.loading = true;
        const { addType } = this.$props;

        let { code, data, msg } = await getOrderDetail(prop.id);
        if (code == 200) {
          this.params = {
            ...this.params,
            ...data,
          };
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    // 增行
    useRowAdd(prop) {
      const { TableColumns } = this.TabColumns.find(
        ({ item: { key } }) => key === prop
      );

      let tabList = this.params[prop];
      let length = tabList.length;

      this.params[prop].push({
        ...this.$init.params(TableColumns),
        delFlag: "0",
        rowno: length ? Number(tabList[length - 1]["rowno"]) + 10 : length + 10,
      });
    },
    // 删行
    useRowRemove(prop, { row }) {
      if (this.tabInfo[prop].length < 2) {
        this.$notify.warning("明细至少保留一行数据");
        return;
      }
      this.params[prop].forEach((item, index) => {
        if (item["rowno"] && item["rowno"] == row["rowno"]) {
          item.id
            ? (item["delFlag"] = "2")
            : this.params[prop].splice(index, 1);
        }
      });
      this.changeQty();
    },
    // 保存
    useSave(prop) {
      console.log(this.params);
      this.$refs[prop].validate(async (valid, obj) => {
        if (valid) {
          try {
            this.$modal.loading("处理中，请稍后...");
            const { params, addType } = this;
            let { code, msg } =
              addType === "add"
                ? await addOrder(params)
                : await editOrder(params);
            if (code == 200) {
              this.$notify.success(msg);
              this.hide();
            }
          } catch (error) {
          } finally {
            this.$modal.closeLoading();
          }
        } else {
          let fail = [];
          for (let key in obj) {
            fail.push(obj[key][0].message);
          }
          this.$notify.warning({
            title: "警告",
            message: fail[0],
          });
          return false;
        }
      });
    },
    // 提交
    async useCommit(prop) {
      this.$modal.confirm("是否确认提交?").then(async () => {
        try {
          this.$modal.loading("处理中，请稍后...");
          let { code, msg } = await submitOrder(this.params);
          if (code == 200) {
            this.$notify.success(msg);
            this.hide();
          }
        } catch (error) {
        } finally {
          this.$modal.closeLoading();
        }
      });
    },
    // 流程跳转
    async useJumpOA() {
      try {
        const {
          $store: {
            state: { user },
          },
          params,
        } = this;
        let { code, oaUrl } = await toOA(user.name, params.oaId);
        if (code == 200) {
          window.open(oaUrl);
        }
      } catch (error) {}
    },
    // 重传NC
    async sendToNC() {
      try {
        this.$modal.loading("处理中，请稍后...");
        let { code, msg } = await againToNC(this.params);
        if (code == 200) {
          this.$notify.success(msg);
          this.hide();
        }
      } catch (error) {
      } finally {
        this.$modal.closeLoading();
      }
    },
    // 子表数量改变
    changeQty(tabName) {
      this.params.qty = this.params["stAllotMaterialList"].reduce(
        (sum, item) => {
          if (item.delFlag !== "2") {
            sum += item.qty;
          }
          return sum;
        },
        0
      );
    },
  },
  created() {},
};
</script>

<template>
  <el-drawer
    v-loading="loading"
    v-bind="$attrs"
    v-on="$listeners"
    :size="width"
    :show-close="false"
    :visible.sync="visible"
    destroy-on-close
    @close="hide"
    @open="beforeOpen"
  >
    <div
      slot="title"
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>{{ title }}</h3>
      <div>
        <el-button
          v-if="addType !== 'see'"
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="useSave('superForm')"
          >保 存</el-button
        >

        <el-button-group v-else style="margin: 0 8px">
          <el-button
            v-show="params.status == '0' || params.status == '3'"
            type="primary"
            :size="$attrs.size"
            :loading="loading"
            @click="useCommit('superForm')"
            >提 交</el-button
          >
          <el-button
            type="primary"
            :size="size"
            @click="sendToNC"
            v-show="params.status == '2' && !params.ncCode"
            >重传NC</el-button
          >
          <el-button
            :size="$attrs.size"
            @click="useJumpOA"
            v-show="
              (params.status == '1' || params.status == '2') && params.oaId
            "
            >流程跳转</el-button
          >
        </el-button-group>

        <el-button :size="$attrs.size" :loading="loading" @click="hide"
          >取 消</el-button
        >
      </div>
    </div>
    <el-super-form
      v-model="params"
      :dict="dict"
      :rules="rules"
      :size="$attrs.size"
      :columns="FormColumns"
      ref="superForm"
      label-width="auto"
      label-position="right"
      style="padding: 20px"
      :disabled="addType === 'see'"
    >
      <!-- 调出仓库 -->
      <template slot="deliveryWarehouseName" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="$attrs.size"
          :source.sync="scope.row"
          :disabled="!params.deliveryInventoryOrg"
        >
        </component
      ></template>
      <!-- 调出部门 -->
      <template slot="deliveryDeptName" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="$attrs.size"
          :source.sync="scope.row"
          :disabled="!params.deliveryInventoryOrg"
        >
        </component
      ></template>
      <!-- 调入仓库 -->
      <template slot="storageWarehouseName" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="$attrs.size"
          :source.sync="scope.row"
          :disabled="!params.storageInventoryOrg"
        >
        </component
      ></template>
    </el-super-form>

    <div style="position: relative">
      <el-tabs v-model="tabName" style="padding: 0 20px 20px">
        <el-tab-pane
          v-for="({ item, TableColumns: columns }, index) in TabColumns"
          :key="index"
          :label="item.title"
          :name="item.key"
          lazy
        >
          <el-super-ux-table
            v-model="tabInfo[item.key]"
            index
            :dict="dict"
            :ref="tabName"
            :columns="columns"
            :size="$attrs.size"
            :height="tableHeight"
          >
            <!-- 物料编码 -->
            <template slot="materialCode" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                :disabled="addType === 'see'"
              >
              </component>
            </template>
            <!-- 数量 -->
            <template slot="qty" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                :disabled="addType === 'see'"
                @change="changeQty(tabName)"
              >
              </component>
            </template>
            <!-- 调入部门 -->
            <template slot="storageDeptName" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                :disabled="addType === 'see' || !params.storageInventoryOrg"
                :queryParams="
                  () => ({
                    drpOrg: params.storageInventoryOrg,
                  })
                "
              >
              </component>
            </template>
            <!-- 产品批号 -->
            <template slot="producBatch" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                :disabled="addType === 'see' || !scope.row['materialCode']"
              >
              </component>
            </template>
            <!-- 调出货位 -->
            <template slot="deliveryAllocationName" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                :disabled="
                  addType === 'see' ||
                  !params.dwCsFlag ||
                  params.dwCsFlag === 'N'
                "
                :queryParams="
                  () => ({
                    stordocId: params.deliveryWarehouse,
                  })
                "
              >
              </component>
            </template>
            <!-- 调入货位 -->
            <template slot="storageAllocationName" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                :disabled="
                  addType === 'see' ||
                  !params.swCsFlag ||
                  params.swCsFlag === 'N'
                "
                :queryParams="
                  () => ({
                    stordocId: params.storageWarehouse,
                  })
                "
              >
              </component>
            </template>
            <ux-table-column
              v-if="tabName === 'stAllotMaterialList'"
              fixed="right"
              title="操作"
              width="80"
              align="center"
            >
              <template slot="header" slot-scope="scope">
                <el-button
                  type="text"
                  :size="$attrs.size"
                  :disabled="addType === 'see'"
                  @click="useRowAdd(tabName)"
                >
                  增行
                </el-button>
              </template>
              <template slot-scope="scope">
                <el-button
                  type="text"
                  :size="$attrs.size"
                  :disabled="addType === 'see'"
                  @click.native.prevent="useRowRemove(tabName, scope)"
                >
                  删除
                </el-button>
              </template>
            </ux-table-column>
          </el-super-ux-table>
        </el-tab-pane>
      </el-tabs>

      <div style="position: absolute; top: 5px; right: 20px">
        <reserved-button
          v-show="addType === 'see'"
          type="primary"
          :info="data"
          :size="$attrs.size"
        />
      </div>
    </div>
  </el-drawer>
</template>

<style scoped>
>>> .el-drawer__header {
  margin-bottom: 0;
  padding: 5px 20px;
}
</style>
