<!--港口-->
<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               id="out-table"
               :header-cell-class-name="headerClassName"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @resetColumn="resetColumnTwo('crud', 'option', 'optionBack', 298)"
               @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 298)"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
      </template>
        <template slot="remarks" slot-scope="scope">
            <avue-text-ellipsis :text="scope.row.remarks" :height="30" use-tooltip placement="top">
                <small slot="more">...</small>
            </avue-text-ellipsis>
        </template>
        <template slot="extendedDataArr" slot-scope="scope">
         <span style="color: #1e9fff" @click="extendedDataview(scope.row)">
                {{scope.row.extendedDataArr.length}}
         </span>
        </template>
        <template slot-scope="{type,disabled,row}" slot="extendedDataArrForm">
            <el-button type="primary"
                       size="small"
                       @click="dialogVisible = true">EDI CODE
            </el-button>
        </template>

    </avue-crud>

      <el-dialog
          title="EDI CODE"
          :visible.sync="dialogVisible"
          width="50%"
          append-to-body
          :destroy-on-close="true"
          :modal-append-to-body="false"
          :before-close="handleClose">
          <div>
              <el-button type="primary"
                         size="small"
                         :disabled="extendedDisabled"
                         @click="extendedDataAdd">新增
              </el-button>
              <el-table
                  stripe
                  :data="form.extendedDataArr"
                  id="out-table"
                  :header-cell-class-name="headerClassName"
                  style="width: 100%">
                  <el-table-column
                      prop="name"
                      label="名称">
                      <template slot-scope="{row}">
                          <el-input v-if="row.edit" size="mini" v-model="row.name" placeholder="请输入名称"></el-input>
                          <span v-else>{{row.name}}</span>
                      </template>
                  </el-table-column>
                  <el-table-column
                      prop="value"
                      label="键值">
                      <template slot-scope="{row}">
                          <el-input v-if="row.edit" size="mini" v-model="row.value" placeholder="请输入键值"></el-input>
                          <span v-else>{{row.value}}</span>
                      </template>
                  </el-table-column>
                  <el-table-column label="操作">
                      <template slot-scope="scope">
                          <el-button
                              type="text"
                              size="mini"
                              :disabled="extendedDisabled"
                              @click="extendedDataEdit(scope.$index, scope.row)">{{scope.row.edit?'保存':'编辑'}}</el-button>
                          <el-button
                              size="mini"
                              type="text"
                              :disabled="extendedDisabled"
                              @click="extendedDataDelete(scope.$index, scope.row)">删除</el-button>
                      </template>
                  </el-table-column>
              </el-table>
          </div>
          <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false;extendedDisabled = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false;extendedDisabled = false">确 定</el-button>
          </span>
      </el-dialog>

  </basic-container>
</template>

<script>
  import {bportsList, bportsDetail, bportsSubmit, bportsRemove} from "@/api/iosBasicData/bports";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
          // 扩展数据弹窗
          dialogVisible:false,
          extendedDisabled:false,
        form: {
            extendedDataArr:[]
        },
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option:{},
        optionBack: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 24,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "港口编码",
              prop: "code",
                search: true,
              rules: [{
                required: true,
                message: "请输入港口编码",
                trigger: "blur"
              }]
            },
            {
              label: "国际编码",
              prop: "unCode",
                search: true,
              rules: [{
                required: true,
                message: "请输入国际编码",
                trigger: "blur"
              }]
            },
            {
              label: "中文名称",
              prop: "cnName",
                search: true,
              rules: [{
                required: true,
                message: "请输入中文名称",
                trigger: "blur"
              }]
            },
            {
              label: "英文名称",
              prop: "enName",
                search: true,
              rules: [{
                required: true,
                message: "请输入英文名称",
                trigger: "blur"
              }]
            },
            {
              label: "国家代码",
              prop: "cntyCode",
                search: true,
              rules: [{
                required: true,
                message: "请输入国家代码",
                trigger: "blur"
              }]
            },
            {
              label: "国家名称",
              prop: "cntyName",
                search: true,
              rules: [{
                required: true,
                message: "请输入国家名称",
                trigger: "blur"
              }]
            },
            {
              label: "是否海港",
              prop: "isSeaPort",
                type:'select',
                dicData:[{
                    label:'否',
                    value:0
                },{
                    label:'是',
                    value:1
                }],
              rules: [{
                required: true,
                message: "请输入是否海港",
                trigger: "blur"
              }]
            },
            {
              label: "是否空港",
              prop: "isAirPort",
                type:'select',
                dicData:[{
                    label:'否',
                    value:0
                },{
                    label:'是',
                    value:1
                }],
              rules: [{
                required: true,
                message: "请输入是否空港",
                trigger: "blur"
              }]
            },
            {
              label: "是否内陆港",
              prop: "isInlandPort",
                width:100,
                type:'select',
                dicData:[{
                    label:'否',
                    value:0
                },{
                    label:'是',
                    value:1
                }],
              rules: [{
                required: true,
                message: "请输入是否内陆港",
                trigger: "blur"
              }]
            },
            {
              label: "扩展数据",
              prop: "extendedDataArr",
                formslot:true,
              // rules: [{
              //   required: true,
              //   message: "请输入JSON 对象数组，用于不查询的扩展数据, 例如：[{name: key1, value: value1}]",
              //   trigger: "blur"
              // }]
            },
            {
              label: "版本",
              prop: "version",
                hide:true,
                display:false,
            },
            {
              label: "状态",
              prop: "status",
                type:'select',
                dicData:[{
                    label:'启用',
                    value:0
                },{
                    label:'停用',
                    value:1
                }],
            },
            {
              label: "是否已删除（0 否 1是）",
              prop: "isDeleted",
                hide:true,
                display:false,
            },
              {
                  label: "主键",
                  prop: "id",
                  hide:true,
                  display:false,
              },
              {
                  label: "创建人 Id",
                  prop: "createUser",
                  hide:true,
                  display:false,
              },
              {
                  label: "创建人",
                  prop: "createUserName",
                  display:false,
              },
              {
                  label: "创建部门 Id",
                  prop: "createDept",
                  hide:true,
                  display:false,
              },
              {
                  label: "创建部门",
                  prop: "createDeptName",
                  display:false,
              },
              {
                  label: "创建时间",
                  prop: "createTime",
                  width:160,
                  display:false,
              },
              {
                  label: "修改人 Id",
                  prop: "updateUser",
                  hide:true,
                  display:false,
              },
              {
                  label: "修改人",
                  prop: "updateUserName",
                  display:false,
              },
              {
                  label: "修改时间",
                  prop: "updateTime",
                  width:160,
                  display:false,
              },
            {
              label: "备注",
              prop: "remarks",
                span:24,
                type: 'textarea',
                width: "180",
                slot: true,
                minRows: 3,
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          // addBtn: this.vaildData(this.permission.bports_add, false),
          // viewBtn: this.vaildData(this.permission.bports_view, false),
          // delBtn: this.vaildData(this.permission.bports_delete, false),
          // editBtn: this.vaildData(this.permission.bports_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
      async created() {
          this.option = await this.getColumnData(this.getColumnName(298), this.optionBack);
      },
    methods: {
        // 扩展数据表格点击查询详情
        extendedDataview(row){
            this.form = row
            this.extendedDisabled = true
            this.dialogVisible = true
        },
        // 扩展数据弹窗关闭
        handleClose(done){
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => {});
        },
        // 扩展数据添加
        extendedDataAdd(){
            this.form.extendedDataArr.map(item=>{
                item.edit = false
            })
            this.form.extendedDataArr.push({
                edit:true
            })
        },
        // 扩展数据编辑
        extendedDataEdit(index,row) {
            row.edit = !row.edit
        },
        // 扩展数据删除
        extendedDataDelete(index,row) {
            this.form.extendedDataArr.splice(index,1)
        },

      rowSave(row, done, loading) {
          row.extendedDataArr.map(item=>{
              delete item.edit
          })
          row.extendedData = JSON.stringify(row.extendedDataArr)
          delete row.extendedDataArr
        bportsSubmit(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
          row.extendedDataArr.map(item=>{
              delete item.edit
          })
          row.extendedData = JSON.stringify(row.extendedDataArr)
          delete row.extendedDataArr
        bportsSubmit(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return bportsRemove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return bportsRemove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          bportsDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        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 = {}) {
        this.loading = true;
        bportsList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        //自定义列保存
        async saveColumnTwo(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 resetColumnTwo(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 scoped>
::v-deep#out-table .back-one {
    background: #ecf5ff !important;
}
::v-deep#out-table .back-two {
    background: #ecf5ff !important;
}
</style>
