<!--
  - Author: gn
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :search.sync="searchForm"
        :table-loading="tableLoading"
        :option="tableOption"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="updateOne"
        @row-save="saveOne"
        @row-del="deleteOne"
        @selection-change="selectionChange1"
      >
        <template slot="auditStatus" slot-scope="scope">
          <span v-if="scope.row.auditStatus == 0" style="color:#00a8f3">待审核</span>
          <span v-else-if="scope.row.auditStatus == 1" style="color:#0ed145">通过</span>
          <span v-else-if="scope.row.auditStatus == 2" style="color:#e04046">不通过</span>
        </template>

        <!-- @on-load="getList" -->
        <template slot-scope="scope" slot="menuLeft">
          <el-button
            v-if="stor_add"
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >添加</el-button>
          <el-button type="primary" size="small" icon="el-icon-download" @click="exportRow">导出</el-button>
          <el-button type="primary" size="small" icon="el-icon-upload2" @click="uploadRow">导入</el-button>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            v-if="stor_audit && scope.row.auditStatus != 1"
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="handleAudit(scope.row, scope.index)"
          >审核</el-button>
          <el-button
            v-if="stor_edit"
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, scope.index)"
          >编辑</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="handleDetail(scope.row, scope.index)"
          >详情</el-button>
          <el-button
            v-if="stor_del"
            type="text"
            size="small"
            icon="el-icon-delete"
            @click="handleDelete(scope.row, scope.index)"
          >撤销</el-button>
        </template>
      </avue-crud>

      <Modal ref="modalRef" :width="width" @ok="refreshChange" />
      <el-dialog
        :title="title"
        :visible.sync="visible"
        width="45%"
        :close-on-click-modal="false"
        append-to-body
      >
        <avue-form ref="formRef" v-model="form" :option="formOption">
          <template slot-scope="scope" slot="menuForm">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-check"
              :loading="btnLoading"
              @click="handleSubmit"
            >确定</el-button>
            <el-button
              size="small"
              icon="el-icon-delete"
              :loading="btnLoading"
              @click="handleEmpty"
            >清空</el-button>
          </template>
        </avue-form>
      </el-dialog>
    </basic-container>

    <ModalView ref="modalViewRef" />

    <ModalUpload ref="modalUploadRef" @ok="getList(page.currentPage)" />
  </div>
</template>

<script>
import { GnTableMixin } from "@/util/GnTableMixin";
import {
  fetchList,
  addResult,
  getResult,
  delResult,
  putResult,
  exportResult
} from "@/api/commonApis";
import fileDownload from "js-file-download";
import Modal from "./components/modal";
import { nowFormatTime1, nowFormatTime2 } from "@/util/GnUtils";
import ModalView from "./components/modalView";
import ModalUpload from "./components/modalUpload";
import request from "@/router/axios";
export default {
  name: "warehouse",
  mixins: [GnTableMixin],
  components: {
    Modal,
    ModalView,
    ModalUpload
  },
  data() {
    return {
      // url
      url: {
        // 共用方法和命名
        getList: "/invtory/invgoodswarehousing/page",
        auditOne: "/invtory/invgoodswarehousing/audit",
        deleteOne: "/invtory/invgoodswarehousing",
        getdetail: "/invtory/invgoodswarehousing/getGoodsByWarehousingNo",
        exportRow: "/invtory/invgoodswarehousing/export",
        uploadRow: "/invtory/invgoodswarehousing/import"
      },
      // 页面的 selfOption
      selectionRows: [],
      selfOption: {
        menuWidth: 240,
        selection: true,
        reserveSelection: true,
        column: [
          {
            label: "ID",
            overHidden: true,
            prop: "id",
            hide: true
          },
          {
            label: "入库单号",
            overHidden: true,
            prop: "warehousingNo",
            width: 120,
            search: true
          },
          {
            label: "供应商",
            overHidden: true,
            prop: "suplierName",
            width: 180,
            search: true
          },
          {
            label: "商品类型",
            width: 100,
            overHidden: true,
            prop: "goodsName"
          },
          {
            type: "date",
            label: "入库日期",
            overHidden: true,
            prop: "warehousingDate",
            search: true,
            searchSpan: 12,
            width: 120,
            labelWidth: 120,
            searchRange: true,
            rangeSeparator: "~",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            label: "审核状态",
            overHidden: true,
            prop: "auditStatus",
            type: "select",
            slot: true,
            dicData: [
              {
                label: "待审核",
                value: 0
              },
              {
                label: "通过",
                value: 1
              },
              {
                label: "不通过",
                value: 2
              }
            ],
            width: 80,
            search: true
          },
          {
            label: "入库数量",
            overHidden: true,
            width: 80,
            prop: "warehousingQyt"
          },
          {
            label: "金额",
            width: 100,
            overHidden: true,
            prop: "amount"
          },
          {
            label: "操作人员",
            width: 100,
            overHidden: true,
            prop: "crteUser"
          },
          {
            label: "操作时间",
            width: 150,
            overHidden: true,
            prop: "crteTime"
          },
          {
            label: "备注",
            overHidden: true,
            prop: "remark"
          },
          {
            label: "审核说明",
            overHidden: true,
            prop: "auditResult"
          }
        ],
        addBtn: false,
        editBtn: false,
        delBtn: false
      },

      width: "80%",

      // ================ 审核弹窗 =================
      title: "入库审核",
      visible: false,
      btnLoading: false,
      form: {},
      formOption: {
        size: "small",
        submitText: "确定",
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: "入库单号",
            prop: "warehousingNo",
            span: 22,
            disabled: true,
            placeholder: " ",
            labelWidth: 120
          },
          {
            label: "审核结果",
            prop: "auditStatus",
            span: 22,
            labelWidth: 120,
            type: "radio",
            dicData: [
              {
                label: "通过",
                value: 1
              },
              {
                label: "不通过",
                value: 2
              }
            ],
            rules: [
              {
                required: true,
                message: "请选择审核结果！",
                trigger: "blur"
              }
            ]
          },
          {
            type: "textarea",
            label: "原因",
            prop: "auditResult",
            span: 22,
            display: true,
            labelWidth: 120,
            minRows: 4
          }
        ]
      }
    };
  },
  watch: {},
  computed: {},
  created() {
    // this.ware_add = this.permissions['stor_add']
    // this.ware_edit = this.permissions['stor_edit']
    // this.ware_del = this.permissions['stor_del']
    // console.log("ware权限增改删", this.permissions['stor_add'], this.permissions['stor_edit'], this.permissions['stor_del']);
    this.stor_add = this.permissions["stor_add"] || true;
    this.stor_audit = this.permissions["stor_audit"] || true;
    this.stor_edit = this.permissions["stor_edit"] || true;
    this.stor_del = this.permissions["stor_del"] || true;
    this.mergeOption();
  },
  methods: {
    mergeOption() {
      this.tableOption = Object.assign(this.tableOption, this.selfOption);
      this.getList();
    },
    fetchList(query) {
      return request({
        url: "/admin/route",
        method: "get",
        params: query
      });
    },
    getList(current, params) {
      this.tableLoading = true;
      if (current) {
        this.page.currentPage = current;
      }
      if (params) {
        this.searchForm = Object.assign(this.searchForm, params);
      }
      fetchList(
        this.url.getList,
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize
          },
          this.searchForm
        )
      )
        .then(res => {
          this.tableData = res.data.data.records;
          this.page.total = res.data.data.total;
          this.tableLoading = false;
        })
        .catch(err => {
          this.$message.error("获取表格数据错误！原因：" + err);
          this.tableLoading = false;
          this.tableData = [];
          this.page.total = 0;
        });
    },
    // 表格选中事件
    selectionChange1(selectionRows) {
      if (selectionRows.length) {
        if (selectionRows.length > 1) {
          const nowVal = selectionRows.shift();
          this.$refs.crud.toggleRowSelection(nowVal, false);
        } else if (selectionRows.length === 1) {
          this.selectionRows = selectionRows;
        } else {
          this.$message.warning("只能选择一条数据!");
        }
      }
    },
    // 导出
    exportRow() {
      if (!this.selectionRows.length) {
        this.$message.warning("请选择需要导出的记录！");
        return;
      }
      this.daochushuju(this.selectionRows[0]);
    },
    async daochushuju(row) {
      let time = nowFormatTime1();
      await exportResult(
        `${this.url.exportRow}?warehousingNo=${row.warehousingNo}`,
        {}
      ).then(res => {
        return fileDownload(res.data, "入库明细" + time + ".xlsx");
      });
    },
    // 导入
    uploadRow() {
      this.$refs.modalUploadRef.init();
    },

    handleAdd() {
      let params = {};
      // params.logo = '/company/logo.png'
      // params.createTime = nowFormatTime1()
      params.warehousingDate = nowFormatTime2();
      this.$refs.modalRef.init(params, "add");
    },
    async handleUpdate(row, index) {
      let params;
      await getResult(this.url.getdetail, row.warehousingNo)
        .then(res => {
          params = res.data.data.data;
        })
        .catch(err => {
          this.$message.error("获取入库明细错误，请稍后再试！");
          return;
        });
      // params.logo = 'company/logo.png'
      if (params.goodsWarehousingTypeMap[0].goodsDealList.length > 50) {
        this.$message.info("正在计算数据并渲染表格编辑事件，请稍等......", 20);
      }
      this.$refs.modalRef.init(params, "edit");
    },
    handleAudit(row, index) {
      this.visible = true;
      this.form = row;
    },
    async handleDetail(row, index) {
      let obj = {
        form: {},
        cardsData: []
      };
      await getResult(this.url.getdetail, row.warehousingNo)
        .then(res => {
          obj.form = res.data.data.data;
        })
        .catch(err => {
          this.$message.error("获取入库明细错误，请稍后再试！");
          return;
        });
      console.log("form", obj.form);
      obj.form.goodsNoList = obj.form.goodsNo;
      obj.form.goodsNoList.forEach((item, index) => {
        this.addOnetoCardsData(item, index, obj);
      });
      this.$refs.modalViewRef.init(obj);
    },

    async addOnetoCardsData(val, index, obj) {
      let obj1 = {
        goodsTypeNo: val,
        goodName: obj.form.goodsName[index],
        tableData: [],
        cardTableOption: JSON.parse(
          JSON.stringify(this.$refs.modalRef.cardTableOption)
        )
      };
      obj1.cardTableOption.menu = false;
      obj1.cardTableOption.border = false;
      obj1.cardTableOption.addRowBtn = false;
      obj1.cardTableOption.column.forEach(ii => {
        if (ii.prop === "goodsNo") {
          ii.prop = "goodsName";
        }
        if (ii.slot === true) {
          delete ii.slot;
        }
      });
      let temp = obj.form.goodsWarehousingTypeMap.find(
        i => i.goodsTypeNo === val
      );
      Object.keys(JSON.parse(temp.goodsDealList[0].goodsProp)).forEach(i => {
        let oo = {};
        oo.prop = i;
        oo.label = i;
        obj1.cardTableOption.column
          .find(i => i.prop === "goodsSpecifications")
          .children.push(oo);
      });
      obj1.tableData = temp.goodsDealList.map((i, k) => {
        i = Object.assign(i, JSON.parse(temp.goodsDealList[k].goodsProp));
        return i;
      });
      obj.cardsData.push(obj1);
    },

    handleDelete(row, index) {
      let self = this;
      this.$confirm(
        "是否确认删除入库单号为 " + row.warehousingNo + " 的数据！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delResult(self.url.deleteOne, row.warehousingId);
        })
        .then(res => {
          if (res.data.code === 0) {
            self.$message.success("删除成功！");
            self.getList();
          } else {
            self.$message.warning("删除失败！原因：" + res.data.message);
          }
        })
        .catch(err => {
          self.$message.error("错误！原因：" + err);
        });
    },

    // ======== 审核相关 ========
    handleSubmit() {
      this.$refs.formRef.validate(async (valid, done) => {
        if (!valid) return;
        this.btnLoading = true;
        await addResult(this.url.auditOne, this.form)
          .then(res => {
            if (res.data.code === 0) {
              this.$message.success("审核操作执行成功！");
              this.resetFormData();
              this.visible = false;
              this.getList();
            } else {
              this.$message.warning("审核操作执行失败！原因：" + res.data.msg);
            }
            this.btnLoading = false;
            done();
          })
          .catch(err => {
            this.btnLoading = false;
            done();
            this.$message.error("错误！原因：" + err);
          });
      });
    },
    handleEmpty() {
      this.resetFormData();
    },
    resetFormData() {
      this.form = {
        auditStatus: "",
        remark: ""
      };
    }
  }
};
</script>