<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>
	  <form methods="post" enctype="multipart/form-data" style="display:inline-block;margin-left:10px;;">
		<el-button class="filter-item" type="primary" v-waves @click="choiceImg">导入</el-button>
		<input ref="filElem" type="file" name="file" class="upload-file" @change="getFile($event)" style="display:none;">
	  </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="ID" width="65">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="280" align="center" label="公司名称">
        <template slot-scope="scope">
          <span>{{scope.row.companyName}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110" align="center" label="剩余份额">
        <template slot-scope="scope">
          <span>{{scope.row.balance}}</span>
        </template>
      </el-table-column>

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

      <el-table-column align="center" label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="small" class="el-button el-button--text el-button--small" @click="handleUpdate(scope.row)">{{btn_edit?'编辑':'查看'}}</el-button>
          <el-button v-if="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="100px">
        <el-form-item label="公司名称" prop="companyId">
          <el-select class="filter-item" v-model="form.companyId" clearable  filterable placeholder="请选择公司">
            <el-option v-for="val in allBranchCompany" :key="val.id" :label="val.name" :value="val.id"> </el-option>
          </el-select>
        </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="排序">
          <el-input v-model.number="form.rank" placeholder="请输入排序"></el-input>
        </el-form-item>
        <!-- <el-form-item label="省份" prop="addrProvince">
          <el-select v-model.number="form.addrProvince" placeholder="请选择省份（直辖市）" @change="changeProvince">
            <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"
            :headers="getHeaderWithToken"
            :action="BASE_API+ '/api/universal/file/app/unauth/admin/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload" :style="{display:'block'}">
            <img v-if="$utils.isString(form.companyPic) && !$utils.isEmpty(form.companyPic)"
                 :src="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-tabs v-model="activeName2" type="card">
          <el-tab-pane label="公司详情" name="first">
            <div class="editor-container" v-if="activeName2=='first'">
              <UE :editorId="activeName2" :defaultMsg="form.info" :config=config  ref="ue"  @ready="editorReadyEvent"></UE>
            </div>
          </el-tab-pane>
        </el-tabs>
      </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-if="btn_edit&&dialogStatus=='update'" type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import UE from '../../modal/Ueditor';//百度ue富文本
  import 'static/css/uploadImg.css';
  import {
    search,
    getObj,
    addObj,
    updateObj,
    delObj
  } from 'api/branchCompany/stock/index';
  import {
    getAll
  } from 'api/base_info/branch_company/';
  import {
    getSonRegionByCodes,
    getRegionByCodes
  } from 'api/base_info/region/';
  import {
    getToken
  } from 'utils/auth';
  import {mapGetters} from 'vuex';
  import axios from 'axios';
  import rsCode from '../../../utils/rsCode';

  export default {
    name: 'branchCompanyStock',
    components: {
      UE
//      Editor
    },
    data() {
      return {
        activeName2: '',//详情
        config: {
          initialFrameWidth: null,
          initialFrameHeight: 350
        },
        allBranchCompany:[],
        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,
          companyId: undefined,
          balance: null,
          total: null,
          price: null,
          addrProvince: null,
          addrCity: null,
          state: null,
          companyPic: null,
          info:undefined
        },
        rules: {
          companyId: [
            {
              required: true,
              message: '请选择公司'
            }
          ],
          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();
      getAll().then(response => {
        this.allBranchCompany = response.data;
      })
      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: {
      editorReadyEvent(instance){
        let t = this;
        instance.addListener('contentChange', () => {
          if(t.activeName2 == "first"){
            t.form.info  = instance.getContent();
          }
        });
      },
      /**
       * 改变省份，清空城市
       * */
      changeProvince(){
        this.form.addrCity = undefined;
      },
      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 isLt2M;
      },
      handleAvatarSuccess(res) {
        this.form.companyPic = res.data;
        this.showLoadingBody = false;
        this.$forceUpdate();
      },
      handleUpdate(row) {
        this.cleanForm();
        this.form = row;
        if (row.state == 0) {
          this.state = undefined;
        }
        if(row.info!=undefined){
          this.form.info = row.info
        }else{
          this.form.info = ''
        }
        this.dialogFormVisible = true;
        this.activeName2 = "first";
        this.dialogStatus = 'update';
        // 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.activeName2 = "first";
        //     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( response => {
              if (response.status === 200) {
                this.dialogFormVisible = false;
                this.getList();
                this.$notify({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                });
              } else {
                this.$notify({
                  title: '失败',
                  message: response.message,
                  type: 'error',
                  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.status === 200) {
                  this.dialogFormVisible = false;
                  this.getList();
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  });
                } else {
                  this.$notify({
                    title: '失败',
                    message: response.message,
                    type: 'error',
                    duration: 2000
                  });
                }
              })
          } else {
            return false;
          }
        });
      },
      handleCancel(formName) {
        this.activeName2 = '';
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
      },
      handleCreate() {
        this.cleanForm();
        this.dialogStatus = 'create';
        this.activeName2 = "first";
        this.dialogFormVisible = true;
      },
      cleanForm() {
        this.form = {
          id: null,
          companyId: undefined,
          balance: null,
          total: null,
          price: null,
          addrProvince: null,
          addrCity: null,
          rank:'',
          info:''
        };
      },
      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();
      },
		choiceImg(){
			this.$refs.filElem.dispatchEvent(new MouseEvent('click'))
		},
		getFile(event){
			let formData = new FormData();
			formData.append('file',event.target.files[0]);
			let config = {
				headers: {
					'Content-Type': 'multipart/form-data'
				}
			}
			axios.post('/vehicle/branchCompany/stock/right/importExcel', formData, config).then(function (res) {
				if (res.status === 200) {
					/*这里做处理*/
				}else{
          this.$notify({
            title: '失败',
            message: res.message,
            type: 'error',
            duration: 2000
          });
        }
			})
		},
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      change() {
        this.form.state = this.state;
        if (!this.form.state) {
          this.form.state = 0;
        }
      }
    },
    watch:{
      dialogFormVisible(newVal,oldVal){
        if(newVal == false){
          this.activeName2 = '';
        }
      }
    }
  }
</script>
