<template>
  <div id="PurchaseDemandList">
    <div v-if="isList">
      <el-card style="position: relative">
        <el-super-search
          v-model="params"
          :size="size"
          :dict="dict"
          :columns="SearchColumns"
          @reset="resetList"
          @submit="getList(params, Pages)"
        ></el-super-search>

        <div class="btn_grooup">
          <DemandButton :size="size" :dict="dict"></DemandButton>
          <el-button type="primary" :size="size" @click="addDivision"
            >新增</el-button
          >
          <el-dropdown :size="size" @command="handleCommand">
            <el-button :size="size" type="primary" style="margin-left: 10px">
              导入<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="数据导入">数据导入</el-dropdown-item>
              <el-dropdown-item command="模板下载">模板下载</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-dropdown :size="size" @command="handleExport">
            <el-button :size="size" style="margin: 0 10px">
              导出<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="选中导出">选中导出</el-dropdown-item>
              <el-dropdown-item command="全部导出">全部导出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-button :size="size" @click="delItems"
            >删除</el-button
          >
        </div>

        <el-super-ux-table
          v-loading="loading"
          v-model="tableList"
          :columns="TableColumns"
          :size="size"
          :dict="dict"
          :page="Pages"
          index
          checkbox
          pagination
          :height="540"
          highlight-current-row
          convenitentOperation
          storage-key="PurchaseDemandList"
          style="font-size: 12px"
          @pagination="getList(params, Pages)"
          @selection-change="handleSelectionChange"
          @row-click="rowSelect"
          @row-dblclick="doubleClick"
          ref="tables"
        >
          <ux-table-column
            fixed="right"
            title="操作"
            align="center"
            width="180"
          >
            <template slot-scope="scope">
              <el-button type="text" :size="size" @click="check(scope.row)"
                >查看</el-button
              >
              <el-button
                type="text"
                :size="size"
                v-if="
                  scope.row.status == '0' ||
                  scope.row.status == '3' ||
                  scope.row.status == '9'
                "
                @click="edit(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="text"
                :size="size"
                v-if="
                  scope.row.status == '0' ||
                  scope.row.status == '3' ||
                  scope.row.status == '9'
                "
                @click="commit(scope.row)"
                >提交</el-button
              >
              <el-button
                type="text"
                :size="size"
                v-if="scope.row.status == '1' && scope.row.flowId"
                @click="reback(scope.row)"
                >收回</el-button
              >
              <el-button
                type="text"
                :size="size"
                v-if="
                  scope.row.status == '0' ||
                  scope.row.status == '3' ||
                  scope.row.status == '9'
                "
                @click="deleteids(scope.row)"
                >删除</el-button
              >
            </template>
          </ux-table-column>
        </el-super-ux-table>
      </el-card>
    </div>

    <!-- 用户导入对话框 -->
    <el-dialog title="数据导入" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="errorFile"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer">
        <el-button :size="size" type="primary" @click="submitFileForm"
          >确 定</el-button
        >
        <el-button :size="size" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 模板下载新增参数 -->
    <el-dialog
      title="需求模板下载"
      :visible.sync="download.open"
      @close="clearDownload"
      width="400px"
    >
      <el-row style="margin-bottom: 20px">
        <span style="margin-right: 10px">需求计划</span>
        <el-select :size="size" v-model="download.planType">
          <el-option
            v-for="dict in dict.type.sys_plan_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          </el-option>
        </el-select>
      </el-row>
      <el-row style="margin-bottom: 20px">
        <span style="margin-right: 10px">需求客户</span>
        <el-select
          clearable
          :size="size"
          v-model="download.customer"
          @clear="download.customer = ''"
          @focus="chooseOrg('CUSTOMER_PARAM', true, '选择客户')"
        >
          <el-option
            v-for="item in mBcustomer"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-row>
      <el-row style="margin-bottom: 20px">
        <span style="margin-right: 10px">供应仓库</span>
        <el-select
          clearable
          :size="size"
          v-model="download.warehouse"
          @clear="cleanMb"
          @focus="chooseOrg('WAREHOUSE_PARAM', true, '选择仓库')"
        >
          <el-option
            v-for="item in mBwarehouse"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-row>
      <el-row style="margin-bottom: 20px">
        <span style="margin-right: 10px">供应货位</span>
        <el-select
          clearable
          :size="size"
          v-model="download.cargoSpace"
          @clear="download.cargoSpace = ''"
          @focus="
            mbHuowei('ALLOCATION_PARAM', true, '选择货位', download.warehouseId)
          "
        >
          <el-option
            v-for="item in mBcargoSpace"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-row>
      <el-row style="margin-bottom: 20px">
        <span style="margin-right: 10px">品类选择</span>
        <el-select
          v-model="download.category"
          :size="size"
          clearable
          @focus="chooseTreeRefer('MATERIALCLASSIFY_PARAM', false, '选择品类')"
        >
          <el-option
            v-for="item in classOptions"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-row>
      <div slot="footer">
        <el-button :size="size" type="primary" @click="mbDownload"
          >模板下载</el-button
        >
        <el-button :size="size" @click="download.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <Add
      v-model="isList"
      v-if="!isList"
      :pageStu="page"
      :disable="disable"
      :row="rowDetail"
      @refresh="getList(params, Pages)"
    />

    <Refers ref="refer" @doSubmit="selectionsToInput" :single="true" />

    <TreeRefers ref="tree" @doSubmit="selectionsToInput2" :single="true" />
  </div>
</template>

<script>
import useColumns from "./columns";
import { dicts } from "./dicts";
// 导入的token
import { getToken } from "@/utils/auth";
// 流程收回
import { rebacktWork } from "@/api/purchase/workSpace.js";
import {
  getDemandList,
  delDemand,
  downLoadDemand,
  exportDemand,
  submitDemand,
  confirmSubmit,
} from "@/api/purchase/purchaseDemand.js";
export default {
  name: "PurchaseDemandList",
  components: {
    Add: () => import("./add.vue"),
    Refers: () => import("@/components/Refers/refers.vue"),
    TreeRefers: () => import("@/components/Refers/sigleTreeRefer.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElSuperSearch: () => import("@/components/super-search/index.vue"),
    DemandButton: () => import("./demand/index.vue"),
  },
  dicts: [
    ...dicts,
    "sys_processing_mode",
    "sys_reserve_ratio",
    "sys_period_unit",
    "sys_price_type",
    "oa_templete_id",
  ],
  data() {
    const { TableColumns, SearchColumns } = useColumns();
    const Pages = this.$init.page();
    const params = this.$init.params(SearchColumns);
    return {
      Pages: Pages,
      params: {
        ...params,
        code: this.$route.query.billCode,
      },
      TableColumns: TableColumns,
      SearchColumns: SearchColumns,
      size: "mini",
      loading: true,
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "数据导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 1,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pu/demand/import",
      },
      // 模板下载参数
      download: {
        open: false,
        planType: "ZJH",
        customer: "",
        warehouse: "",
        warehouseId: "",
        cargoSpace: "",
        category: "",
      },
      mBcustomer: [],
      mBwarehouse: [],
      mBcargoSpace: [],
      classOptions: [],
      // 下拉收起配置
      expanded: false,
      // 页面配置
      isList: true,
      // 页面状态
      page: "",
      referCondition: {
        type: "",
        isPage: true,
        title: "",
      },
      customerOptions: [],
      personOptions: [],
      deptOptions: [],
      supplierOptions: [],
      tableList: [],
      total: 0,
      rowDetail: {},
      disable: false,
      ids: [],
    };
  },
  created() {
    this.getList(this.params, this.Pages);
  },
  methods: {
    resetList() {
      const { TableColumns, SearchColumns } = useColumns();
      this.Pages = this.$init.page();
      this.params = this.$init.params(SearchColumns);
      this.getList(this.params, this.Pages);
    },
    async getList(params, pages) {
      try {
        this.loading = true;
        let { code, rows, total } = await getDemandList({
          ...params,
          ...pages,
        });
        if (code === 200) {
          this.tableList = rows;
          this.Pages.total = total;
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    mbDownload() {
      this.$modal.loading("正在下载模板，请稍后...");
      downLoadDemand(this.download)
        .then((res) => {
          this.$modal.closeLoading();
          const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=UTF-8",
          }); // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
          const downloadElement = document.createElement("a"); //创建a标签
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          // var temp = res.headers["content-disposition"];
          // var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码）
          // var name = fileName.split(";")[0]; //切割成文件名
          downloadElement.href = href; //下载地址
          downloadElement.download =
            "采购需求单模板" + this.parseTime(new Date().getTime()) + ".xlsx"; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放blob对象
          this.download.open = false;
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },
    // 关闭模板下载弹窗清空参数
    clearDownload() {
      // 模板下载参数
      this.download = {
        open: false,
        planType: "ZJH",
        customer: "",
        warehouse: "",
        warehouseId: "",
        cargoSpace: "",
        category: "",
      };
    },
    handleCommand(command) {
      // alert(command)
      if (command == "模板下载") {
        this.download.open = true;
      }
      if (command == "数据导入") {
        this.upload.title = "用户导入";
        this.upload.open = true;
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.$modal.loading("正在导入数据，请稍后...");
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.$modal.closeLoading();
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList(this.params, this.Pages);
    },
    errorFile(err) {
      this.$modal.closeLoading();
      this.$modal.notifyError("文件已变动，请重新上传");
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleExport(command) {
      if (command == "选中导出") {
        if (this.ids.length == 0) {
          this.$modal.notifyWarning("请选中至少一条数据");
        } else {
          this.$modal.loading("正在导出数据，请稍后...");
          let param = { all: false, ids: this.ids };
          exportDemand(param)
            .then((res) => {
              this.$modal.closeLoading();
              const blob = new Blob([res], {
                type: "application/vnd.ms-excel;charset=UTF-8",
              }); // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
              const downloadElement = document.createElement("a"); //创建a标签
              const href = window.URL.createObjectURL(blob); // 创建下载的链接
              // var temp = res.headers["content-disposition"];
              // var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码）
              // var name = fileName.split(";")[0]; //切割成文件名
              downloadElement.href = href; //下载地址
              downloadElement.download =
                "采购需求单选中导出" +
                this.parseTime(new Date().getTime()) +
                ".xlsx"; // 下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); // 点击下载
              document.body.removeChild(downloadElement); // 下载完成移除元素
              window.URL.revokeObjectURL(href); // 释放blob对象
            })
            .catch((err) => {
              this.$modal.closeLoading();
            });
        }
      } else {
        this.$modal.loading("正在导出数据，请稍后...");
        let param2 = { all: true };
        exportDemand(param2)
          .then((res) => {
            this.$modal.closeLoading();
            const blob = new Blob([res], {
              type: "application/vnd.ms-excel;charset=UTF-8",
            }); // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
            const downloadElement = document.createElement("a"); //创建a标签
            const href = window.URL.createObjectURL(blob); // 创建下载的链接
            // var temp = res.headers["content-disposition"];
            // var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码）
            // var name = fileName.split(";")[0]; //切割成文件名
            downloadElement.href = href; //下载地址
            downloadElement.download =
              "采购需求单全部导出" +
              this.parseTime(new Date().getTime()) +
              ".xlsx";
            document.body.appendChild(downloadElement);
            downloadElement.click(); // 点击下载
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放blob对象
          })
          .catch((err) => {
            this.$modal.closeLoading();
          });
      }
    },
    addDivision() {
      this.isList = false;
      this.page = "add";
      this.disable = false;
    },
    check(row) {
      this.isList = false;
      this.page = "check";
      this.rowDetail = row;
      this.disable = true;
    },
    doubleClick(row) {
      this.isList = false;
      this.page = "check";
      this.rowDetail = row;
      this.disable = true;
    },
    // 表格选中数据
    rowSelect(row) {
      this.$refs.tables.toggleRowSelection([{ row: row }]);
    },
    edit(row) {
      this.isList = false;
      this.page = "edit";
      this.rowDetail = row;
      this.disable = false;
    },
    commit(row) {
      console.log("row", row);
      this.$modal.loading("提交中...");
      submitDemand(row)
        .then((res) => {
          if (res.code === 200) {
            this.$modal.notifySuccess("提交成功");
            this.$modal.closeLoading();
            this.getList(this.params, this.Pages);
          }
          if (res.code === 233) {
            this.$modal
              .confirm(res.msg)
              .then(function () {
                // 确认
              })
              .then(() => {
                confirmSubmit(row)
                  .then((res) => {
                    if (res.code === 200) {
                      this.$modal.notifySuccess("提交成功");
                      this.$modal.closeLoading();
                      this.getList(this.params, this.Pages);
                    }
                  })
                  .catch((err) => {
                    this.$modal.closeLoading();
                  });
                // 取消
              })
              .catch(() => {
                this.$modal.closeLoading();
              });
            this.$modal.closeLoading();
          }
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },
    // 流程收回
    reback(row) {
      this.$modal.loading("收回中...");
      let params = {
        billCode: row.code,
        fdId: row.flowId,
        fdTemplateId: this.dict.type.oa_templete_id.find((item) => {
          return item.label == "采购需求单";
        }).value,
        billMaker: row.createBy,
      };
      rebacktWork(params)
        .then((res) => {
          if (res.code === 200) {
            this.$modal.notifySuccess("收回成功");
            this.$modal.closeLoading();
            this.getList(this.params, this.Pages);
          }
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },
    // 行内删除
    deleteids(row) {
      console.log("row", row);
      this.$modal
        .confirm("确定删除选择数据?")
        .then(() => {
          delDemand(row.id).then((res) => {
            if (res.code === 200) {
              this.$modal.notifySuccess("删除成功");
              this.getList(this.params, this.Pages);
            }
          });
        })
        .catch(() => {});
    },
    // 批量删除按钮
    delItems() {
      if (this.ids.length == 0) {
        this.$modal.notifyWarning("请选中至少一条数据");
      } else {
        let param = this.ids.join();
        this.$modal
          .confirm("确认删除选中数据?")
          .then(() => {
            delDemand(param).then((res) => {
              if (res.code === 200) {
                this.$modal.notifySuccess("删除成功");
                this.getList(this.params, this.Pages);
              }
            });
          })
          .catch(() => {});
      }
    },
    // 搜索区参照选择
    chooseOrg(type, isPage, title, stordocId) {
      this.referCondition.type = type;
      this.referCondition.isPage = isPage;
      this.referCondition.title = title;
      this.referCondition.stordocId = stordocId;
      this.$refs.refer.init(this.referCondition);
    },
    selectionsToInput(selection) {
      // 搜索区选择客户
      if (
        this.referCondition.type == "CUSTOMER_PARAM" &&
        this.referCondition.title == "需求客户"
      ) {
        this.customerOptions = selection;
        this.queryParams.customer = selection[0].id;
      }
      // 模板内选择客户
      if (
        this.referCondition.type == "CUSTOMER_PARAM" &&
        this.referCondition.title == "选择客户"
      ) {
        this.mBcustomer = selection;
        this.download.customer = selection[0].code;
      }
      // 模板内选择仓库
      if (
        this.referCondition.type == "WAREHOUSE_PARAM" &&
        this.referCondition.title == "选择仓库"
      ) {
        this.mBwarehouse = selection;
        this.download.warehouse = selection[0].code;
        this.download.warehouseId = selection[0].id;
      }
      // 模板内选择货位
      if (
        this.referCondition.type == "ALLOCATION_PARAM" &&
        this.referCondition.title == "选择货位"
      ) {
        this.mBcargoSpace = selection;
        this.download.cargoSpace = selection[0].code;
      }
      if (this.referCondition.type == "CONTACTS_PARAM") {
        this.personOptions = selection;
        this.queryParams.demandPersonal = selection[0].code;
      }
      if (this.referCondition.type == "DEPT_PARAM") {
        this.deptOptions = selection;
        this.queryParams.demandDept = selection[0].id;
      }
      if (this.referCondition.type == "SUPPLIER_PARAM") {
        this.supplierOptions = selection;
        this.queryParams.additionalSupplier = selection[0].id;
      }
    },
    mbHuowei(type, isPage, title, stordocId) {
      this.referCondition.type = type;
      this.referCondition.isPage = isPage;
      this.referCondition.title = title;
      if (stordocId) {
        this.referCondition.stordocId = stordocId;
        this.$refs.refer.init(this.referCondition);
      } else {
        this.$modal.notifyWarning("请先选择仓库");
      }
    },
    cleanMb() {
      this.download.warehouse = "";
      this.download.warehouseId = "";
    },
    // 搜索区树形选择
    chooseTreeRefer(type, isPage, title) {
      this.referCondition.type = type;
      this.referCondition.isPage = isPage;
      this.referCondition.title = title;
      this.$refs.tree.init(this.referCondition);
    },
    selectionsToInput2(selection) {
      this.classOptions.push(selection);
      this.download.category = selection.code;
    },
   
  },
};
</script>

<style lang="scss" scoped>
#PurchaseDemandList {
  padding: 12px;
  box-sizing: border-box;
  overflow-y: scroll;
}
.btn_grooup {
  margin: 10px 0;
  display: flex;
  justify-content: flex-end;
}
</style>
