<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" ref="filter-container">
      <el-form :rules="rules4Query" ref="queryForm" :inline="inline" :model="listQuery" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="名称">
              <el-input v-model="listQuery.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类型">
              <el-select class="filter-item" v-model="listQuery.type" placeholder="请选择随行物品类型">
                <el-option :key="undefined" label="无" :value="undefined"></el-option>
                <el-option v-for="(val, key, index) in accompanyItemTypeAndCode " :key="val.code" :label="val.val"
                           :value="val.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
            <el-button class="filter-item" v-if="accompanying_item_btn_add" style="margin-left: 10px;"
                       @click="handleCreate"
                       type="primary" icon="edit">添加
            </el-button>
          </el-col>
        </el-row>
      </el-form>

    </div>


    <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row
              style="width: 100%">

      <el-table-column align="center" label="名称">
        <template scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>

      <el-table-column  align="center" label="物品类型">
        <template scope="scope">
          <span>{{getTypeName(scope.row.type)}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="备注">
        <template scope="scope">
          <span>{{scope.row.remark}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="价格">
        <template scope="scope">
          <span>{{scope.row.price}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="最后更新时间">
        <template scope="scope">
          <span>{{scope.row.updateTime?scope.row.updateTime:scope.row.createTime}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="250">
        <template scope="scope">
          <el-button size="small" class="el-button el-button--text el-button--small"  @click="handleUpdate(scope.row)">{{accompanying_item_btn_update?'编辑':'查看'}}</el-button>
          <el-button v-if="accompanying_item_btn_del " size="small" class="el-button el-button--text el-button--small"  style="color: red;" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>


    <!--  增加/修改弹出框  -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">

      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"></el-input>
        </el-form-item>

        <el-form-item label="类型">
          <el-select class="filter-item" v-model="form.type" placeholder="请选择随行物品类型">
            <el-option v-for="(val, key, index) in accompanyItemTypeAndCode " :key="val.code" :label="val.val"
                       :value="val.code"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="5" v-model="form.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form4Apply')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-if="accompanying_item_btn_update&&dialogStatus=='update'" type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    page,
    addObj,
    getObj,
    delObj,
    putObj
  } from 'api/vehicle/accompanyingItem/';


  import {
    ACCOMPANYING_ITEM_AMOUNT_INFINITY
  } from '../../../store/modules/baseInfo';


  import rsCode from '../../../utils/rsCode';

  import {mapGetters} from 'vuex';


  export default {
    name: 'vehicleInfo',
    components: {},
    data() {
      return {
        form: {
          name: undefined,
          type: undefined,
          price:undefined
        },
        rules: {
          name: [
            {
              type: 'string',
              required: true,
              message: '请输入名称',
              trigger: 'blur'
            }
          ],
          remark: [
            {
              min: 0,
              max: 2000,
              message: '长度小于 2000 个字符',
              trigger: 'blur'
            }
          ],
          price: [
            {
              type: 'string',
              required: true,
              message: '请输入输入价格',
              trigger: 'blur'
            },{
              pattern: /^\d+$|^\d*\.\d+$/,
              message: '请输入正确的价格'
            }
          ]
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          name: undefined,
          type: undefined
        },
        rules4Query: undefined,
        dialogFormVisible: false,
        inline: true,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogStatus: undefined,
        tableKey: 0,
        accompanying_item_btn_update: false,
        accompanying_item_btn_del: false,
        accompanying_item_btn_add: false
      }
    },
    created() {
      this.getList();

      this.accompanying_item_btn_update = this.elements['accompanyingItem:btn_update'];
      this.accompanying_item_btn_del = this.elements['accompanyingItem:btn_del'];
      this.accompanying_item_btn_add = this.elements['accompanyingItem:btn_add'];
    },
    computed: {
      ...mapGetters([
        'elements',
        'accompanyItemTypeAndCode'
      ])
    },
    methods: {
      getTypeName: function (type) {
        if (this.$utils.isEmpty(this.accompanyItemTypeAndCode[type])) {
          return '未知';
        }
        return this.accompanyItemTypeAndCode[type].val;
      },
      getList() {
        this.listLoading = true;
        page(this.listQuery).then(response => {
          let totalCountRs = undefined;
          let listRs = undefined;
          if (!this.$utils.isEmpty(response.data.data) && this.$utils.isInteger(response.data.totalCount)) {
            listRs = response.data.data;
            totalCountRs = response.data.totalCount;
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        })
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.$refs.queryForm.validate(valid => {
          if (valid) {
            this.getList();
          } else {
            return false;
          }
        });
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleCreate() {
        this.resetTemp();
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
      },
      handleUpdate(row) {
        getObj(row.id)
          .then(response => {
            this.form = response.data;
            this.dialogFormVisible = true;
            this.dialogStatus = 'update';
          });
      },
      handleDelete(row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            delObj(row.id)
              .then(() => {
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                });
                const index = this.list.indexOf(row);
                this.list.splice(index, 1);
              });
          });
      },
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form)
              .then(response => {
                if (response.code === rsCode.RS_CODE_SUC) {
                  this.dialogFormVisible = false;
                  this.getList();
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  });
                } else {
                  this.$notify({
                    title: '失败',
                    message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                    type: 'error',
                    duration: 2000
                  });
                }
              });
          } else {
            return false;
          }
        });
      },
      cancel(formName) {
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
      },
      update(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            this.form.amount = undefined; // 不能直接修改数量
            putObj(this.form).then(response => {
              if (response.code === rsCode.RS_CODE_SUC) {
                this.dialogFormVisible = false;
                this.getList();
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                });
              } else {
                this.$notify({
                  title: '失败',
                  message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                  type: 'error',
                  duration: 2000
                });
              }
            });
          } else {
            return false;
          }
        });
      },
      resetTemp() {
        this.form = {
          name: undefined,
          type: undefined,
          price:undefined
        };
      }
    }
  }
</script>
