<!--
  - Author: gn
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        @current-change="currentChange"
        @size-change="sizeChange"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @row-update="updateOne"
        @row-save="saveOne"
        @row-del="deleteOne"
        
      >
        <!-- :search.sync="searchForm" -->
        <!-- @on-load="getList" -->
        <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>

        <template slot="exWarehouseStatus" 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>
        </template>

        <template slot-scope="scope" slot="menuLeft">
          <el-button
            v-if="ware_add"
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >添加</el-button>
          <el-button type="primary" size="small" icon="el-icon-download" @click="exportAll">导出</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
            type="text"
            size="small"
            icon="el-icon-download"
            @click="exportOne(scope.row, scope.index)"
          >导出</el-button>
          <el-button
            v-if="ware_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="ware_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="ware_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 ModalUpload from "./components/modalUpload";
import {
  fetchList,
  addResult,
  getResult,
  delResult,
  putResult,
  exportResult,
  exportAll
} 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";

export default {
  name: "warehouse",
  mixins: [GnTableMixin],
  components: {
    Modal,
    ModalView,
    ModalUpload
  },
  data() {
    return {
      // url
      url: {
        // 共用方法和命名
        getList: "/invtory/invgoodsexwarehouse/page",
        auditOne: "/invtory/invgoodsexwarehouse/audit",
        deleteOne: "/invtory/invgoodsexwarehouse",
        getdetail: "/invtory/invgoodsexwarehouse/getGoodsByExWarehouseNo",
        exportRow: "/invtory/invgoodsexwarehouse/export",
        exportAll: "/invtory/invgoodsexwarehouse/exportAll"
      },
      // 页面的 selfOption
      selfOption: {
        menuWidth: 240,
        selection: false,
        reserveSelection: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        column: [
          {
            label: "ID",
            overHidden: true,
            prop: "id",
            hide: true
          },
          {
            label: "出库单号",
            overHidden: true,
            prop: "exWarehouseNo",
            width: 120,
            search: true
          },
          {
            label: "客户",
            overHidden: true,
            prop: "custNo",
            hide: true
          },
          {
            label: "客户",
            overHidden: true,
            prop: "custName",
            labelWidth: 120,
            width: 180,
            search: true
          },
          {
            type: "date",
            label: "出库日期",
            overHidden: true,
            prop: "exWarehouseDate",
            search: true,
            searchSpan: 12,
            width: 100,
            labelWidth: 120,
            searchRange: true,
            rangeSeparator: "~",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            label: "商品类型",
            width: 100,
            overHidden: true,
            prop: "goodsName"
          },
          {
            label: "出库数量",
            overHidden: true,
            width: 80,
            prop: "exWarehouseQyt"
          },
          {
            label: "金额",
            width: 100,
            overHidden: true,
            prop: "totalPrice"
          },
          {
            label: "快递单号",
            overHidden: true,
            prop: "courierNumber",
            search: true
          },
          {
            label: "关联订单号",
            overHidden: true,
            prop: "orderNo",
            search: true
          },

          {
            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,
            prop: "exWarehouseStatus",
            type: "select",
            slot: true,
            dicData: [
              {
                label: "未出库",
                value: 0
              },
              {
                label: "已出库",
                value: 1
              }
            ],
            width: 80
          },

          {
            label: "操作人员",
            width: 100,
            overHidden: true,
            prop: "crteUser"
          },
          {
            label: "操作时间",
            overHidden: true,
            width: 150,
            prop: "crteTime"
          },
          /**{
            label: "备注",
            overHidden: true,
            prop: "remark"
          },
          {
            label: "审核说明",
            overHidden: true,
            prop: "auditResult"
          }**/
        ]
      },

      width: "80%",

      // ================ 审核弹窗 =================
      title: "出库审核",
      visible: false,
      btnLoading: false,
      form: {},
      formOption: {
        size: "small",
        submitText: "确定",
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: "出库单号",
            prop: "exWarehouseNo",
            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.ware_add = this.permissions["ware_add"] || true;
    this.ware_audit = this.permissions["ware_audit"] || true;
    this.ware_edit = this.permissions["ware_edit"] || true;
    this.ware_del = this.permissions["ware_del"] || true;
    this.mergeOption();
  },
  methods: {
    mergeOption() {
      this.tableOption = Object.assign(this.tableOption, this.selfOption);
      this.getList(1);
    },
    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("只能选择一条数据!");
        }
      }
    },
    // 导入
    uploadRow() {
      this.$refs.modalUploadRef.init();
    },
    exportOne(row, index) {
      this.daochushuju(row);
    },
    // 导出
    exportRow(row, index) {
      this.daochushuju(row);
    },
    async exportAll(params) {
      if (params) {
        this.searchForm = Object.assign(this.searchForm, params);
      }
      let time = nowFormatTime1();
      await exportAll(
        `${this.url.exportAll}`,
        this.searchForm
      ).then(res => {
        return fileDownload(res.data, "出库明细" + time + ".xlsx");
      });
    },
    async daochushuju(row) {
      let time = nowFormatTime1();
      await exportResult(
        `${this.url.exportRow}?exWarehouseNo=${row.exWarehouseNo}`,
        {}
      ).then(res => {
        return fileDownload(res.data, "出库明细" + time + ".xlsx");
      });
    },

    handleAdd() {
      let params = {};
      // params.logo = '/company/logo.png'
      // params.createTime = nowFormatTime1()
      params.exWarehouseDate = nowFormatTime2();
      this.$refs.modalRef.init(params, "add");
    },
    async handleUpdate(row, index) {
      let params;
      await getResult(this.url.getdetail, row.exWarehouseNo)
        .then(res => {
          params = res.data.data.data;
        })
        .catch(err => {
          this.$message.error("获取出库明细错误，请稍后再试！");
          return;
        });
      // params.logo = 'company/logo.png'
      this.$refs.modalRef.init(params, "edit");
    },
    handleAudit(row, index) {
      this.visible = true;
      this.form = row;
    },
    handleDelete(row, index) {
      let self = this;
      this.$confirm(
        "是否确认删除出库单号为 " + row.exWarehouseNo + " 的数据！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delResult(self.url.deleteOne, row.exWarehouseId);
        })
        .then(res => {
          if (res.data.code === 0) {
            self.$message.success("删除成功！");
            self.getList(this.page.currentPage);
          } else {
            self.$message.warning("删除失败！原因：" + res.data.message);
          }
        })
        .catch(err => {
          self.$message.error("错误！原因：" + err);
        });
    },

    async handleDetail(row, index) {
      let obj = {
        form: {},
        cardsData: []
      };
      await getResult(this.url.getdetail, row.exWarehouseNo)
        .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);
    },

    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.index = false;
      obj1.cardTableOption.stripe = false;
      obj1.cardTableOption.menu = false;
      obj1.cardTableOption.border = false;
      obj1.cardTableOption.addRowBtn = false;
      obj1.cardTableOption.column.forEach(ii => {
        if (ii.prop === "goodsNo") {
          ii.label = "商品编号";
        }
        if (ii.slot === true) {
          delete ii.slot;
        }
      });
      let temp = obj.form.goodsExWarehouseTypeMap.find(
        i => i.goodsTypeNo === val
      );
      Object.keys(JSON.parse(temp.goodsDealList[0].goodsProp)).forEach(i => {
        let oo = {};
        oo.prop = i;
        oo.label = i;
        oo.width = 80;
        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);
    },

    // ======== 审核相关 ========
    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(this.page.currentPage);
            } 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>