<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input
          v-model="queryParams.enterpriseName"
          placeholder="请输入企业名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否有许可证" prop="haslicenseKey" label-width="100px">
      <el-select v-model="queryParams.haslicenseKey" placeholder="请选择是否有许可证" clearable size="small">
        <el-option label="全部" value=""></el-option>
        <el-option label="是" value="1"></el-option>
        <el-option label="否" value="0"></el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="许可证编号" prop="licenseKey" label-width="90px">
        <el-input
          v-model="queryParams.licenseKey"
          placeholder="请输入许可证编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport">导入</el-button>
        </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          type="info"
          @click="getGovermentTaskInfo"
        >从省平台获取数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="企业id" align="center" prop="enterpriseId" />-->
      <el-table-column label="企业名称" align="center" prop="enterpriseName" >
        <span slot-scope="scope" v-if="scope.row.enterpriseName">{{scope.row.enterpriseName}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="企业类型" align="center" prop="enterpriseType" :formatter="enterpriseTypeFormat">
      </el-table-column>
      <el-table-column label="注册地址" align="center" prop="registerAddress" >
        <span slot-scope="scope" v-if="scope.row.registerAddress">{{scope.row.registerAddress}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="法定代表人" align="center" prop="legalRepresentative" >
        <span slot-scope="scope" v-if="scope.row.legalRepresentative">{{scope.row.legalRepresentative}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="经营区域" align="center" prop="businessArea">
        <span slot-scope="scope" v-if="scope.row.businessArea">{{scope.row.businessArea}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contact">
        <span slot-scope="scope" v-if="scope.row.contact">{{scope.row.contact}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="phone">
        <span slot-scope="scope" v-if="scope.row.phone">{{scope.row.phone}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="许可证编号" align="center" prop="licenseKey" >
        <span slot-scope="scope" v-if="scope.row.licenseKey">{{scope.row.licenseKey}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="许可证有效期" align="center" prop="licenseValidityTime" >
        <span slot-scope="scope" v-if="scope.row.licenseValidityTime">{{scope.row.licenseValidityTime}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="年度监督检查情况" align="center" prop="annualSupervisionInspection" >
        <span slot-scope="scope" v-if="scope.row.annualSupervisionInspection">{{scope.row.annualSupervisionInspection}}</span>
        <span v-else>-</span>
      </el-table-column>

      <el-table-column label="营业执照" align="center" width="80" >
        <template slot-scope="List" v-if="List.row.doDusiness">
          <MyImage
            class="view-img"
            :src="List.row.doDusiness.split(',')[0]"
            :previewSrcList="List.row.doDusiness.split(',')"
          >
          </MyImage>
          <!--<img  v-for="item in List.row.doDusiness.split(',')" :src="item" width="100px">-->
        </template>
      </el-table-column>
      <!--<el-table-column label="营业执照" align="center"  >-->
        <!--<template slot-scope="List">-->
          <!--<span-->
            <!--class="dbtn"-->
            <!--@click="checkFile(List.row.doDusiness)"-->
            <!--v-if="List.row.doDusiness"-->
          <!--&gt;-->
            <!--<i class="el-icon el-icon-view"></i>查看/下载-->
          <!--</span>-->
          <!--<span v-else>-</span>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <DetailInfo ref="detail"/>
    <!-- 添加或修改企业信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业类型" prop="enterpriseType">
              <el-select v-model="form.enterpriseType" placeholder="请选类型" style="width: 100%;">
                <el-option
                  v-for="item in options"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="parseInt(item.dictValue)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="23">
            <el-form-item label="注册地址" prop="registerAddress">
              <el-input v-model="form.registerAddress" placeholder="请输入注册地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="法定代表人" prop="legalRepresentative">
              <el-input v-model="form.legalRepresentative" placeholder="请输入法定代表人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="许可证有效期" prop="licenseValidityTime">
              <el-date-picker
                v-model="form.licenseValidityTime"
                type="date"
                placeholder="请选择许可证有效期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
           <el-form-item label="许可证编号" prop="licenseKey">
             <el-input v-model="form.licenseKey" placeholder="请输入许可证编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经营区域" prop="businessArea">
              <el-input v-model="form.businessArea" placeholder="请输入经营区域" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="负责人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="23">
            <el-form-item label="营业执照">
              <FileUpload
                :fileNum="6"
                listType="picture"
                @resFun="getFileInfo"
                @remove="listRemove"
                :fileArr="fileList">
              </FileUpload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="23">
            <el-form-item label="年度监督检查情况" prop="annualSupervisionInspection">
              <el-input v-model="form.annualSupervisionInspection" type="textarea" placeholder="请输入年度监督检查情况" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="23">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的企业数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo, exportInfo,importTemplate } from "@/api/regulation/info";
import MyImage from "@/components/MyImage/index.vue";
import FileUpload from '@/components/FileSuperviseUpload';
import { getToken } from "@/utils/auth";
import DetailInfo from "./DetailInfo";
export default {
  name: "Info",
  components: {
    FileUpload,DetailInfo,MyImage
  },
  dicts: ['enterprise_type'],
  data() {
    return {
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "燃气企业信息导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/regulation/info/importData" // todo
      },
      //图片
      fileList: [],
      //头像数据
      fileo :{
        name: "",
        url:"" },
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      options: [],
      value: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enterpriseName:null,
        enterpriseName: null,
        registerAddress: null,
        legalRepresentative: null,
        businessArea: null,
        licenseKey: null,
        haslicenseKey:null,
        licenseValidityTime: null,
        annualSupervisionInspection: null,
        isDel: null,
        remarks: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        enterpriseName: [
          { required: true, message: "请输入企业名称", trigger: "blur" },
          // { min: 0, max: 20, message: "长度20位", trigger: "blur" },
        ],
        enterpriseType: [
          { required: true, message: "请选择分类", trigger: "blur" },
          // { min: 0, max: 20, message: "长度20位", trigger: "blur" },
        ],
        registerAddress: [
          { required: true, message: "请输入注册地址", trigger: "blur" },
          // { min: 0, max: 20, message: "长度20位", trigger: "blur" },
        ],
        legalRepresentative: [
          { required: true, message: "请输入法定代表人", trigger: "blur" },
          // { min: 0, max: 20, message: "长度20位", trigger: "blur" },
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("enterprise_type").then(response => {
      this.options = response.data;
      console.log("this.options = " + JSON.stringify(this.options))
    });
  },
  methods: {
    // 任务组名字典翻译
    enterpriseTypeFormat(row) {
      return this.selectDictLabel(this.options, row.enterpriseType);
    },

    handleImport(){
      this.upload.title = "燃气企业导入"; // todo
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
          this.download(response.msg);
      });
    },

    // 文件上传处理中
    handleFileUploadProgress(event,file,fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },

    //获取数据
    getGovermentTaskInfo(){
      this.$confirm('是否确认从省平台获取数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        ///return '';
      }).then(() => {
        ///this.getList();
      ///this.msgSuccess("从省平台获取数据成功");
    }).catch(() => {});
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /**上传营业执照照片*/
    getFileInfo(res){
      this.form.doDusiness = this.form.doDusiness?this.form.doDusiness+','+res.url:res.url;
      this.fileList.push({
        name: res.fileName,
        url: res.url,
      });
    },
    listRemove(e) {
      if(e){
        this.fileList = this.fileList.filter(obj => obj.url !== e.url);
        this.form.doDusiness =  this.fileList.map(obj => obj.url).join(', ');
      }
    },
    checkFile(url) {
      window.open(url,'_blank');
    },
    /** 查询企业信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        enterpriseId: null,
        enterpriseName: null,
        registerAddress: null,
        legalRepresentative: null,
        businessArea: null,
        licenseKey: null,
        haslicenseKey:null,
        licenseValidityTime: null,
        annualSupervisionInspection: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null,
        remarks: null,
        dealPlan:null,
        doDusiness: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.enterpriseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList =[];
      this.reset();
      this.open = true;
      this.title = "添加企业信息";
    },
    handleDetail(row){
      this.$refs.detail.getDetailInfo(row.enterpriseId);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.fileList =[];
      this.reset();
      const enterpriseId = row.enterpriseId || this.ids
      getInfo(enterpriseId).then(response => {
        this.form = response.data;
        //图片回显
        if (this.form.doDusiness) {
          for(var item of this.form.doDusiness.split(',')){
            this.fileList.push({
              name: '营业执照',
              url: item,
            });
          }
        }
        this.open = true;
        this.title = "修改企业信息";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.enterpriseId != null) {
            updateInfo(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const enterpriseIds = row.enterpriseId || this.ids;
      this.$confirm('是否确认删除企业名称为"' + row.enterpriseName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInfo(enterpriseIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企业信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportInfo(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style>
  .dbtn {
    display: inline-block;
    line-height: normal;
    padding-left: 2px;
    padding-right: 2px;
    cursor: pointer;
    border-radius: 3px;
    border-style: solid;
    border-width: 0;
    color: rgb(48, 180, 107);
  }
  .dbtn:hover {
    border-width: 1px;
    border-color: rgb(48, 180, 107);
  }
  .view-img{
    width: 50px;
    height: 50px;
  }
</style>
