<script>
import { LIST } from "@/api/business/purchase/task";
import { TableColumns, SearchColumns } from "./column";

const initParams = (prop, key = "key", value = "value") => {
  // get params
  const object1 = Object.fromEntries(
    prop.map(({ item, attr }) => [item[key], attr[value]])
  );
  // get mapping params
  const object2 = {};
  prop
    .filter((item) => item.attr.dataMapping)
    .map(({ attr: { dataMapping } }) => {
      for (let key in dataMapping) {
        object2[key] = null;
      }
    });
  return { ...object1, ...object2 };
};

// 初始化字典
const initDicts = (prop) =>
  Array.from(
    new Set(
      prop
        .filter((item) => item.attr.dictName)
        .map((item) => item.attr.dictName)
    )
  );

export default {
  name: "PuchaseTask",
  dicts: [...initDicts([...TableColumns, ...SearchColumns])],
  components: {
    SeeModel: () => import("./see/index.vue"),
    CloseModel: () => import("./close/index.vue"),
    ExportModel: () => import("./export/index.vue"),
    ShiftModel: () => import("./modify-buyer/index.vue"),
    DirectModel: () => import("./first-direct/index.vue"),
    ReturnModel: () => import("./documents-return/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
    ElPopoverMultipleSelectV2: () =>
      import("@/components/popover-select-v2/multiple.vue"),
  },
  data() {
    return {
      size: "mini",
      loading: false,
      searchColumns: SearchColumns,
      params: initParams(SearchColumns),
      tableData: [],
      selectData: [],
      tableColumns: TableColumns,
      page: { pageNum: 1, pageSize: 10, total: 0 },
    };
  },
  computed: {},
  watch: {},
  provide() {
    return {
      initParams,
      $dicts: () => this.dict.type,
    };
  },
  created() {
    this.params.status = "0";
    this.useQuery(this.params, this.page);
  },
  methods: {
    //
    setSelectable(row) {
      const { status } = row;
      if (status === "1") {
        // 已执行协议直采
        return false;
      } else {
        return true;
      }
    },
    //
    async fetchList(prop, page) {
      try {
        this.loading = true;
        const { code, rows, total } = await LIST(prop, page);
        if (code === 200) {
          this.tableData = rows;
          this.page.total = total;
        }
      } catch (err) {
        // catch
      } finally {
        // finally
        this.loading = false;
      }
    },
    // 查 询
    async useQuery(prop, page) {
      const { pageNum, pageSize } = page;
      const { date, documentsCodes: code } = prop;
      const [startDate, endDate] = date || [];
      const documentsCodes = code
        ? code.replace(/\s*/g, "").replaceAll("，", ",")
        : undefined;
      await this.fetchList(
        {
          ...prop,
          endDate,
          startDate,
          documentsCodes,
          date: undefined,
        },
        { pageNum, pageSize, isAsc: "desc", orderByColumn: "updateTime" }
      );
    },
    // 重 置
    useReset() {
      this.page.pageNum = 1;
      this.page.pageSize = 10;
      this.params = initParams(SearchColumns);
      this.useQuery(this.params, this.page);
    },
    // 选 择
    useSelect(prop) {
      this.selectData = prop;
    },
    // 行 关
    async useClose(prop) {
      const { open } = this.$refs.CloseModel;
      await open(prop);
    },
    // 退 回
    async useReturn(prop) {
      const { open } = this.$refs.ReturnModel;
      await open(prop);
    },
    hasPowerReturn(prop) {
      return !!prop.length;
    },
    // 转 派
    async useShift(prop) {
      const { id } = prop;
      const { open } = this.$refs.ShiftModel;
      await open(id);
    },
    hasPowerShift(prop) {
      return prop.length === 1;
    },
    // 明 细
    async useSee(prop) {
      const { id } = prop;
      const { open } = this.$refs.SeeModel;
      await open(id);
    },
    // 直 采
    async useDirect(prop) {
      console.log(this);
      const { open } = this.$refs.DirectModel;
      await open(prop);
    },
    hasPowerDirect(prop) {
      if (prop.length === 1) {
        const [{ status }] = prop;
        if (status === "1") return false;
        else return true;
      } else {
        return !!prop.length;
      }
    },
    // 导 出
    async useExport(prop, page) {
      const { open } = this.$refs.ExportModel;
      await open(prop, page);
    },
  },
};
</script>

<template>
  <el-card v-loading="loading" :body-style="{ padding: 0 }">
    <see-model ref="SeeModel"></see-model>
    <export-model ref="ExportModel"></export-model>
    <close-model
      ref="CloseModel"
      @success="useQuery(params, page)"
    ></close-model>
    <shift-model
      ref="ShiftModel"
      @success="useQuery(params, page)"
    ></shift-model>
    <direct-model
      ref="DirectModel"
      @success="useQuery(params, page)"
    ></direct-model>
    <return-model
      ref="ReturnModel"
      @success="useQuery(params, page)"
    ></return-model>
    <el-form
      :size="size"
      :model="params"
      label-width="auto"
      label-position="right"
      @submit.native.prevent
    >
      <el-row :gutter="20">
        <el-col
          v-for="column in searchColumns"
          :key="column.item.title"
          :span="column.item.span || 6"
        >
          <el-form-item :prop="column.item.key" :label="column.item.title">
            <component
              v-if="column.attr.referName"
              v-bind="column.attr"
              v-model="params[column.item.key]"
              :source.sync="params"
              :is="column.attr.component"
              @change="useQuery(params, page)"
            ></component>
            <component
              v-else-if="column.attr.dictName"
              v-bind="column.attr"
              v-model="params[column.item.key]"
              :is="column.attr.component"
              @change="useQuery(params, page)"
              style="width: 100%"
            >
              <el-option
                v-for="item in dict.type[column.attr.dictName]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option
            ></component>
            <component
              v-else
              v-bind="column.attr"
              v-model="params[column.item.key]"
              :is="column.attr.component"
              @change="useQuery(params, page)"
              @keyup.enter.native="useQuery(params, page)"
            ></component>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-button :size="size" @click="useQuery(params, page)">
        查 询
      </el-button>
      <el-button :size="size" @click="useReset"> 重 置 </el-button>
      <!-- <el-button :size="size" @click="useExport(params, page)">
        导 出
      </el-button> -->
      <el-button
        v-show="hasPowerShift(selectData)"
        :size="size"
        @click="useShift(selectData[0])"
      >
        转 派
      </el-button>
      <el-button
        v-show="hasPowerReturn(selectData)"
        :size="size"
        @click="useReturn(selectData)"
      >
        退回需求
      </el-button>
      <!-- <el-button
          :size="size"
          :disabled="selectData.length !== 1"
          @click="useClose(selectData[0])"
        >
          行关闭
        </el-button> -->
      <el-button
        v-show="hasPowerDirect(selectData)"
        :size="size"
        @click="useDirect(selectData)"
      >
        协议直采
      </el-button>
    </el-row>
    <el-table
      :data="tableData"
      size="mini"
      highlight-current-row
      @row-dblclick="useSee"
      @selection-change="useSelect"
      @row-click="useSelect([$event])"
    >
      <el-table-column
        fixed
        width="55"
        align="center"
        type="selection"
        :selectable="setSelectable"
      >
      </el-table-column>
      <el-table-column
        v-for="(column, index) in tableColumns"
        :key="index"
        :prop="column.item.key"
        :label="column.item.title"
        :width="column.item.width || 200"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <dict-tag
            v-if="column.attr.dictName"
            :size="size"
            :value="scope.row[column.item.key]"
            :options="dict.type[column.attr.dictName]"
          />
          <component is="span" v-else>{{
            scope.row[column.item.key]
          }}</component>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="page.total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="useQuery(params, page)"
    />
  </el-card>
</template>

<style scoped lang="scss">
.el-card {
  width: calc(100% - 20px);
  height: 100%;
  margin: 10px;
  padding: 0 0 20px 0;
  .el-form {
    padding: 20px 0 0;
  }
  .el-row {
    display: flex;
    flex-wrap: wrap;
    padding: 0 20px;
  }
  ::v-deep .el-table--mini {
    width: 100%;
    margin: 20px 0 0 0;
    .el-table__cell {
      height: 50px;
    }
  }
}
</style>
