<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="公司名称"
                v-model="listQuery.companyName"></el-input>
      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" v-if="btn_add" style="margin-left: 10px;" @click="handleCreate"
                 type="primary" icon="edit">添加
      </el-button>
    </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="ID" width="65">
        <template scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110" align="center" label="公司名称">
        <template scope="scope">
          <span>{{scope.row.companyName}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110" align="center" label="剩余份额">
        <template scope="scope">
          <span>{{scope.row.balance}}</span>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" label="总份额">
        <template scope="scope">
          <span>{{scope.row.total}}</span>
        </template>
      </el-table-column>
      <el-table-column width="180" align="center" label="股权单价">
        <template scope="scope">
          <span>{{scope.row.price}}</span>
        </template>
      </el-table-column>
      <el-table-column width="180" align="center" label="地区">
        <template scope="scope">
          <span>{{getAddrStr(scope.row.addrProvince, scope.row.addrCity)}}</span>
        </template>
      </el-table-column>
      <el-table-column width="180" align="center" label="状态">
        <template scope="scope">
          <span>{{stockStateStr.get(scope.row.state).label}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="150">
        <template scope="scope">
          <el-button v-if="btn_edit" size="small" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="btn_del" size="small" type="danger" @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="100px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称"></el-input>
        </el-form-item>
        <el-form-item label="剩余份额" prop="balance">
          <el-input v-model.number="form.balance" placeholder="请输入剩余份额"></el-input>
        </el-form-item>
        <el-form-item label="总份额" prop="total">
          <el-input v-model.number="form.total" placeholder="请输入总份额"></el-input>
        </el-form-item>
        <el-form-item label="股权单价" prop="price">
          <el-input v-model.number="form.price" placeholder="请输入股权单价"></el-input>
        </el-form-item>
        <el-form-item label="省份" prop="addrProvince">
          <el-select v-model.number="form.addrProvince" placeholder="请选择省份（直辖市）">
            <el-option v-for="item in provinceRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="城市" prop="addrCity">
          <el-select v-model.number="form.addrCity" placeholder="请选择城市">
            <el-option v-for="item in cityRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select class="filter-item" v-model.number="state" placeholder="请选择" @change="change">
            <el-option v-for="item in Array.from(stockStateStr.keys())" :key="stockStateStr.get(item).key"
                       :label="stockStateStr.get(item).label" :value="stockStateStr.get(item).value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司图片" prop="drivingLicensePath" :style="{display:'block'}">
          <el-upload
            class="avatar-uploader"
            :action="BASE_API + '/vehicle/branchCompany/stock/upload/companyPic'"
            :show-file-list="false"
            :headers="getHeaderWithToken"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload" :style="{display:'block'}">
            <img v-if="$utils.isString(form.companyPic) && !$utils.isEmpty(form.companyPic)"
                 :src="getCompanyPicUrl(form.companyPic)" class="avatar" :style="{display:'block'}">
            <i v-else class="el-icon-plus avatar-uploader-icon" :style="{lineHeight:'350px'}"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import 'static/css/uploadImg.css';
  import {
    search,
    getObj,
    addObj,
    updateObj,
    delObj
  } from 'api/branchCompany/stock/index';
  import {
    getSonRegionByCodes,
    getRegionByCodes
  } from 'api/base_info/region/';
  import {
    getToken
  } from 'utils/auth';
  import {mapGetters} from 'vuex';
  import rsCode from '../../../utils/rsCode';

  export default {
    name: 'branchCompanyStock',
    data() {
      return {
        BASE_API: process.env.BASE_API,
        showLoadingBody: false,
        state: null,
        stockStateStr: new Map([
          [-1, {
            key: -1,
            label: '下架',
            value: -1
          }],
          [0, {
            key: 0,
            label: '筹备中',
            v1ue: 0
          }],
          [1, {
            key: 1,
            label: '筹备完成',
            value: 1
          }],
          [2, {
            key: 2,
            label: '上架',
            value: 2
          }]
        ]),
        form: {
          id: null,
          companyName: null,
          balance: null,
          total: null,
          price: null,
          addrProvince: null,
          addrCity: null,
          state: null,
          companyPic: null
        },
        rules: {
          companyName: [
            {
              required: true,
              message: '请输入用户',
              trigger: 'blur'
            }
          ],
          total: [
            {
              required: true,
              message: '请输入总份额'
            }
          ],
          price: [
            {
              required: true,
              message: '请输入股权单价'
            }
          ]
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          companyName: null
        },
        dialogFormVisible: false,
        dialogStatus: '',
        btn_edit: false,
        btn_del: false,
        btn_add: false,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        tableKey: 0,
        addrProvince: [
          {
            required: true,
            type: 'number',
            message: '请选择省份',
            trigger: 'blur'
          }
        ],
        addrCity: [
          {
            required: true,
            type: 'number',
            message: '请选择城市',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (this.$utils.isInteger(this.form.addrProvince) &&
                value.toString().substr(0, 2) != this.form.addrProvince.toString().substr(0, 2)) {
                return callback(new Error('请选择省份下相应城市'));
              }
              callback();
            },
            trigger: 'blur'
          }
        ]
      }
    },
    created() {
      this.getList();
      this.btn_edit = this.elements['branchCompany/stock:btn_update'];
      this.btn_del = this.elements['branchCompany/stock:btn_delete'];
      this.btn_add = this.elements['branchCompany/stock:btn_add'];
    },
    computed: {
      ...mapGetters([
        'elements'
      ]),
      provinceRegions() {
        return getSonRegionByCodes(1);
      },
      cityRegions() {
        if (!this.$utils.isInteger(this.form.addrProvince)) {
          return null;
        }
        return getSonRegionByCodes(this.form.addrProvince);
      },
      getHeaderWithToken() {
        return {Authorization: getToken()};
      }
    },
    methods: {
      getCompanyPicUrl(companyPic) {
        return process.env.BASE_API +
          '/vehicle/branchCompany/stock/download/companyPic?realFileRelPath=' + encodeURI(companyPic);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/gif';
        const isLt2M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/GIF 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 10MB!');
        }
        this.showLoadingBody = true;
        return isJPG && isLt2M;
      },
      handleAvatarSuccess(res) {
        this.form.companyPic = res.data;
        this.showLoadingBody = false;
        this.$forceUpdate();
      },
      handleUpdate(row) {
        getObj(row.id)
          .then(response => {
            this.form = response.data;
            this.state = response.data.state;
            if (this.state == 0) {
              this.state = undefined;
            }
            console.log('get:state:' + response.data.state);
            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);
              });
          });
      },
      update(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            this.dialogFormVisible = false;
            this.form.password = undefined;
            updateObj(this.form).then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      getAddrStr(addrProvince, addrCity) {
        if (addrProvince && addrProvince) {
          const regions = getRegionByCodes([addrProvince, addrCity]);
          return regions[0].name + ' ' + regions[1].name;
        }
        return '';
      },
      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;
          }
        });
      },
      handleCancel(formName) {
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
      },
      handleCreate() {
        this.cleanForm();
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
      },
      cleanForm() {
        this.form = {
          id: null,
          companyName: null,
          balance: null,
          total: null,
          price: null,
          addrProvince: null,
          addrCity: null
        };
      },
      getList() {
        this.listLoading = true;
        search(this.listQuery)
          .then(response => {
            this.list = response.data.list;
            this.total = response.data.total;
            this.listLoading = false;
          })
      },
      handleFilter() {
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      change() {
        this.form.state = this.state;
        if (!this.form.state) {
          this.form.state = 0;
        }
      }
    }
  }
</script>
