<template>
  <div class="app-container calendar-list-container">
    <div>
      <div class="filter-container" ref="filter-container">
        <div class="top_btn">
          <el-button type="primary" @click="add_item" icon="el-icon-plus">添加公司</el-button>
        </div>
        <el-form ref="queryForm" :inline="inline" :model="listQuery" label-width="80px">
          <el-row>
            <el-form-item label="公司名称">
              <el-input v-model="listQuery.name" placeholder="请输入公司名称"></el-input>
            </el-form-item>
            <el-button
              class="filter-item"
              type="primary"
              v-waves
              icon="el-icon-search"
              @click="handleFilter"
            >搜索</el-button>
            <el-button class="filter-item" @click="clear_handleFilter">清除搜索</el-button>
          </el-row>
        </el-form>
      </div>
      <el-table :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
        <el-table-column align="center" label="公司名称" prop="name"></el-table-column>
        <el-table-column align="center" label="联系人/电话">
          <template slot-scope="{row}">
            <span>{{row.contact}}/{{row.mobile}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="法人姓名" prop="legalPerson"></el-table-column>
        <el-table-column align="center" label="法人身份证" prop="legalIdNumber"></el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="{row}">
            <el-button type="text" @click="edit_item(row)">编辑</el-button>
            <el-button type="text" @click="edit_del(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,40,50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      customClass="customWidth1"
      :title="title_text"
      :visible.sync="add_edit_dialog"
      @close="add_edit_dialog=false"
    >
      <div class="form_box">
        <el-form ref="company_form" :rules="rules" :model="company_form" style label-width="100px">
          <el-form-item label="公司名称" prop="name">
            <el-input v-model="company_form.name"></el-input>
          </el-form-item>
          <el-form-item label="法人姓名" prop="legalPerson">
            <el-input v-model="company_form.legalPerson"></el-input>
          </el-form-item>
          <el-form-item label="法人身份证" prop="legalIdNumber">
            <el-input v-model="company_form.legalIdNumber"></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="company_form.contact"></el-input>
          </el-form-item>
          <el-form-item label="联系人手机" prop="mobile">
            <el-input v-model="company_form.mobile"></el-input>
          </el-form-item>
          <el-form-item label="营业执照" prop="businessLicense">
            <el-upload
              class="avatar-uploader"
              :action="BASE_API+'/api/universal/file/app/unauth/admin/upload'"
              :show-file-list="false"
              :headers="getHeaderWithToken"
              :on-success="handleAvatarSuccess"
            >
              <img
                v-if="$utils.isString(company_form.businessLicense) && !$utils.isEmpty(company_form.businessLicense)"
                :src="company_form.businessLicense"
                style="width:200px;max-height:200px;"
              />
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
                style="lineHeight:100px;width:100px;height: 100px;vertical-align: middle;"
              ></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="add_edit_dialog = false">取 消</el-button>
        <el-button type="primary" @click="add_company_ok('company_form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { formatDate } from "utils/dateFormattor";

import {
  toEast8Date,
  deepCopyDate,
  newEast8Date,
  convertDate2Str,
  timestamp2Date,
} from "utils/dateUtils";

import { mapGetters } from "vuex";

import {
  company_list,
  add_company,
  del_company,
  upd_company,
} from "api/company";
import { getAllZone } from "api/base_info/constant/";
import Element1 from "../admin/menu/components/element";
import ElRow from "element-ui/packages/row/src/row";
import ElCol from "element-ui/packages/col/src/col";
import { getToken } from "utils/auth";

export default {
  name: "carApplyList",
  components: {
    ElCol,
    ElRow,
    Element1,
  },
  data() {
    var validatelegalIdNumber = (rule, value, callback) => {
      if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        callback(new Error("请输入正确的身份证"));
      } else {
        callback();
      }
    };
    var validatemobile = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };

    return {
      title_text: "",
      BASE_API: process.env.BASE_API,
      add_edit_dialog: false,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
      },
      inline: true,
      tableKey: 0,
      rules: {
        name: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
        legalPerson: [
          { required: true, message: "请输入法人姓名", trigger: "blur" },
        ],
        legalIdNumber: [
          { required: true, message: "请输入法人身份证", trigger: "blur" },
          { validator: validatelegalIdNumber, trigger: "blur" },
        ],
        contact: [{ required: true, message: "请输入联系人", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入联系人手机", trigger: "blur" },
          { validator: validatemobile, trigger: "blur" },
        ],
        businessLicense: [
          { required: true, message: "请上传凭证", trigger: "blur" },
        ],
      },
      company_form: {
        id: "",
        name: "",
        legalPerson: "",
        legalIdNumber: "",
        contact: "",
        mobile: "",
        businessLicense: "",
      },
    };
  },
  created() {
    this.getList();
  },
  computed: {
    ...mapGetters(["elements"]),
    getHeaderWithToken() {
      return { Authorization: getToken() };
    },
  },
  methods: {
    add_company_ok(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          if (this.title_text == "编辑公司") {
            upd_company(this.company_form).then((res) => {
              if (res.status == 200) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                this.add_edit_dialog = false;
                this.handleFilter();
              } else {
                this.$error({
                  message: res.message,
                });
              }
            });
            return;
          }

          add_company(this.company_form).then((res) => {
            if (res.status == 200) {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.add_edit_dialog = false;
              this.handleFilter();
            } else {
              this.$error({
                message: res.message,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.company_form.businessLicense = res.data;
    },
    form_clear() {
      this.company_form = {
        id: "",
        name: "",
        legalPerson: "",
        legalIdNumber: "",
        contact: "",
        mobile: "",
        businessLicense: "",
      };
    },
    /**
     * 获取列表
     * */
    getList() {
      this.listLoading = true;
      company_list(this.listQuery).then((response) => {
        console.log(response);
        let totalCountRs = undefined;
        let listRs = undefined;
        if (
          !this.$utils.isEmpty(response.data.data) &&
          this.$utils.isInteger(response.data.totalCount)
        ) {
          listRs = response.data.data;
          totalCountRs = response.data.totalCount;
        }
        this.listLoading = false;
        this.list = listRs;
        this.total = totalCountRs;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          this.getList();
        } else {
          return false;
        }
      });
    },
    clear_handleFilter() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
      };
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    add_item() {
      this.add_edit_dialog = true;
      this.title_text = "添加公司";
      this.form_clear();
    },
    edit_item(row) {
      this.add_edit_dialog = true;
      this.title_text = "编辑公司";

      this.company_form = {
        id: row.id,
        name: row.name,
        legalPerson: row.legalPerson,
        legalIdNumber: row.legalIdNumber,
        contact: row.contact,
        mobile: row.mobile,
        businessLicense: row.businessLicense,
      };
    },
    edit_del(row) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          del_company({ id: row.id }).then((res) => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.handleFilter();
            } else {
              this.$message({
                type: "info",
                message: res.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style>
.top_btn {
  width: 90%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.form_box {
  width: 80%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.customWidth1 {
  width: 35%;
}
</style>
