<!-- 数据 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      id="out-table"
      :header-cell-class-name="headerClassName"
      :search.sync="query"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @resetColumn="resetColumn('crud', 'option', 'optionBack', 535)"
      @saveColumn="saveColumn('crud', 'option', 'optionBack', 535)"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addRow()">新增</el-button>
        <!-- <el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">删 除</el-button> -->
        <!-- <el-button type="warning" size="small" icon="el-icon-printer" @click="excelBox = true">导入 </el-button>
        <el-button type="success" size="small" @click="handleExport" icon="el-icon-printer">导出</el-button> -->
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <!-- <el-button type="text" size="small" @click.stop="rowView(row, index)">查看
        </el-button> -->
        <el-button type="text" size="small" @click.stop="rowEdit(row, index)">编辑 </el-button>
        <el-button type="text" size="small" @click.stop="rowDel(row, index)">删除 </el-button>
      </template>
      <template slot="branchNameForm" slot-scope="{ type, disabled }">
        <dic-select
          v-model="form.branchName"
          placeholder="所属公司"
          key="id"
          label="deptName"
          url="/blade-system/dept/top-list"
          :filterable="true"
          :remote="true"
          dataName="deptName"
          :disabled="disabled"
          @selectChange="dicChange('branchName', $event)"
        ></dic-select>
      </template>
      <tempalte slot="vesselCnNameForm" slot-scope="{ type, disabled }">
        <dic-select
          v-model="form.vesselCnName"
          placeholder="船名"
          key="id"
          label="cnName"
          res="records"
          url="/blade-los/bvessels/list?status=0&current=1&size=10"
          :filterable="true"
          :remote="true"
          dataName="cnName"
          @selectChange="dicChange('vesselCnName', $event)"
          :slotRight="true"
          rightLabel="code"
          :disabled="disabled"
        ></dic-select>
      </tempalte>
      <tempalte slot="polCnNameForm" slot-scope="{ type, disabled }">
        <dic-select
          v-model="form.polCnName"
          placeholder="港口"
          key="id"
          label="cnName"
          res="records"
          url="/blade-los/bports/list?status=0&current=1&size=10"
          :filterable="true"
          :remote="true"
          dataName="cnName"
          @selectChange="dicChange('polCnName', $event)"
          :slotRight="true"
          rightLabel="code"
          :disabled="disabled || !(roleName.includes('admin') || roleName.includes('总部'))"
        ></dic-select>
      </tempalte>
    </avue-crud>

    <el-dialog title="导入数据" append-to-body :visible.sync="excelBox" width="555px" :close-on-click-modal="false" v-dialog-drag>
      <avue-form :option="excelOption" v-model="excelForm" :table-loading="excelLoading" :upload-before="uploadBefore" :upload-after="onSuccess">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleGet"> 点击下载<i class="el-icon-download el-icon--right"></i> </el-button>
        </template>
      </avue-form>
      <p style="text-align: center;color: #DC0505">
        温馨提示 第一次导入时请先下载模板
      </p>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, submit, remove } from "@/api/iosBasicData/sailingSchedule.js";
import dicSelect from "@/components/dicSelect/main";
import { getToken } from "@/util/auth";

export default {
  name: "船期管理",
  components: {
    dicSelect
  },
  data() {
    return {
      roleName: localStorage.getItem("roleName").split(","), // 当前的角色权限
      form: {
        branchId: JSON.parse(localStorage.getItem("sysitemData")).deptId,
        branchName: JSON.parse(localStorage.getItem("sysitemData")).deptName
      },
      query: {},
      loading: true,
      excelBox: false,
      excelForm: {},
      excelLoading: false,
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data"
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/blade-los/btrademodes/importBTradeModes"
          }
        ]
      },
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      selectionList: [],
      option: {},
      optionBack: {
        height: "auto",
        align: "center",
        stripe: true,
        calcHeight: 30,
        searchIcon: true,
        searchIndex: 3,
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        border: true,
        index: true,
        addBtn:false,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogDrag: true,
        dialogClickModal: false,
        menuWidth: 100,
        column: [
          {
            label: "所属公司",
            prop: "branchId",
            display: false,
            hide: true,
            type: "select",
            filterable: true,
            dicUrl: "/api/blade-system/dept/lazy-list",
            props: {
              label: "deptName",
              value: "id"
            },
            search: true
          },
          {
            label: "所属公司",
            prop: "branchName",
            width: 120,
            rules: [
              {
                required: true,
                message: "请选择所属公司",
                trigger: "blur"
              }
            ],
            overHidden: true
          },
          {
            label: "船名",
            prop: "vesselId",
            display: false,
            hide: true,
            search: true,
            type: "select",
            filterable: true,
            remote: true,
            dicUrl: "/api/blade-los/bvessels/list?status=0&current=1&size=10&cnName={{key}}",
            props: {
              label: "cnName",
              value: "id",
              res: "data.records"
            },
            overHidden: true
          },
          {
            label: "船名",
            prop: "vesselCnName",
            width: 100,
            rules: [
              {
                required: true,
                message: "请选择船名",
                trigger: "blur"
              }
            ],
            overHidden: true
          },
          {
            label: "航次",
            prop: "voyageNo",
            width: 100,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入航次",
                trigger: "blur"
              }
            ],
            overHidden: true
          },
          {
            label: "开船日期",
            prop: "etd",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd 00:00:00",
            rules: [
              {
                required: true,
                message: "请选择日期",
                trigger: "blur"
              }
            ],
            overHidden: true
          },
          {
            label: "装货港",
            prop: "polId",
            display: false,
            hide: true,
            search: true,
            type: "select",
            filterable: true,
            remote: true,
            dicUrl: "/api/blade-los/bports/list?status=0&current=1&size=10&cnName={{key}}",
            props: {
              label: "cnName",
              value: "id",
              res: "data.records"
            },
            overHidden: true
          },
          {
            label: "装货港",
            prop: "polCnName",
            width: 100,
            rules: [
              {
                required: true,
                message: "请选择装货港",
                trigger: "blur"
              }
            ],
            overHidden: true
          },
          {
            label: "创建人",
            prop: "createUserName",
            display: false,
            overHidden: true
          },
          {
            label: "创建时间",
            prop: "createTime",
            width: 150,
            display: false,
            overHidden: true
          },
          {
            label: "修改人",
            prop: "updateUserName",
            display: false,
            overHidden: true
          },
          {
            label: "修改时间",
            prop: "updateTime",
            width: 150,
            display: false,
            overHidden: true
          },
          {
            label: "是否已删除（0 否 1是）",
            prop: "isDeleted",
            hide: true,
            display: false,
            overHidden: true
          },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            width: 180,
            span: 12,
            minRows: 2,
            slot: true,
            overHidden: true
          }
        ]
      },
      data: []
    };
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(535), this.optionBack);
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    dicChange(name, row) {
      if (name == "branchName") {
        if (row) {
          this.form.branchId = row.id;
        } else {
          this.form.branchId = null;
          this.form.branchName = null;
        }
      }
      if (name == "polCnName") {
        if (row) {
          this.form.polId = row.id;
          this.form.polCode = row.code;
          this.form.polEnName = row.enName;
        } else {
          this.form.polId = null;
          this.form.polCode = null;
          this.form.polEnName = null;
          this.form.polCnName = null;
        }
      }
      if (name == "vesselCnName") {
        if (row) {
          this.form.vesselId = row.id;
          this.form.vesselEnName = row.enName;
        } else {
          this.form.vesselId = null;
          this.form.vesselEnName = null;
          this.form.vesselCnName = null;
        }
      }
    },
    // 导出
    handleExport() {
      var condition = "";
      for (const key in this.query) {
        var value = this.query[key];
        if (value) {
          condition += `&${key}=${this.query[key]}`;
        }
      }

      this.$confirm("是否导出数据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          window.open(`/api/blade-los/btrademodes/exportBTradeModes?${this.website.tokenHeader}=${getToken()}${condition}`);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消" //
          });
        });
    },
    uploadBefore(file, done, loading) {
      done();
      loading = true;
    },
    // 上传成功
    onSuccess(res, done, loading, column) {
      if (res.length > 0) {
        this.$message.success("上传成功！");
      }
      this.excelBox = false;
      loading = false;
      this.onLoad(this.page);
      done();
    },
    // 下载模板
    handleGet() {
      window.open(`/api/blade-los/btrademodes/exportBTradeModes/template?${this.website.tokenHeader}=${getToken()}`);
    },
    addRow() {
      this.form = {
        branchId: JSON.parse(localStorage.getItem("sysitemData")).deptId,
        branchName: JSON.parse(localStorage.getItem("sysitemData")).deptName
      };
      this.$refs.crud.rowAdd();
    },
    // 编辑
    rowEdit(row, index) {
      getDetail({ id: row.id }).then(res => {
        this.form = res.data.data;
        this.$refs.crud.rowEdit(row, index);
      });
    },
    rowSave(row, done, loading) {
      submit(row)
        .then(res => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
        .finally(() => {
          done();
          loading();
        });
    },
    rowUpdate(row, index, done, loading) {
      submit(row)
        .then(res => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
        .finally(() => {
          done();
          loading();
        });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        remove({ ids: row.id }).then(res => {
          this.onLoad(this.page, this.query);
          this.$message.success("成功删除");
        });
      });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }

      for (const selection of this.selectionList) {
        if (selection.status == 0) {
          this.$message.warning("选中的数据中有启用数据,启用数据不可删除!");
          return;
        }
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        remove({ ids: this.ids }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
      });
    },
    searchReset() {
      this.query = this.$options.data().query;
      this.onLoad(this.page, this.query);
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      let obj = {};
      obj = {
        ...Object.assign(params, this.query)
      };
      this.loading = true;
      getList(page.currentPage, page.pageSize, obj)
        .then(res => {
          this.page.total = res.data.data.total;
          this.data = res.data.data.records;
          this.$nextTick(() => {
            this.$refs.crud.dicInit();
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //自定义列保存
    async saveColumn(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行编码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumn(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    // 更改表格颜色
    headerClassName(tab) {
      //颜色间隔
      let back = "";
      if (tab.columnIndex >= 0 && tab.column.level === 1) {
        if (tab.columnIndex % 2 === 0) {
          back = "back-one";
        } else if (tab.columnIndex % 2 === 1) {
          back = "back-two";
        }
      }
      return back;
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep#out-table .back-one {
  background: #ecf5ff !important;
}

::v-deep#out-table .back-two {
  background: #ecf5ff !important;
}

/deep/ .el-col-md-8 {
  width: 24.33333%;
}
</style>
