<template>
  <el-card
    v-loading="loading"
    :body-style="{
      height: '100%',
      padding: 0,
      display: 'flex',
      'flex-direction': 'column',
    }"
  >
    <el-super-search
      v-model="params"
      :size="size"
      :dict="dict"
      :columns="SearchColumns"
      @reset="resetList"
      @submit="getList({ ...page, ...params })"
    ></el-super-search>

    <div style="margin: 16px 0">
      <el-super-ux-table
        v-model="tableList"
        :size="size"
        :dict="dict"
        :page="page"
        :columns="TableColumns"
        :height="tableHeight"
        index
        pagination
        highlight-current-row
        storage-key="workSpaceSuperTable"
        @selection-change="(selection) => (ids = selection)"
        @row-click="rowSelect"
        @pagination="getList({ ...page, ...params })"
      >
        <ux-table-column fixed="right" title="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button type="text" :size="size" @click.stop="check(scope.row)"
              >查看</el-button
            >
            <el-button type="text" :size="size" @click.stop="audit(scope.row)"
              >审批</el-button
            >
            <el-button type="text" :size="size" @click.stop="reject(scope.row)"
              >驳回</el-button
            >
          </template>
        </ux-table-column>
      </el-super-ux-table>
    </div>

    <el-tabs v-model="tabName">
      <el-tab-pane label="单据概述" name="first">
        <el-super-ux-table
          v-if="cols.length !== 0"
          v-loading="loading"
          v-model="sonTableList"
          :size="size"
          :dict="dict"
          :page="tabPage"
          :columns="cols"
          :height="tabHeight"
          :key="checkRow.type"
          index
          pagination
          highlight-current-row
          @pagination="getDetailList(checkRow)"
        >
        </el-super-ux-table>
        <el-empty v-else :image-size="80" description="暂无数据"></el-empty>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script>
import {
  getWorkSpaceList,
  auditWork,
  getWorkDetailList,
  oaBack,
} from "@/api/purchase/workSpace.js";
import useColumns from "./columns";
import { dicts } from "./dicts";
export default {
  name: "workSpace",
  dicts: [...dicts],
  components: {
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElSuperSearch: () => import("@/components/super-search/index.vue"),
  },
  data() {
    const page = this.$init.page();
    const {
      SearchColumns,
      TableColumns,
      PU_DEMAND_RULE,
      ALLOT_RULE,
      MATERIAL_APPLY_RULE,
      PU_PRICE_APPLY_RULE,
      PU_ORDER_RULE,
    } = useColumns();
    const params = this.$init.params(SearchColumns);
    return {
      page: page,
      tabPage: page,
      Columns: {
        PU_DEMAND_RULE,
        ALLOT_RULE,
        MATERIAL_APPLY_RULE,
        PU_PRICE_APPLY_RULE,
        PU_ORDER_RULE,
      },
      size: "mini",
      SearchColumns,
      TableColumns,
      params,
      tabName: "first",
      loading: false,
      tableList: [],
      ids: [],
      sonTableList: [],
      checkRow: {
        billCode: "",
        type: "",
      },
      cols: [],
      // 记录点击行的下标
      recordIndex: "",
    };
  },
  computed: {
    tableHeight: {
      get() {
        return `${
          this.tableList.length
            ? this.tableList.length > 9
              ? 350
              : this.tableList.length * 36 + 36
            : 120
        }px`;
      },
      set() {},
    },
    tabHeight: {
      get() {
        return `${
          this.sonTableList.length
            ? this.sonTableList.length > 5
              ? 300
              : this.sonTableList.length * 36 + 60
            : 120
        }px`;
      },
      set() {},
    },
  },
  created() {
    this.resetList();
  },
  methods: {
    async getList(params) {
      try {
        this.$modal.loading("加载中...");
        let { code, rows, total } = await getWorkSpaceList(params);
        if (code === 200) {
          this.tableList = rows;
          this.page.total = total;
        }
      } catch (error) {
      } finally {
        this.$modal.closeLoading();
      }
    },
    resetList() {
      this.params = this.$init.params(this.SearchColumns);
      this.page = this.$init.page();
      this.getList({ ...this.page, ...this.params });
    },
    // doubleClick(row) {
    //   this.rowSelect(row);
    // },
    rowSelect(row, column, event) {
      // this.recordIndex = this.tableList.findIndex((value, index ,arr) => {
      //   return value.billCode == row.billCode
      // })
      // this.check(row)
      // 选择行存储便于子表分页
      this.checkRow = row;
      this.cols = [...this.Columns[row.type]];
      this.getDetailList(this.checkRow);
    },
    audits() {
      if (this.ids.length == 0) {
        this.$modal.notifyWarning("请选中至少一条数据");
      } else {
        this.$modal
          .confirm("确认审批选中单据?")
          .then(() => {
            this.$modal.loading("审批中...");
            auditWork(this.ids).then((res) => {
              if (res.code === 200) {
                this.$modal.closeLoading();
                this.$modal.notifySuccess("审批成功");
                this.getList({ ...this.page, ...this.params });
                this.sonTableList = [];
              }
            });
          })
          .catch(() => {
            this.$modal.closeLoading();
            this.getList({ ...this.page, ...this.params });
            this.sonTableList = [];
          });
      }
    },
    check(row) {
      this.$router.push({
        path: row.linkUrl,
        query: { billCode: row.billCode },
      });
    },
    audit(row) {
      this.$modal.loading("审批中...");
      auditWork([row])
        .then((res) => {
          if (res.code === 200) {
            this.$modal.closeLoading();
            this.$modal.notifySuccess("审批成功");
            this.getList({ ...this.page, ...this.params });
            this.sonTableList = [];
          }
        })
        .catch(() => {
          this.$modal.closeLoading();
          this.getList({ ...this.page, ...this.params });
          this.sonTableList = [];
        });
    },
    // 驳回
    reject(row) {
      this.$prompt(
        "<div>请填写驳回原因 <span style='color:#ff6262'>注：只能驳回到起草节点</span></div>",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /\s*\S+?/,
          inputErrorMessage: "驳回原因不能为空",
          dangerouslyUseHTMLString: true,
        }
      )
        .then(async ({ value }) => {
          try {
            this.$modal.loading("加载中...");
            let params = {
              checkAmount: false,
              fdTemplateId: row.fdTemplateId,
              fdId: row.fdId,
              billCode: row.billCode,
              backReason: value,
            };
            console.log(params, "params");
            const { msg, code } = await oaBack(params);
            if (code === 200) {
              this.$emit("success");
              this.$notify.success(msg);
            }
          } catch (error) {
          } finally {
            this.$modal.closeLoading();
          }
        })
        .catch(() => {
          this.$modal.closeLoading();
        });
    },

    // 获取单据概述列表
    async getDetailList(row) {
      try {
        this.loading = true;
        let param = {
          billCode: row.billCode,
          type: row.type,
          ...this.tabPage,
        };
        let { code, rows, total } = await getWorkDetailList(param);
        if (code === 200) {
          this.sonTableList = rows;
          this.tabPage.total = total;
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.el-card {
  width: calc(100% - 32px);
  height: calc(100vh - 32px);
  margin: 16px;
  padding: 16px;
  border-radius: 8px;
  overflow-y: auto;
  overflow-x: hidden;
}

.el-button-group + .el-button-group {
  margin: 0 0 0 8px;
}
</style>
