<!-- 采购订单修订—— 查看 -->
<script>
import {
  initColumns,
  initDicts,
  initRules,
  initParams,
} from "@/utils/init/index.js";
// import { Columns, TabColumns } from "../add/column";
import orderApi from "@/api/business/purchase/purchase-order";
import { PRINT } from "@/api/business/purchase/task";
import judgeColumns from "../add/column";
import VirtualScroll from "el-table-virtual-scroll";
import { VirtualColumn } from "el-table-virtual-scroll";

const { Columns, TabColumns } = judgeColumns();

const NewColumns = initColumns(Columns);
const NewTabColumns = TabColumns.map((element) => ({
  ...element,
  tableColumns: initColumns(element.tableColumns).map((item, index) => ({
    ...item,
    hidden: true,
  })),
}));
//
const SelectColumns = NewColumns.filter(
  (column) => column.inputType === "Select"
);
NewTabColumns.forEach((column) => {
  SelectColumns.push(
    ...column.tableColumns.filter((cColumn) => cColumn.inputType === "Select")
  );
});

export default {
  name: "SeePurchaseOrderDrawer",
  dicts: initDicts(SelectColumns),
  components: {
    "virtual-scroll": VirtualScroll,
    VirtualColumn,
    FileUploadCenter: () => import("../components/FileUploadCenter/index.vue"),
    FilePrint: () => import("../print/index.vue"),
    ButtonHide: () => import("../components/hide/index.vue"),
  },
  data() {
    return {
      visible: false,
      loading: false,
      columns: NewColumns,
      printData: {},
      rules: initRules(NewColumns),
      params: {
        ...initParams(NewColumns),
        puOrderItemList: [],
        // puOrderExecuteList: [],
      },

      tabColumns: NewTabColumns,
      tabName: "puOrderItemList",
      tableData: [], //虚拟滚动加载显示的数据
      size: "mini",
    };
  },
  computed: {
    tabHeight: {
      get() {
        let length = this.params["puOrderItemList"].filter(
          (item) => item.delFlag === "0"
        ).length;
        return `${length ? (length > 8 ? 500 : length * 36 + 120) : 120}px`;
      },
      set() {},
    },
    innerColumns: {
      get() {
        let { tabName, tabColumns } = this;
        let obj = tabColumns.find(({ key }) => key === tabName).tableColumns;

        return obj;
      },
      set(value) {
        let { tabName, tabColumns } = this;
        this.tabColumns = tabColumns.map((item) => {
          if (item.key === tabName) {
            item.tableColumns = value;
          }
          return { ...item };
        });
        this.$nextTick(() => {
          this.$refs.puOrderItemList &&
            this.$refs.puOrderItemList[0].doLayout();
        });
      },
    },
  },
  watch: {},
  methods: {
    setVisible(prop) {
      this.visible = prop;

      if (!this.visible) {
        this.$refs["orderSeeForm"].clearValidate();
      }
    },

    //查询详情
    async fetchItem(prop) {
      try {
        this.loading = true;
        const { code, msg, data } = await orderApi.details(prop);
        if (code === 200) {
          this.params = data;
        }
      } catch (err) {
        //
      } finally {
        this.loading = false;
      }

      try {
        this.loading = true;
        const { data, code } = await PRINT({ id: this.params.id || 628 });
        if (code === 200) {
          this.printData = data;
          this.loading = false;
        }
      } catch (err) {
        alert(err);
      } finally {
      }
    },
    // 取 消
    handleCancel() {
      // this.params = initParams(Columns);
      this.params = {
        ...initParams(this.columns),
        puOrderItemList: [],
        // puOrderExecuteList: [],
      };
      this.setVisible(false);
    },
    handleRefresh() {
      let { id } = this.params;
      this.fetchItem(id);
    },
    // 发送NC
    async handleSendNC() {
      try {
        let { code } = await orderApi.toNc({ puOrderId: this.params.id });

        if (code == 200) {
          this.handleRefresh();
        }
      } catch (error) {
      } finally {
      }
    },
    // 判断是否能发送NC
    judgeIsToNC() {
      let { source, status, deliveryStatus } = this.params;

      // 自制 & 状态为：自由态、驳回
      // if(source === '3' &&(status === '0' || status === '3')){
      if (status === "2") {
        // 发送NC之后展示 SUCCESS("0","成功"),SEND_IN("1","发送中"),FAILURE("2","失败");
        //    未发送                发送过但未成功
        if (!deliveryStatus || (deliveryStatus && deliveryStatus !== "0")) {
          return true;
        }

        return false;
      }

      return false;
    },
    beforeOpen() {},
    getSummaries({ columns, data }) {
      const means = []; // 合计
      let { tabColumns, tabName } = this;
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          means.push("合计");
        } else {
          const values = data.map((item) => Number(item[column.property]));

          let sumColumn = tabColumns
            .find((tab) => tab.key === tabName)
            .tableColumns.filter((item) => item.hidden)
            .filter(
              ({ key, isSummary }) => isSummary && key === column.property
            );

          // 合计
          // if (!values.every(value => isNaN(value))) {
          if (sumColumn.length) {
            means[columnIndex] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            means[columnIndex] = means[columnIndex].toFixed(2);
          } else {
            means[columnIndex] = "";
          }
        }
      });
      // sums[index] = sums[index] && sums[index].toFixed(2); // 保留2位小数，解决小数合计列
      return [means];
    },
    onHide(prop) {
      this.innerColumns = prop;
    },
  },
  created() {},
  mounted() {},
  destroyed() {},
};
</script>
<template>
  <el-drawer
    direction="btt"
    size="100%"
    :with-header="false"
    :visible.sync="visible"
    @open="beforeOpen"
    @close="$emit('close')"
    v-loading="loading"
  >
    <el-form
      :size="size"
      label-position="right"
      label-width="140px"
      :model="params"
      :rules="rules"
      ref="orderSeeForm"
      class="orderSeeForm"
    >
      <el-card
        :body-style="{
          padding: '20px',
          display: 'flex',
          'flex-wrap': 'wrap',
        }"
        style="margin: 10px"
      >
        <div
          slot="header"
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <h3>查看</h3>
          <div style="text-align: right">
            <FilePrint v-model="printData"></FilePrint>
            <el-button :size="size" @click="handleRefresh">刷新</el-button>
            <template v-if="judgeIsToNC()">
              <el-tooltip
                class="box-item"
                effect="dark"
                :key="params.deliveryStatus"
                :content="params.deliveryMsg"
                placement="bottom-end"
              >
                <el-button
                  :key="params.deliveryStatus"
                  :disabled="params.deliveryStatus === '1'"
                  :size="size"
                  type="primary"
                  @click="handleSendNC"
                  >{{
                    params.deliveryStatus === "1"
                      ? "发送中"
                      : params.deliveryStatus === "2"
                      ? "重新发送NC"
                      : "发送NC"
                  }}</el-button
                >
              </el-tooltip>
            </template>

            <el-button :size="size" @click="handleCancel">取 消</el-button>
          </div>
        </div>
        <el-row style="display: flex; flex-wrap: wrap">
          <el-col
            v-for="(column, index) in columns"
            :key="index"
            :span="column.span || 6"
          >
            <el-form-item :prop="column.key" :label="column.title">
              <el-input
                v-if="column.inputType === 'Input'"
                v-model="params[column.key]"
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                readonly
                style="width: 100%"
              ></el-input>
              <dr-popover-select
                v-if="column.inputType === 'PopoverSelect'"
                v-model="params[column.key]"
                disabled
                :value-key="column.valueKey"
                :source.sync="params"
                :title="column.title"
                :type="column.referName"
                :multiple="column.multiple"
                :placeholder="column.placeholder"
                :data-mapping="column.dataMapping"
                :query-params="column.queryParams"
              ></dr-popover-select>

              <el-input
                v-if="column.inputType === 'Textarea'"
                v-model="params[column.key]"
                type="textarea"
                :rows="column.rows"
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                readonly
                :maxlength="column.maxlength"
                show-word-limit
                style="width: 100%"
              ></el-input>

              <el-input-number
                v-if="column.inputType === 'InputNumber'"
                v-model="params[column.key]"
                :controls-position="column.controlsPosition"
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                :precision="column.precision"
                disabled
                style="width: 100%"
              ></el-input-number>
              <el-select
                v-if="column.inputType === 'Select'"
                v-model="params[column.key]"
                disabled
                :size="size"
                :clearable="column.clearable"
                :placeholder="column.placeholder"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type[column.referName]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-select
                v-if="column.inputType === 'TagSelect'"
                v-model="params[column.key]"
                multiple
                clearable
                collapse-tags
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                disabled
                style="width: 100%"
              >
                <template #prefix>
                  <el-icon
                    class="el-icon-view"
                    style="cursor: pointer"
                    @click.stop="$message.info(234)"
                  >
                  </el-icon>
                </template>
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-date-picker
                v-if="column.inputType === 'DatePicker'"
                v-model="params[column.key]"
                :type="column.type"
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                readonly
                :picker-options="column.pickerOptions"
                style="width: 100%"
              ></el-date-picker>
              <el-checkbox
                v-if="column.inputType === 'Checkbox'"
                v-model="params[column.key]"
                disabled
                true-label="Y"
                false-label="N"
              ></el-checkbox>
              <file-upload-center
                v-if="column.inputType === 'Upload'"
                v-model="params[column.key]"
                :file-type="column.fileType"
                :disabled="true"
              ></file-upload-center>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card
        :body-style="{
          padding: '20px',
          display: 'flex',
          'flex-wrap': 'wrap',
          position: 'relative',
        }"
        style="margin: 10px"
      >
        <el-tabs v-model="tabName" style="width: 100%">
          <el-tab-pane
            v-for="(column, index) in tabColumns"
            :key="index"
            :label="column.title"
            :name="column.key"
          >
            <ux-grid
              border
              use-virtual
              keep-source
              show-summary
              show-overflow
              beautify-table
              :size="size"
              :ref="column.key"
              :height="tabHeight"
              style="width: 100%"
              :data="params[column.key].filter((item) => item.delFlag === '0')"
              :summary-method="getSummaries"
              :header-row-style="{
                color: '#515a6e',
              }"
            >
              <ux-table-column
                title="序号"
                type="index"
                width="60"
              ></ux-table-column>
              <ux-table-column
                v-for="(cColumn, cIndex) in column.tableColumns.filter(
                  (item) => item.hidden
                )"
                :key="cColumn.key + cColumn.hidden"
                :field="cColumn.key"
                :title="cColumn.title"
                :width="cColumn.width || 80"
                resizable
              >
                <template slot="header" slot-scope="scope">
                  <span v-if="cColumn.require" style="color: #ff4949">*</span>
                  <span>
                    {{ cColumn.title }}
                  </span>
                </template>
                <template slot-scope="scope">
                  <el-form-item label-width="0">
                    <span v-if="!cColumn.inputType">
                      {{ scope.row[cColumn.key] }}
                    </span>

                    <el-input
                      v-if="cColumn.inputType === 'Input'"
                      v-model="scope.row[cColumn.key]"
                      :placeholder="cColumn.placeholder"
                      :clearable="cColumn.clearable"
                      readonly
                      :size="size"
                      style="width: 100%"
                    ></el-input>

                    <!--  -->
                    <dr-popover-select
                      v-if="cColumn.inputType === 'PopoverSelect'"
                      v-model="scope.row[cColumn.key]"
                      :source.sync="scope.row"
                      :title="cColumn.title"
                      :value-key="cColumn.valueKey"
                      disabled
                      :type="cColumn.referName"
                      :multiple="cColumn.multiple"
                      :placeholder="cColumn.placeholder"
                      :data-mapping="cColumn.dataMapping"
                      :query-params="cColumn.queryParams"
                      :size="size"
                    ></dr-popover-select>

                    <el-input-number
                      v-if="cColumn.inputType === 'InputNumber'"
                      v-model="scope.row[cColumn.key]"
                      :precision="cColumn.precision"
                      :controls-position="cColumn.controlsPosition"
                      :placeholder="cColumn.placeholder"
                      :clearable="cColumn.clearable"
                      disabled
                      :size="size"
                      style="width: 100%"
                    ></el-input-number>

                    <el-select
                      v-if="cColumn.inputType === 'Select'"
                      v-model="scope.row[cColumn.key]"
                      disabled
                      :size="size"
                      :clearable="cColumn.clearable"
                      :placeholder="cColumn.placeholder"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in dict.type[cColumn.referName]"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>

                    <el-checkbox
                      v-if="cColumn.inputType === 'Checkbox'"
                      v-model="scope.row[cColumn.key]"
                      disabled
                      true-label="Y"
                      false-label="N"
                    ></el-checkbox>
                  </el-form-item>

                  <el-date-picker
                    v-if="cColumn.inputType === 'DatePicker'"
                    v-model="scope.row[cColumn.key]"
                    :size="size"
                    :type="cColumn.type"
                    :placeholder="cColumn.placeholder"
                    :clearable="cColumn.clearable"
                    :disabled="cColumn.disabled"
                    :picker-options="cColumn.pickerOptions"
                    style="width: 100%"
                  ></el-date-picker>
                </template>
              </ux-table-column>
            </ux-grid>
          </el-tab-pane>
        </el-tabs>
        <el-row style="margin-top: 10px">
          <el-col>
            <button-hide v-model="innerColumns" @change="onHide"></button-hide>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </el-drawer>
</template>

<style scoped>
.orderSeeForm >>> .el-form-item {
  margin-bottom: 5px;
}
::v-deep .singleTable .el-form-item {
  margin-bottom: 0px;
}
::v-deep.uxbeautifyTableClass
  .elx-header--column
  .elx-resizable.is--line:before {
  height: 100%;
  background-color: #dfe6ec;
}
</style>
