<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div>
      <span style="font-size:14px">公司名称：</span>
      <el-input
        v-model="customerName"
        clearable
        placeholder="请输入公司名称"
        style="width: 200px;margin-bottom:20px"
        size="small"
        class="filter-item"
      />

      <span style="font-size:14px">公司类型：</span>
      <el-select v-model="typeId" style="margin-bottom:20px" size="medium" clearable value-key="areaId" filterable placeholder="请选择公司名称">
        <el-option
          v-for="item in customerType"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-button style=" width:90px;  " size="small" type="primary" icon="el-icon-search" @click="handleFind">查询
      </el-button>
      <el-button
        class="filter-item"
        size="small"
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增客户
      </el-button>
      <el-button
        class="filter-item"
        size="small"
        type="primary"
        icon="el-icon-upload"
        @click="handleBatchAdd"
      >批量导入
      </el-button>
    </div>
    <el-table v-loading="loading" :data="tableData" style="width: 100%">
      <el-table-column label="序号" fixed="left" width="60" align="center">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="公司编号"  align="center" fixed="left"  :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.customerId }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="客户名称" width="300" fixed="left" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.customerName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系电话" width="200" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>

      <el-table-column label="邮箱" width="250" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>

      <el-table-column label="投标类型" align="center" width="250" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.customerBidType === 1" size="small">物流</span>
            <span v-if="scope.row.customerBidType === 2" size="small">原料</span>
            <span v-if="scope.row.customerBidType === 3" size="small">销售</span>
            <span v-if="scope.row.customerBidType === 4" size="small">加工承揽</span>
            <span v-if="scope.row.customerBidType === 0" size="small">未知</span>
           <!--  <span v-if="scope.row.customerTypeDetails === 6" size="small">个人独资企业</span>
            <span v-if="scope.row.customerTypeDetails === 7" size="small">国有独资公司</span>
            <span v-if="scope.row.customerTypeDetails === 8" size="small">其他</span> -->
        </template>
      </el-table-column>

      <el-table-column label="公司类型" align="center" width="250" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <!-- <span>{{ scope.row.customerTypeDetails }}</span> -->
          <span v-if="scope.row.type === 1" size="small">有限责任公司（自然人独资）</span>
            <span v-if="scope.row.type === 2" size="small">有限责任公司(自然人投资或控股)</span>
            <span v-if="scope.row.type === 3" size="small">股份有限公司</span>
            <span v-if="scope.row.type === 4" size="small">有限合伙企业</span>
            <span v-if="scope.row.type === 5" size="small">外商独资公司</span>
            <span v-if="scope.row.type === 6" size="small">个人独资企业</span>
            <span v-if="scope.row.type === 7" size="small">国有独资公司</span>
            <span v-if="scope.row.type === 8" size="small">其他</span>
            <span v-if="scope.row.type === 0" size="small">未知</span>
        </template>
      </el-table-column>
      <el-table-column label="法定代表人" width="250" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.legalPerson }}</span>
        </template>
      </el-table-column>
      <el-table-column label="经营范围" width="250" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.businessScope }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册资本" width="250" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.registeredCapital }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成立日期" width="250" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.dateOfEstablishment }}</span>
        </template>
      </el-table-column>
      <el-table-column label="营业日期" width="250" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.businessDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="住所" width="250" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.residence }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" width="250" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.createDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" width="250" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>

      <!--     </div>
    </template>
  </el-table-column> -->

      <el-table-column label="操作" fixed="right" width="235" min-width="150" align="center">
        <template slot-scope="scope">
          <!-- <el-button type="text" icon="el-icon-view"  @click="lookRecord(scope.row)">查看</el-button> -->
          <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="pagination">
      <el-pagination
        :popper-class="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        background
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- <el-pagination
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        background
        @current-change="handleCurrentChange"
      /> -->
    </div>

    <!-- 批量上传 -->
       <el-dialog
      title="批量添加客户"
      width="45%"
      :visible.sync="batchVisible"
      :close-on-click-modal="false"
    >
    <!-- <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="batchVisible = false">取消</el-button>
        <el-button :size="size" type="primary" @click="batchVisible">确定</el-button>
      </span> -->
      <div style="padding:35px 0">
          <el-row type="flex" class="row-bg" justify="center" >
            <el-col :span="9">
              <div class="grid-content bg-purple" style="text-align: center;">
                <div>1、下载子设备模板，填写信息</div>
                <i class="el-icon-document"></i>
                <br/>
                <el-button @click="onFile">下载模板</el-button>
              </div>
            </el-col>
          <div style="border-right:0.5px solid #eee"></div>
            <el-col :span="9">
              <div class="grid-content bg-purple-light" style="text-align: center;">
                <div>2、上传填写好的文件</div>
                <i class="el-icon-document"></i>
                <el-upload
                  :action="BASE_API+'/customer/batch'"
                  :on-preview="handlePreview"
                  :on-change="handleChange"
                  name="multipartFile"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :on-exceed="handleExceed"
                  :on-error="hanndleErr"
                  multiple
                  :limit="3"
                  :file-list="fileList">
                  <el-button >上传文件</el-button>
                </el-upload>
              </div>
            </el-col>
          </el-row>
      </div>
      
        </el-dialog>

    <!-- 新增修改界面 -->
    <el-dialog
      :title="isEditForm ? '编辑' : '新增'"
      width="85%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="dataRule"
        label-width="80px"
        :size="size"
        style="text-align:left;"
        @keyup.enter.native="submitForm()"
      >
        <el-card shadow="never">
          <!-- <el-card  shadow="hover" > -->
          <div slot="header" class="clearfix">
            <span class="topClass">客户基本信息</span>
          </div>
          <el-row :gutter="20">
          <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                  <el-form-item label="客户名称" prop="customerName" :label-width="formLabelWidth">
                    <el-input v-model="dataForm.customerName" style="width:100%" placeholder="请输入客户名称" />
                  </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                  <el-form-item label="手机" prop="phone" :label-width="formLabelWidth">
                    <el-input v-model="dataForm.phone"  style="width:100%" placeholder="请输入手机" />
                  </el-form-item>
          </el-col>
           <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                      <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
                        <el-input v-model="dataForm.email" style="width:100%"  placeholder="请输入邮箱" />
                      </el-form-item>
                  </el-col>
          </el-row>
          <el-row :gutter="20">
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
               <el-form-item label="投标类型" prop="customerBidType" :label-width="formLabelWidth">
                    <el-select v-model="dataForm.customerBidType" style="width:100%"  clearable value-key="areaId" filterable placeholder="请选择投标类型">
                      <el-option
                        v-for="item in customerBidType"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                  <el-form-item label="公司类型" prop="type" :label-width="formLabelWidth">
                    <el-select v-model="dataForm.type" style="width:100%"  clearable value-key="areaId" filterable placeholder="请选择公司类型">
                      <el-option
                        v-for="item in customerType"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
              </el-col>

              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                <el-form-item label="法定代表人" prop="legalPerson" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.legalPerson" style="width:100%" placeholder="请输入法人" />
                </el-form-item>
              </el-col>
         
          </el-row>
           <el-row :gutter="20">
               <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                 <el-form-item label="经营范围" prop="businessScope" :label-width="formLabelWidth">
                    <el-input v-model="dataForm.businessScope" style="width:100%" placeholder="请输入经营范围" />
                  </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                 <el-form-item label="注册资本" prop="registeredCapital" :label-width="formLabelWidth">
                    <el-input v-model="dataForm.registeredCapital" style="width:100%" placeholder="请输入注册资本" />
                  </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                 <el-form-item label="住所" prop="residence" :label-width="formLabelWidth">
                    <el-input v-model="dataForm.residence" style="width:100%" placeholder="请输入住所" />
                  </el-form-item>
              </el-col>

          </el-row>
           <el-row :gutter="20">
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                   <el-form-item label="成立日期" prop="dateOfEstablishment" :label-width="formLabelWidth">
                    <el-date-picker
                      v-model="dataForm.dateOfEstablishment"
                      type="date"
                      style="width:100%"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="选择开始日期时间"
                    />
                  </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                  <el-form-item label="营业日期" prop="businessDate" :label-width="formLabelWidth">
                    <el-date-picker
                      v-model="dataForm.businessDate"
                      style="width:100%"
                      type="date"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="选择结束日期时间"
                    />
                  </el-form-item>
              </el-col>
     
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
              </el-col>
          </el-row>
           <el-row :gutter="20">
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
              </el-col>
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
              </el-col>
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
              </el-col>
          </el-row>

        <!-- 
       
       
       
      
       -->
        </el-card>

         <el-card shadow="never">
          <!-- <el-card  shadow="hover" > -->
          <div slot="header" class="clearfix">
            <span class="topClass">用户信息</span>
          </div>
          <el-row :gutter="20">
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                 <el-form-item label="用户名" prop="userName" :label-width="formLabelWidth">
                    <el-input v-model="dataForm.userName" style="width:100%" placeholder="请输入用户名" />
                  </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
                 <el-form-item label="角色" prop="roleList" label-width="120px">
                    <el-select v-model="dataForm.roleList" :multiple-limit="1" value-key="roleName" multiple placeholder="请选择角色" style="width: 100%;">
                      <el-option
                        v-for="item in roles"
                        :key="item.roleId"
                        :label="item.roleName"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24" :sm="12" :md="12" :lg="8">
              </el-col>
          </el-row>
          
         </el-card>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="dialogVisible = false">取消</el-button>
        <el-button :size="size" type="primary" @click="submitEditForm">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { Listarea } from '@/api/dataForm'
import { customerList, addCustomer, editCustomer, deleteCustomer,userRoles,apiFile } from '@/api/record'
import { Notification, MessageBox } from 'element-ui'
import { parseTime } from '@/utils/index'
import { getUserInfo,vailUserName } from '@/api/user'

export default {
  data() {
    const checkTel = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'))
      } else if (!this.checkMobile(value)) {
        callback(new Error('手机号码不合法'))
      } else {
        callback()
      }
    }
    const userBack = (rule,value,callback) =>{
      if(!this.isEditForm){
        vailUserName(value).then((res)=>{
          console.log(res,"userName")
          if(res.data.data){
          callback()
          }else{
          callback(new Error('用户名重复'))
          }
        })
      }else{
        callback()
      }
    }
    return {
      size: 'small',
      tableData: [],
      priceData: [],
      customerName: '',
      typeId: '',
      customerType: [
        { id: 1, name: '有限责任公司（自然人独资）' },
        { id: 2, name: '有限责任公司(自然人投资或控股)' },
        { id: 3, name: '股份有限公司' },
        { id: 4, name: '有限合伙企业' },
        { id: 5, name: '外商独资公司' },
        { id: 6, name: '个人独资企业' },
        { id: 7, name: '国有独资公司' },
        { id: 8, name: '其他' },
        // {id:0,name:"未知"},

      ],
      customerBidType:[
        {id:1,name:"物流"},
        {id:2,name:"原料"},
        {id:3,name:"销售"},
        {id:4,name:"加工承揽"},
        // {id:0,name:"未知"},
      ],
      areaList: [],
      query: {
        name: ''
      },
      formLabelWidth: '90px',
      isEditForm: false,
      currentPage: '1',
      pageSize: 10,
      total: 0, // 总数量
      dataForm: {
      },
      // 表单校验
      dataRule: {
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        customerBidType: [
          { required: true, message: '请选择投标类型', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkTel, trigger: 'change' }
        ],
        userName:[
          { required: true, message: '请输入用户名', trigger: 'blur' }, { validator: userBack, trigger: 'blur' }
        ],
        roleList: [{ required: true, message: '请选择角色', trigger: 'blur'}],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern:
              /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
            message: '输入邮箱不合法'
          }
        ]
        // type: [
        //   { required: true, message: "请选择用户类型", trigger: "change" },
        // ],
        // roleList: [
        //   { required: true, message: "请选择角色", trigger: "change" },
        // ],
      },


      loading: false,
      dialogVisible: false,
      batchVisible:false,
       BASE_API: process.env.BASE_API,
       fileList: [],
      roles:[],
      fileUrl:"",

    }
  },
  created() {
    this.getTenantList()
    this.onRoles()
    this.getFile()  //获取模板地址
    console.log('res')
  },
  methods: {
    parseTime,
    getTenantList: function() {
      this.loading = true
      const params = new URLSearchParams()
      params.append('type', this.typeId)
      params.append('customerName', this.customerName)
      params.append('current', this.currentPage)
      params.append('size', this.pageSize)
      customerList(params).then(response => {
        // console.log("code")
        console.log(response)
        this.loading = false
        this.tableData = response.data.data.records
        console.log('1' + response.data.data.records)
        this.total = response.data.data.total
      })
    },
    // 获取模板url
    getFile(){
      apiFile().then((res)=>{
        console.log(res)
        this.fileUrl = res.data.data.path
      })
    },
     // 文件移除的时候
    handleRemove(file, fileList) {
      this.form.appendix = ''
      console.log(file, fileList, this.fileList, '移出')
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file, fileList) {
      console.log(file, fileList, '上传')
      if (file.response) {
        console.log(file.response, 'file')
        if (file.response.code == '200') {
          // this.form.appendix = file.response.data
          Notification({
          title: '成功',
          type: 'success'
        });
          this.fileList = []
          this.batchVisible = false
          this.getTenantList()
        } else {
          Notification.error({
            title: file.response.msg,
            duration: 1000
          })
          this.fileList = []
        }
      }
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file, 'file1')

      // window.location.href = file.url
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个附件，本次选择了 ${files.length} 个文件`)
    },
    hanndleErr(err, files, fileList) {
      console.log(err, 'err')
      console.log(files, 'err')
      console.log(fileList, 'err')
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    onRoles(){
      userRoles().then((res)=>{
        console.log(res)
        this.roles = res.data.data
      })
    },
    onFile(){
        // let url = "https://fire-development.oss-cn-beijing.aliyuncs.com/bid/dev/客户批量上传模板.xlsx"
        window.open(this.fileUrl, '_self');
    },
    // 验证手机号
    checkMobile(str) {
      const reg = /^1[3456789]\d{9}$/
      return reg.test(str)
    },

    handleFind: function() {
      this.currentPage = '1'
      this.getTenantList()
    },
    handleSizeChange: function(val) {
      this.pageSize = val
      this.getTenantList()
    },
    // 换页
    handleCurrentChange: function(val) {
      const page = val.toString()
      this.currentPage = page
      this.getTenantList()
    },
    // 查看
    // lookRecord:function(row){
    //     this.lookCord=row
    //     this.dialogVisible = true
    //     console.log(row)
    // },
    // 批量添加客户
    handleBatchAdd(){
      this.batchVisible = true
    },
    // 显示新增界面
    handleAdd: function() {
      this.isEditForm = false
      this.dialogVisible = true
      this.dataForm = {}
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].resetFields()
      }
    },
    // 编辑界面
    handleEdit: function(row) {
      this.isEditForm = true
      this.dialogVisible = true
      this.dataForm = JSON.parse(JSON.stringify(row))
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].resetFields()
      }
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('此操作将删除该公司, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCustomer(row.customerId,row.userId).then(response => {
            if (response.data.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.getTenantList()
            } else {
              this.$message({
                type: 'error',
                message: response.data.msg
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    submitEditForm() {
      console.log(this.dataForm)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.isEditForm) {
            // 更新字典
            editCustomer(this.dataForm).then((res) => {
              if (res.data.code === 200) {
                this.$message({ message: '操作成功', type: 'success' })
              } else {
                this.$message({ message: res.data.msg, type: 'error' })
              }
              this.dialogVisible = false
              this.getTenantList()
            })
          } else {
            // 新增字典
            addCustomer(this.dataForm).then((res) => {
              if (res.data.code === 200) {
                this.$message({ message: '操作成功', type: 'success' })
              } else {
                this.$message({ message: res.data.msg, type: 'error' })
              }
              this.dialogVisible = false
              this.getTenantList()
              this.$refs['dataForm'].resetFields()
            })
          }
        }
      })
    }

  }
}
</script>

<style scoped lang="scss" >

   .el-dropdown-link {
    cursor: pointer;
    color: #1282f3;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .el-scrollbar__wrap {
   overflow-y: hidden;
}

.el-card {
  border: 0px solid #fff;
  .topClass{
    font-weight: 600;
    font-size: 17px;
  }
}
.el-icon-document{
  font-size: 70px;
  color:#409EFF;
  line-height: 130px;
}
/deep/.el-card__body {
  padding: 20px 10px 0 10px !important;
}
</style>

