<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <el-input v-model="searchParam.nameLike" clearable size="small" placeholder="企业名称" style="width: 200px;" class="filter-item" />
        <el-cascader
          v-model="searchParam.deptId"
          :options="administrativeAreaList"
          :props="{ checkStrictly: true, value: 'id' }"
          :show-all-levels="false"
          placeholder="所属区域"
          ></el-cascader>
        <!-- <el-select v-model="searchParam.auditState" placeholder="审核状态" clearable size="small" class="filter-item">
          <el-option v-for="e in enterpriseApi.auditStates()" :key="e.key" :label="e.value" :value="e.key" />
        </el-select> -->
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="searchSubmit">搜索</el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="searchParamReset">重置</el-button>
        <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-tooltip class="item" effect="dark" content="按当前查询条件导出" placement="top">
          <el-button :loading="exporting" class="filter-item" size="mini" type="info" plain icon="el-icon-download" @click="exportSubmit">导出</el-button>
        </el-tooltip>
      </div>
    </div>
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="addCompanyShow" :title="'企业信息'" width="1160px">
    <el-form ref="addCompanyForm" :model="mainDataEditing" :rules="mainFormRules" size="mini" label-width="170px" style="margin-right: 100px;">
      <el-row :gutter="10">
        <el-divider content-position="center">基础信息</el-divider>
        <el-col :span="12">
          <el-form-item label="企业名称：" prop="name">
            <el-input v-model="mainDataEditing.name"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司地址：" prop="address">
            <el-input v-model="mainDataEditing.address" maxlength="500" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="所属区域：" prop="_administrativeAreaCascade">
            <!-- <el-cascader v-model="mainDataEditing._administrativeAreaCascade" style="width: 100%;" :options="administrativeAreaList" clearable /> -->
            <el-cascader
                v-model="mainDataEditing._administrativeAreaCascade"
                :options="administrativeAreaList"
                :props="{ checkStrictly: true, value: 'id' }"
                :show-all-levels="false"
                ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属集团：" prop="">
            <!-- <el-select   v-model="mainDataEditing.dict41" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in dict41List" :key="item.id" :label="item.value" :value="item.id" />
            </el-select> -->
            <el-select
              v-model="mainDataEditing.pid"
              placeholder="请输入企业"
              clearable
            >
              <el-option
                v-for="item in options4enterpriseIdList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="单位性质：" prop="dict1">
            <el-select   v-model="mainDataEditing.dict1" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in dict1List" :key="item.id" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经济类型：" prop="dict2">
            <el-select   v-model="mainDataEditing.dict2" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in dict2List" :key="item.id" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="行业类别：" prop="dict3">
            <el-select   v-model="mainDataEditing.dict3" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in dict3List" :key="item.id" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="统一社会信用代码：" prop="idCode">
            <el-input v-model="mainDataEditing.idCode" maxlength="100" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="是否有注册资本：" prop="hasRegisteredCapital">
            <el-radio-group v-model="mainDataEditing.hasRegisteredCapital" size="mini">
              <el-radio-button :label="true">是</el-radio-button>
              <el-radio-button :label="false">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="mainDataEditing.hasRegisteredCapital" label="注册资本（万元）：" prop="registeredCapital">
            <el-input-number v-model="mainDataEditing.registeredCapital" :precision="2" :controls="false" style="width: 100%;" :min="0" :max="999999" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="18">
          <el-form-item label="经营范围：" prop="businessScope">
            <el-input v-model="mainDataEditing.businessScope" type="textarea" :rows="3" maxlength="1000" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="center">企业资质</el-divider>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="成立日期：" prop="setupDate">
            <el-date-picker   v-model="mainDataEditing.setupDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="经营期限（起）：" prop="beginLimitDate">
            <el-date-picker   v-model="mainDataEditing.beginLimitDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经营期限（止）：" prop="endLimitDate">
            <el-date-picker   v-model="mainDataEditing.endLimitDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="生产经营方式：" prop="dict4">
            <el-select   v-model="mainDataEditing.dict4" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in dict4List" :key="item.id" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="企业规模：" prop="dict5">
            <el-select   v-model="mainDataEditing.dict5" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in dict5List" :key="item.id" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否规模以上企业：" prop="dict6">
            <el-select   v-model="mainDataEditing.dict6" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in dict6List" :key="item.id" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="隶属层级：" prop="dict7">
            <el-select   v-model="mainDataEditing.dict7" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in dict7List" :key="item.id" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="责任人：" prop="liablePerson">
            <el-input   v-model="mainDataEditing.liablePerson" maxlength="30" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任人电话：" prop="liablePersonPhone">
            <el-input   v-model="mainDataEditing.liablePersonPhone" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="生产经营地址：" prop="businessAddress">
            <el-input   v-model="mainDataEditing.businessAddress" maxlength="500" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="center">证书</el-divider>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="采矿许可证：" prop="_workLicenseFileList">
            <el-upload
               
              class="upload-demo"
              :action="`${baseApi}/api/file/upload`"
              multiple
              :headers="httpHeaders"
              :limit="1"
              :on-success="upFileSuccessWork"
              :on-remove="upFileRemoveWork"
              :on-error="upFileError"
              :on-exceed="upFileExceed"
              :before-upload="upFileBefore"
              :on-preview="openFile"
              :file-list="mainDataEditing._workLicenseFileListShow"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片不要超过20M，仅支持jpeg、png格式</div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <div>
            <el-form-item label="采矿许可有效期：" prop="workLicenseBeginDate">
              <el-date-picker   v-model="mainDataEditing.workLicenseBeginDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="至：" prop="workLicenseEndDate">
              <el-date-picker   v-model="mainDataEditing.workLicenseEndDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="安全生产许可证：" prop="_safetyLicenseFileList">
            <el-upload
               
              class="upload-demo"
              :action="`${baseApi}/api/file/upload`"
              multiple
              :headers="httpHeaders"
              :limit="1"
              :on-success="upFileSuccessSafety"
              :on-remove="upFileRemoveSafety"
              :on-error="upFileError"
              :on-exceed="upFileExceed"
              :before-upload="upFileBefore"
              :on-preview="openFile"
              :file-list="mainDataEditing._safetyLicenseFileListShow"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片不要超过20M，仅支持jpeg、png格式</div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <div>
            <el-form-item label="安全许可有效期：" prop="safetyLicenseBeginDate">
              <el-date-picker   v-model="mainDataEditing.safetyLicenseBeginDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="至：" prop="safetyLicenseEndDate">
              <el-date-picker   v-model="mainDataEditing.safetyLicenseEndDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-divider content-position="center">位置</el-divider>
      <el-row :gutter="100">
        <el-col :span="12">
          <el-form-item label="经度：" prop="longitude">
            <el-input-number   v-model="mainDataEditing.longitude" :precision="6" :controls="false" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度：" prop="latitude">
            <el-input-number   v-model="mainDataEditing.latitude" :precision="6" :controls="false" style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="100">
        <el-col :span="18">
          <el-form-item label="位置地图：">
            <AMapSearchPointAdd :is-search="true" :point="mapPoint4add" @choosePoint="choosePoint" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="addCompanyShow=false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确认</el-button>
      </div>
    </el-dialog>
    <!--企业信息窗-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog1Show" :title="'企业信息'" width="1160px">
      <el-form ref="mainForm" :model="dialog1Data" size="mini" label-width="170px">
        <el-divider content-position="left">基础信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="企业名称：" prop="name">
              <span>{{ dialog1Data.name }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司地址：" prop="address">
              <span>{{ dialog1Data.address }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属区域：">
              <span>{{ dialog1Data.deptName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属集团：">
              <span>{{ dialog1Data.pName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位性质：" prop="dict1">
              <span>{{ dialog1Data.dict1Name }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经济类型：" prop="dict2">
              <span>{{ dialog1Data.dict2Name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行业类别：" prop="dict3">
              <span>{{ dialog1Data.dict3Name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否有注册资本：" prop="hasRegisteredCapital">
              <span>
                {{ dialog1Data.hasRegisteredCapital === true ? '是' : '' }}
                {{ dialog1Data.hasRegisteredCapital === false ? '否' : '' }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dialog1Data.hasRegisteredCapital" label="注册资本：" prop="registeredCapital">
              <span>{{ dialog1Data.registeredCapital }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="经营范围：" prop="businessScope">
              <span>{{ dialog1Data.businessScope }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">企业资质</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成立日期：" prop="setupDate">
              <span>{{ dialog1Data.setupDate }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经营期限（起）：" prop="beginLimitDate">
              <span>{{ dialog1Data.beginLimitDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经营期限（止）：" prop="endLimitDate">
              <span>{{ dialog1Data.endLimitDate }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产经营方式：" prop="dict4">
              <span>{{ dialog1Data.dict4Name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="企业规模：" prop="dict5">
              <span>{{ dialog1Data.dict5Name }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否规模以上企业：" prop="dict6">
              <span>{{ dialog1Data.dict6Name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="隶属层级：" prop="dict7">
              <span>{{ dialog1Data.dict7Name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="责任人：" prop="liablePerson">
              <span>{{ dialog1Data.liablePerson }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任人电话：" prop="liablePersonPhone">
              <span>{{ dialog1Data.liablePersonPhone }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产经营地址：" prop="businessAddress">
              <span>{{ dialog1Data.businessAddress }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码：" prop="idCode">
              <span>{{ dialog1Data.idCode }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">证书</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采矿许可证：" prop="_workLicenseFileList">
              <div v-for="file in dialog1Data._workLicenseFileList" :key="file.url">
                <el-link type="primary" @click="openFile(file)">{{ file.name }}</el-link>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div>
              <el-form-item label="采矿许可有效期：" prop="workLicenseBeginDate">
                <span>{{ dialog1Data.workLicenseBeginDate }}</span>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="至：" prop="workLicenseEndDate">
                <span>{{ dialog1Data.workLicenseEndDate }}</span>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安全生产许可证：" prop="_safetyLicenseFileList">
              <div v-for="file in dialog1Data._safetyLicenseFileList" :key="file.url">
                <el-link type="primary" @click="openFile(file)">{{ file.name }}</el-link>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div>
              <el-form-item label="安全许可有效期：" prop="safetyLicenseBeginDate">
                <span>{{ dialog1Data.safetyLicenseBeginDate }}</span>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="至：" prop="safetyLicenseEndDate">
                <span>{{ dialog1Data.safetyLicenseEndDate }}</span>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-divider content-position="left">位置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度：" prop="longitude">
              <span>{{ dialog1Data.longitude }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度：" prop="latitude">
              <span>{{ dialog1Data.latitude }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item v-show="dialog1Data.longitude && dialog1Data.latitude" label="位置地图：">
              <AMapSearchPoint :is-search="false" :point="mapPoint" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <!--审核确认窗-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog2Show" :title="'请确认'" width="580px">
      <span>确认要</span>
      <span v-show="dialog2Data.auditState===2" style="color:#66cb71;font-weight:bold;">通过</span>
      <span v-show="dialog2Data.auditState===3" style="color:#e75851;font-weight:bold;">拒绝</span>
      <span style="font-weight:bold;">{{ dialog2Data.name }}</span>
      <span>的申请吗？</span>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog2Show=false">取消</el-button>
        <el-button :loading="dialog2Saving" type="primary" @click="dialog2Submit">确认</el-button>
      </div>
    </el-dialog>
    <!--表格-->
    <el-table ref="table" v-loading="searching" :data="tableData" row-key="id" @select="tableSelectChange" @select-all="tableSelectAll" @selection-change="tableSelectionChange">
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column :show-overflow-tooltip="true" label="编号" prop="id" width="100px" align="center" />
      <el-table-column :show-overflow-tooltip="true" label="企业名称" prop="name" align="center" />
      <el-table-column :show-overflow-tooltip="true" label="所属区域" prop="deptName" align="center" />

      <!-- <el-table-column :show-overflow-tooltip="true" label="审核状态" prop="auditState" align="center">
        <template slot-scope="scope">
          <span v-for="e in enterpriseApi.auditStates()" :key="e.key">
            <span v-if="e.key==scope.row.auditState">{{ e.value }}</span>
          </span>
        </template>
      </el-table-column> -->
      <el-table-column :show-overflow-tooltip="true" label="统一社会信用代码" prop="idCode" align="center" />
      <el-table-column :show-overflow-tooltip="true" label="成立日期" prop="setupDate" align="center" />
      <el-table-column :show-overflow-tooltip="true" label="公司地址" prop="address" align="center" />
      <el-table-column :show-overflow-tooltip="true" label="法定代表人" prop="liablePerson" align="center" />
      <el-table-column :show-overflow-tooltip="true" label="法人电话" prop="liablePersonPhone" align="center" />
      <el-table-column :show-overflow-tooltip="true" label="采矿许可证有效期至" prop="workLicenseEndDate" align="center">
        <template slot-scope="scope">
          <span :style="{'color':dateToNow(scope.row.workLicenseEndDate)<0?'#F56C6C':dateToNow(scope.row.workLicenseEndDate)<30?'#E6A23C':null}">
            {{ scope.row.workLicenseEndDate }}
          </span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="安全生产许可证有效期至" prop="safetyLicenseEndDate" align="center">
        <template slot-scope="scope">
          <span :style="{'color':dateToNow(scope.row.safetyLicenseEndDate)<0?'#F56C6C':dateToNow(scope.row.safetyLicenseEndDate)<30?'#E6A23C':null}">
            {{ scope.row.safetyLicenseEndDate }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" round @click="showEnterpriseInfo(scope.row.id)">查看详情</el-button>
          <el-button size="mini" round @click="editEnterpriseInfo(scope.row)">修改</el-button>
          <el-button size="mini" round @click="deleteEnterpriseInfo(scope.row)">删除</el-button>

          <!-- <el-button v-show="scope.row.auditState==1" size="mini" round @click="auditBtn(scope.row, 2)">通过</el-button>
          <el-button v-show="scope.row.auditState==1" size="mini" round @click="auditBtn(scope.row, 3)">不通过</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      :page-sizes="[10, 20, 50, 100]"
      :current-page.sync="searchParam.page"
      :page-size.sync="searchParam.count"
      :total="searchResult.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="searchSubmit"
      @current-change="searchSubmit"
    />
  </div>
</template>

<script>
import enterpriseApi from '@/api/kd/enterprise'
import dictionaryApi from '@/api/kd/dictionary'

import AMapSearchPoint from '@/components/AMap/AMapSearchPoint'
import AMapSearchPointAdd from '@/components/AMap/AMapSearchPointAdd'

import { getDeptList } from '@/api/system/dept'
import {getCompanyList} from '@/api/system/user'
import request from '@/utils/request'
      

import administrativeAreaApi from '@/api/kd/administrativeArea'
import { mapGetters } from 'vuex'
import { downloadFile } from '@/utils'
import { getToken } from '@/utils/auth'
import { validatePhone } from '@/utils/validate'


const searchParam = {// 默认搜索条件
  page: 1,
  count: 10,
  searchCount: true,
  nameLike: '',
  auditState: '',
  deptId: ''
}
export default {
  name: 'CEnterprise', // 本页面名
  components: { AMapSearchPoint, AMapSearchPointAdd },
  data() {
    return {
      /**
       * 新增字段
       */
       httpHeaders: {
        'Authorization': getToken()
      },
       addCompanyShow: false,
       mainDataEditing: {},
       dict1List: [],
      dict2List: [],
      dict3List: [],
      dict4List: [],
      dict5List: [],
      dict6List: [],
      dict7List: [],
      dict41List: [], // 企业类型
      administrativeAreaList: [],
      options4enterpriseIdList: [],
      dialog1FormRules: {
        code: [{ required: true, message: '请输入' }]
      },
      mainFormRules: {
        name: [{ required: true, message: '请输入' }],
        idCode: [{ required: true, message: '请输入' }],
        _administrativeAreaCascade: [{ required: true, message: '请选择' }],
        address: [{ required: true, message: '请输入' }],
        dict1: [{ required: true, message: '请选择' }],
        dict2: [{ required: true, message: '请选择' }],
        dict3: [{ required: true, message: '请选择' }],
        hasRegisteredCapital: [{ required: true, message: '请选择' }],
        registeredCapital: [{ required: true, message: '请输入' }],
        businessScope: [{ required: true, message: '请输入' }],
        setupDate: [{ required: true, message: '请选择' }],
        beginLimitDate: [{ required: true, message: '请选择' }],
        endLimitDate: [{ required: true, message: '请选择' }],
        dict4: [{ required: true, message: '请选择' }],
        dict5: [{ required: true, message: '请选择' }],
        dict6: [{ required: true, message: '请选择' }],
        dict7: [{ required: true, message: '请选择' }],
        dict41: [{ required: true, message: '请选择' }],

        liablePerson: [{ required: true, message: '请输入' }],
        liablePersonPhone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        businessAddress: [{ required: true, message: '请输入' }],
        longitude: [{ required: true, message: '请选择位置' }],
        latitude: [{ required: true, message: '请选择位置' }],
        _workLicenseFileList: [{ required: true, message: '请选择' }],
        workLicenseBeginDate: [{ required: true, message: '请选择' }],
        workLicenseEndDate: [{ required: true, message: '请选择' }],
        _safetyLicenseFileList: [{ required: true, message: '请选择' }],
        safetyLicenseBeginDate: [{ required: true, message: '请选择' }],
        safetyLicenseEndDate: [{ required: true, message: '请选择' }]
      },

      searching: false,
      exporting: false,
      enterpriseApi: enterpriseApi,
      searchParam: {
        nameLike: '',
        auditState: '',
        deptId: ''
      },
      searchResult: {
        total: 0,
        results: [] // 搜索结果
      },
      dialog1Show: false,
      dialog1Data: {},
      dialog2Show: false,
      dialog2Saving: false,
      dialog2Data: {}
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ]),
    tableData() {
      // 将返回结果转换为可展示文本
      return this.searchResult.results
    },
    mapPoint() {
      if (this.dialog1Data.longitude && this.dialog1Data.latitude) {
        return [this.dialog1Data.longitude * 1, this.dialog1Data.latitude * 1]
      }
      return null
    },
    mapPoint4add() {
        if (this.mainDataEditing.longitude && this.mainDataEditing.latitude) {
          return [this.mainDataEditing.longitude * 1, this.mainDataEditing.latitude * 1]
        }
      return null
    }
  },
  mounted() {
    // administrativeAreaApi.cascadeElementUI().then(response => {
    //   this.administrativeAreaList = response.results
    // })

      getDeptList({
      }).then((res) => {
        this.administrativeAreaList = res.body.content;
      });
      getCompanyList({
        // deptId 
      })
      .then((res) => {
        this.options4enterpriseIdList = res.body;
      });

    const dictGroups = [1, 2, 3, 4, 5, 6, 7]
    dictGroups.forEach(i => {
      dictionaryApi.getList({ 'groupCode': i }).then(response => {
        this['dict' + i + 'List'] = response.results
      })
    })
    this.searchParamReset()
    this.searchSubmit()
  },
  methods: {

    /**
     * 企业新增
     */
     confirmAdd(){
      this.$refs.addCompanyForm.validate((valid) => {
        if (valid) {
          if (this.mainDataEditing.beginLimitDate >= this.mainDataEditing.endLimitDate) {
            this.$message.error('经营期限（起）应小于经营期限（止）')
          } else if (this.mainDataEditing.workLicenseBeginDate >= this.mainDataEditing.workLicenseEndDate) {
            this.$message.error('采矿许可有效期（起）应小于采矿许可有效期（止）')
          } else if (this.mainDataEditing.safetyLicenseBeginDate >= this.mainDataEditing.safetyLicenseEndDate) {
            this.$message.error('安全许可有效期（起）应小于安全许可有效期（止）')
          }else{
            this.addCompanyLoading = true
            
            this.mainDataEditing.deptId = this.mainDataEditing._administrativeAreaCascade[this.mainDataEditing._administrativeAreaCascade.length - 1]
            delete this.mainDataEditing._administrativeAreaCascade
            if (this.mainDataEditing._workLicenseFileList) {
              this.mainDataEditing.workLicenseFilePath = JSON.stringify(this.mainDataEditing._workLicenseFileList)
            }
            if (this.mainDataEditing._safetyLicenseFileList) {
              this.mainDataEditing.safetyLicenseFilePath = JSON.stringify(this.mainDataEditing._safetyLicenseFileList)
            }
            
            if(this.mainDataEditing.id){
              let enterprise = JSON.parse(JSON.stringify(this.mainDataEditing))
              enterprise.name = null
              enterprise.createDatetime = null
              enterprise.createBy = null
              enterprise.updateDatetime = null
              enterprise.updateBy = null
              enterprise.hasEnable = null
              enterprise.applyDatetime = null
              enterprise.auditState = null
              enterprise.auditDatetime = null
              enterprise.auditBy = null
              request({
                url: 'api/enterprise/set-my',
                method: 'post',
                data: enterprise
              }).then(() => {
                this.addCompanyLoading = false
                this.addCompanyShow = false
                this.$message({
                  message: '操作完成',
                  type: 'success'
                })
                this.searchSubmit()
              }).catch(() => {
                this.addCompanyLoading = false
                this.addCompanyShow = false
              })
            }else{
              request({
                url: 'api/enterprise/add/enterpriseList',
                method: 'post',
                data: this.mainDataEditing
              }).then(() => {
                this.addCompanyLoading = false
                this.addCompanyShow = false
                this.$message({
                  message: '操作完成',
                  type: 'success'
                })
                this.searchSubmit()
              }).catch(() => {
                this.addCompanyLoading = false
                this.addCompanyShow = false
              })
            }
          }
        }else{
          this.$message({
            message: '填写不满足要求，请检查',
            type: 'error'
          })
        }
      });
     
     },
    add(){
      this.mainDataEditing = {}
      // this.mainDataEditing.id = null
      this.addCompanyShow = true
    },
     elementuiUpListFormat(fileList) {
      const filePathArray = []
      fileList.forEach(f => {
        if (f.response && f.response.result) {
          filePathArray.push({
            name: f.name,
            url: f.response.result
          })
        } else if (f.name && f.url) {
          filePathArray.push({
            name: f.name,
            url: f.url
          })
        }
      })
      return filePathArray
    },
    upFileSuccessWork(response, file, fileList) {
      if (!this.mainDataEditing._workLicenseFileList) {
        this.mainDataEditing._workLicenseFileList = []
      }
      this.mainDataEditing._workLicenseFileList.push({
        name: file.name,
        url: response.result
      })
      this.$set(this.mainDataEditing, '_workLicenseFileList', this.mainDataEditing._workLicenseFileList)
    },
    upFileRemoveWork(file, fileList) {
      this.mainDataEditing._workLicenseFileList = this.elementuiUpListFormat(fileList)
    },
    upFileSuccessSafety(response, file, fileList) {
      if (!this.mainDataEditing._safetyLicenseFileList) {
        this.mainDataEditing._safetyLicenseFileList = []
      }
      this.mainDataEditing._safetyLicenseFileList.push({
        name: file.name,
        url: response.result
      })
      this.$set(this.mainDataEditing, '_safetyLicenseFileList', this.mainDataEditing._safetyLicenseFileList)
    },
    upFileRemoveSafety(file, fileList) {
      this.mainDataEditing._safetyLicenseFileList = this.elementuiUpListFormat(fileList)
    },
    upFileError() {
      this.$message.error('上传失败，请稍后再试')
    },
    upFileExceed() {
      this.$message.error('只可以上传一张照片')
    },
    upFileBefore(file) {
      const isIMG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLtSize = file.size / 1024 / 1024 < 20
      if (!isIMG) {
        this.$message.error('上传图片只能是 JPG/JPEG/PNG 格式')
        return false
      }
      if (!isLtSize) {
        this.$message.error('上传图片大小不能超过 20MB')
        return false
      }
      return true
    },
    openFile(file) {
      if (file.url) {
        window.open(this.baseApi + '/file' + file.url)
      } else if (file.response && file.response.result) {
        window.open(this.baseApi + '/file' + file.response.result)
      }
    },
    choosePoint(lnglat) {
      console.log(lnglat)
      if (lnglat) {
        this.$set(this.mainDataEditing, 'longitude', lnglat[0])
        this.$set(this.mainDataEditing, 'latitude', lnglat[1])
      } else {
        this.$set(this.mainDataEditing, 'longitude', null)
        this.$set(this.mainDataEditing, 'latitude', null)
      }
    },
    searchParamReset() {
      this.searchParam = JSON.parse(JSON.stringify(searchParam))
    },
    searchSubmit() {
      this.searching = true
      let deptId = this.searchParam.deptId[this.searchParam.deptId.length -1 ]
      enterpriseApi.getPage({
        ...this.searchParam,
        deptId
      }).then(response => {
        this.searchResult = response
        this.searching = false
      }).catch(() => {
        this.searching = false
      })
    },
    exportSubmit() {
      this.exporting = true
      enterpriseApi.export(this.searchParam).then(response => {
        downloadFile(response, '企业信息', 'xlsx')
        this.exporting = false
      }).catch(() => {
        this.exporting = false
      })
    },
    auditBtn(enterprise, auditState) {
      this.dialog2Data = JSON.parse(JSON.stringify(enterprise))
      this.dialog2Data.auditState = auditState
      this.dialog2Show = true
    },
    dialog2Submit() {
      this.doAudit(this.dialog2Data)
    },
    deleteEnterpriseInfo(row){
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(
        () => {
          enterpriseApi.deleteById([row.id]).then((res) => {
            this.$message.success("操作成功");
            this.searchSubmit();
          });
        },
        () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        }
      );
    },
    editEnterpriseInfo(row){
      this.addCompanyShow = true
      this.mainDataEditing = row
      if (this.mainDataEditing.workLicenseFilePath) {
        this.mainDataEditing._workLicenseFileList = JSON.parse(this.mainDataEditing.workLicenseFilePath)
        this.mainDataEditing._workLicenseFileListShow = JSON.parse(this.mainDataEditing.workLicenseFilePath) // 数据存放与原始绑定分开，可以防止中途赋值产生的闪烁问题
      }
      if (this.mainDataEditing.safetyLicenseFilePath) {
        this.mainDataEditing._safetyLicenseFileList = JSON.parse(this.mainDataEditing.safetyLicenseFilePath)
        this.mainDataEditing._safetyLicenseFileListShow = JSON.parse(this.mainDataEditing.safetyLicenseFilePath) // 数据存放与原始绑定分开，可以防止中途赋值产生的闪烁问题
      }
      this.mainDataEditing._administrativeAreaCascade = [row.deptId]
    },
    showEnterpriseInfo(enterpriseId) {
      enterpriseApi.getById(enterpriseId).then(response => {
        this.dialog1Data = response
        if (this.dialog1Data.workLicenseFilePath) {
          this.dialog1Data._workLicenseFileList = JSON.parse(this.dialog1Data.workLicenseFilePath)
        }
        if (this.dialog1Data.safetyLicenseFilePath) {
          this.dialog1Data._safetyLicenseFileList = JSON.parse(this.dialog1Data.safetyLicenseFilePath)
        }
        this.dialog1Show = true
      })
    },
    tableSelectChange(selection, row) {
      console.log('select', selection, row, this.tableData)
    },
    tableSelectAll(selection) {
      console.log('selectAll', selection, this.tableData)
    },
    tableSelectionChange(selection) {
      console.log('selectionChange', selection, this.tableData)
    },
    doAudit(enterprise) {
      this.dialog2Saving = true
      enterpriseApi.audit(enterprise).then(() => {
        this.dialog2Saving = false
        this.dialog2Show = false
        this.$message({
          message: '审核完成',
          type: 'success'
        })
        this.searchSubmit()
      }).catch(() => {
        this.dialog2Saving = false
        this.dialog2Show = false
      })
    },
    openFile(file) {
      if (file.url) {
        window.open(this.baseApi + '/file' + file.url)
      } else if (file.response && file.response.result) {
        window.open(this.baseApi + '/file' + file.response.result)
      }
    },
    dateToNow(dateString) {
      return (new Date(dateString).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
  ::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
    height: 30px;
    line-height: 30px;
  }
</style>
