<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" ref="crud" v-model="form"
               :permission="permissionList" :before-open="beforeOpen" :before-close="beforeClose" :page.sync="page"
               @row-update="rowUpdate" @row-save="rowSave" @search-change="searchChange" @search-reset="searchReset"
               @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
               @refresh-change="refreshChange" @on-load="onLoad" :upload-before="uploadBefore">
      <template slot="menuLeft">
        <!--        <el-button v-if="vaildData(permission.manage_compan_companyList_addUser, false)" size="small"-->
        <!--          @click.stop="handleAddUser" type="primary" :disabled="selectionList.length === 0">关联账号</el-button>-->
        <!-- <el-button v-if="vaildData(permission.manage_compan_companyList_config, false)" size="small"
          @click.stop="handleConfig" type="primary" :disabled="selectionList.length === 0">服务设置</el-button> -->
        <!-- <el-button v-if="vaildData(permission.manage_compan_companyList_check, false)" size="small"
          @click.stop="handleCheck" type="primary" :disabled="selectionList.length === 0">审核</el-button> -->
      </template>
      <template slot="cityIdForm" slot-scope="{ disabled }">
        <jl-city-cascader :disabled="disabled" v-model="form.cityId"></jl-city-cascader>
      </template>
      <template slot="cityId" slot-scope="{ row }">
        <jl-city-cascader :type="'view'" :disabled="true" v-model="row.cityId"></jl-city-cascader>
      </template>
      <template slot="lonForm" slot-scope="{ row }">
        <super-map-view
          :isCanEdit="false"
          @addAddress="changeAddress"
          :longitude="row.lon <= 0 ? 104.397894 : row.lon"
          :latitude="row.lat <= 0 ? 31.126855 : row.lat"
          :open="true"
          :zoom="10"
          :min-zoom="10"
          :max-zoom="20"
          :flag-tip="false"
          placeholder="请输入详细地址"
          :type="'select'"
        ></super-map-view>
      </template>
      <template slot="companyAddressForm" slot-scope="{ disabled }">
        <!--        <select-map-->
        <!--          ref="selectMap"-->
        <!--          @addAddress="addAddress"-->
        <!--          @addressDel="addressDel"-->
        <!--          :isCanEdit="!disabled"-->
        <!--          :lng="obj.lon"-->
        <!--          :lat="obj.lat"-->
        <!--          :address="form.companyAddress"-->
        <!--          :type="type"-->
        <!--        ></select-map>-->
      </template>
      <template slot="authUrlIdImgForm">
        <el-image style="width: 100px; height: 100px" :src="form.authUrlId" :preview-src-list="[form.authUrlId]">
        </el-image>
      </template>
      <template slot="identityUrl4IdImgForm">
        <el-image style="width: 100px; height: 100px" :src="form.identityUrl4Id"
                  :preview-src-list="[form.identityUrl4Id]"></el-image>
      </template>
      <template slot="identityUrl5IdImgForm">
        <el-image style="width: 100px; height: 100px" :src="form.identityUrl5Id"
                  :preview-src-list="[form.identityUrl5Id]"></el-image>
      </template>

      <template slot="signSrcUrlForm">
        <el-image style="width: 100px; height: 100px" :src="form.signSrcUrl"
                  :preview-src-list="[form.signSrcUrl]"></el-image>
      </template>
      <template slot="letterOfAttorneyUrlForm">
        <el-image style="width: 100px; height: 100px" :src="form.letterOfAttorneyUrl"
                  :preview-src-list="[form.letterOfAttorneyUrl]"></el-image>
      </template>
      <template slot="motoleyUrlImgForm">
        <div v-if="imgList.length > 0">
          <span v-for="(item, index) in imgList" :key="index" class="motoley-img">
            <el-image style="width: 100px; height: 100px" :src="item.url" :preview-src-list="[item.url]"></el-image>

          </span>
        </div>
        <div class="el-image__error" style="width: 100px; height: 100px" v-else>加载失败</div>
      </template>
      <template slot="recordForm" slot-scope="{ row }">
        <company-record :data="row"></company-record>
      </template>
      <template slot="motoleyUrlForm">
        <el-upload class="companyList-upload" list-type="picture-card" :auto-upload="true" :file-list="imgList"
                   :limit="5"
                   :action="mutiPutFile" :on-preview="handlePictureCardPreview" :on-exceed="handleImgLimit"
                   :on-success="handleImgSuccess" :on-remove="handleImgRemove" :before-remove="beforeRemove"
                   :before-upload="beforeAvatarUpload">
          <i slot="default" class="el-icon-plus avue-upload__icon"></i>
        </el-upload>
      </template>
      <!--服务费-->
      <template slot="serveCost" slot-scope="{ row }">
        <span v-if="row.serveCost != -1 && row.serveCost">{{
            moneyFormat(row.serveCost)
          }}</span>
        <span v-else>-</span>
      </template>
      <!--商报状态搜索栏-->
      <!-- <template slot="insuranceOnSearch">
        <el-select
          v-model="query.insuranceOn"
          placeholder="商保状态"
          @change="selectInsureTyepChange"
        >
          <el-option
            v-for="(item, index) in insureTypeList"
            :key="index"
            :label="item.label"
            :value="item.value"
            >{{ item.label }}</el-option
          >
        </el-select>
      </template> -->
      <!--保证金状态搜索栏trialOn-->
      <template slot="trialOnSearch">
        <el-select v-model="query.trialOn" placeholder="保证金" @change="selectTrailTyepChange">
          <el-option v-for="(item, index) in bondList" :key="item.value" :label="item.label" :value="item.value">{{
              item.label
            }}
          </el-option>
        </el-select>
      </template>
    </avue-crud>
    <add-account ref="addUser"></add-account>
    <company-config ref="config" @success="refreshChange"></company-config>
    <company-check ref="check" @success="refreshChange"></company-check>
  </basic-container>
</template>

<script>
import {
  getList,
  detailCompany,
  add,
  update,
  stop,
  start,
} from "@/api/manage/company";
import {getStationDic} from "@/api/manage/station";
import {getTradeDic} from "@/api/manage/trade";
import {mapGetters} from "vuex";
import addAccount from "./addAccount";
import companyConfig from "./companyConfig";
import companyCheck from "./companyCheck";
import {putFile} from "@/api/resource/oss";
import {check18IdCardNo, isvalidatemobile} from "@/util/validate";
import {moneyFormat} from "@/util/money";
import companyRecord from "./companyRecord";
import {companyStatus} from "@/const/company";
import {getDeptMyTree} from "@/api/tenant/talents";

const accept = [
  "image/png",
  "image/jpeg",
  "image/svg+xml",
  "image/gif",
  "image/x-photoshop",
];

function getPath(path) {
  if (path) {
    const arr = path.split(",");
    return arr[arr.length - 1];
  }
  return path
}

export default {
  components: {addAccount, companyConfig, companyCheck, companyRecord},
  name: "manage_compan_companyList",
  data() {
    const validateTradeId = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('请选择所属行业'));
      } else {
        callback();
      }
    }
    return {
      type: "",
      insureTypeList: [//商保下拉框
        {
          label: "停用",
          value: 0,
        },
        {
          label: "启用",
          value: 1,
        },
      ],
      bondList: [//保证金
        {
          label: "已缴",
          value: 0,
        },
        {
          label: "未缴",
          value: 1,
        },
        {
          label: "免缴",
          value: 2,
        },
      ],
      mutiPutFile: putFile(),
      imgList: [],
      form: {},
      selectionList: [],
      query: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      obj: {},
      data: [],
      selectJW: null,
      depTree: [],
    };
  },
  created() {
    this.getDept()
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permission.manage_compan_companyList_add,
          false
        ),
        viewBtn: this.vaildData(
          this.permission.manage_compan_companyList_view,
          false
        ),
        editBtn: this.vaildData(
          this.permission.manage_compan_companyList_edit,
          false
        ),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    option() {
      const validatePhone = (rule, value, callback) => {
        function checkPhoneNumber(s) {
          const mobilePattern = /^1[3-9]\d{9}$/;
          const landlinePattern = /^0\d{2,3}-?\d{7,8}$/;
          return mobilePattern.test(s) || landlinePattern.test(s);
        }

        // if (isvalidatemobile(value)) {
        if (checkPhoneNumber(value)[0]) {
          callback(new Error(checkPhoneNumber(value)));
        } else {
          callback();
        }
      };
      return {
        height: "auto",
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: "序号",
        selection: true,
        viewBtn: true,
        addBtn: false,
        editBtn: true,
        addBtnText: "社区街道登记",
        addTitle: "新增机构名称",
        rowKey: "$index",
        delBtn: false,
        menuWidth: 300,
        labelWidth: 151,
        dialogClickModal: false,
        dialogType: "drawer",
        dialogFullscreen: true,
        column: [
          {
            label: "所属机构",
            prop: "deptId",
            type: "tree",
            multiple: false,
            dicData: this.depTree,
            props: {
              label: "title",
              value: 'value'
            },
            checkStrictly: true,
            search: true,
            span: 20,
            hide: true,
            searchLabelWidth: 80,
            searchSpan: 6,
          },
          {
            label: '机构名称',
            prop: 'companyName',
          },
          {
            label: "联系人姓名",
            display: false,
            prop: "masterName",
          },
          {
            label: "手机号",
            display: false,
            prop: "phone",
          },
        ],
        group: [
          {
            label: "",
            column: [
              {
                type: "input",
                label: "机构名称",
                span: 20,
                display: true,
                size: "small",
                prop: "companyName",
                value: this.userInfo.company_name,
                disabled: true,
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入机构名称",
                  },
                ],
              },
              {
                type: "input",
                label: "联系人姓名",
                span: 20,
                display: true,
                size: "small",
                prop: "masterName",
              },
              {
                type: "input",
                label: "手机号",
                span: 20,
                size: "small",
                prop: "phone",
                rules: [
                  {required: true, trigger: "blur", validator: validatePhone},
                ],
              },
              {
                type: "textarea",
                label: "备注",
                span: 20,
                display: true,
                size: "small",
                prop: "remarks",
              },
              {
                label: "所在位置",
                prop: "lon",
                hide: true,
                span: 20,
                display: true,
                formslot: true,
              },
            ],
          }
        ],
      }
    }
  },
  methods: {
    async getDept() {
      let params = {
        tenantId: '000000'
      }
      let resData = await getDeptMyTree(params)
      if (resData.data.code === 200) {
        this.depTree = resData.data.data
      }
    },
    /*地图*/
    addAddress(form) {
      this.obj.address = form.address + (form.title || "");
      this.obj.lat = form.lat;
      this.obj.lon = form.lng;
      this.form.companyAddress = form.address + (form.title || "");
    },
    addressDel() {
      this.form.companyAddress = this.obj.address = "";
    },
    // uploadBefore(file, done, loading) {
    //   const isLt2M = file.size / 1024 / 1024 < 2;
    //   if (!isLt2M) {
    //     this.$message.error("上传图片大小不能超过 2MB!");
    //     loading();
    //     return;
    //   }
    //   done();
    // },
    // uploadBefore(done) {
    //   done();
    // },
    initData() {
      this.onLoad(this.page, this.query);
    },
    handleCheck() {
      if (this.ids.length !== 1) {
        this.$message.closeAll();
        this.$message({
          type: "warning",
          message: "请选择一条数据",
        });
        return;
      }
      /*已审核的*/
      let flags = true;
      this.data.forEach((ele) => {
        if (ele.status == 0 && ele.id == this.ids[0]) {
          flags = false;
        }
      });
      if (!flags) {
        this.$message.closeAll(); //只显示一个提示
        this.$message.error("该机构名称已经审核，不用重复操作");
        return;
      }
      this.$refs.check.open(this.ids[0]);
    },
    handleAddUser() {
      if (this.ids.length !== 1) {
        this.$message({
          type: "warning",
          message: "请选择一条数据",
        });
        return;
      }
      const selected = this.selectionList[0];
      this.$refs.addUser.open(selected);
    },
    handleConfig() {
      if (this.ids.length !== 1) {
        this.$message({
          type: "warning",
          message: "请选择一条数据",
        });
        return;
      }
      const selected = this.selectionList[0];
      this.$refs.config.open(selected.id, selected.tenantId);
    },
    rowSave(row, done, loading) {
      row.authUrlId = getPath(row.authUrlId);
      row.identityUrl4Id = getPath(row.identityUrl4Id);
      row.identityUrl5Id = getPath(row.identityUrl5Id);

      add(row).then(
        () => {
          this.onLoad(this.page);
          // 获取新增数据的相关字段
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          // 数据回调进行刷新
          done(row);
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    changeAddress(val) {
      this.selectJW = val
    },
    rowUpdate(row, index, done, loading) {
      row.authUrlId = getPath(row.authUrlId);
      row.identityUrl4Id = getPath(row.identityUrl4Id);
      row.identityUrl5Id = getPath(row.identityUrl5Id);
      const copyRow = {...row}
      if (this.obj.address) {
        copyRow.companyAddress = this.obj.address
      }
      if (this.selectJW) {
        const {lng, lat} = this.selectJW
        copyRow.lon = lng
        copyRow.lat = lat
      }
      update(copyRow).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          // 数据回调进行刷新
          done(row);
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowStop(id) {
      let h = this.$createElement;
      this.$confirm(
        h("p", {style: "color: #F56C6C"}, "一旦终止合作社区街道将无法操作系统"),
        "您确定要终止与此公司的合作吗？",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      )
        .then(() => {
          this.loading = true;
          stop(id)
            .then((resp) => {
              this.$message({
                type: "success",
                message: resp.data.msg,
              });
              this.onLoad(this.page, this.query);
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {
        });
    },
    rowStart(id) {
      let h = this.$createElement;
      this.$confirm(
        h("p", {style: "color: #F56C6C"}, "一旦恢复合作社区街道所有账号均可使用"),
        "您确定要恢复与此公司的合作吗？",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      )
        .then(() => {
          this.loading = true;
          start(id)
            .then((resp) => {
              this.$message({
                type: "success",
                message: resp.data.msg,
              });
              this.onLoad(this.page, this.query);
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      //(this.query,params);
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    beforeOpen(done, type) {
      if (["add", "edit"].includes(type)) {
        this.imgList = [];
        this.initData();
        this.selectJW = null
        done();
      }
      if (["edit", "view"].includes(type)) {
        this.imgList = [];
        this.loading = true;
        let params = {
          id: this.form.id,
          createDept: this.form.createDept
        }
        detailCompany(params).then((res) => {
          this.loading = false;
          this.form = res.data.data;
          if (this.form.motoleyUrl) {
            var strList = this.form.motoleyUrl.split(',');
            for (var i in strList) {
              this.imgList.push({url: strList[i]})
            }
          }
          if (this.form.tradeId == 1) {
            this.form.tradeId = '';
          }
          done();
        });
      }
    },
    beforeClose(done) {
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(this.query, params)
      ).then((res) => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      });
    },
    moneyFormat,
    /*多张图片上传*/

    handleImgLimit() {
      this.$message.warning('当前最多上传5张图片');
    },
    handleImgSuccess(res) {
      if (res.code == 200) {
        this.imgList.push({url: res.data.link});

        var str = "";
        for (var i = 0; i < this.imgList.length; i++) {
          str += this.imgList[i]['url'] + ",";
        }
        if (str.length > 0) {
          str = str.substr(0, str.length - 1);
        }
        this.form.motoleyUrl = str;
      } else {
        this.$message.error('上传失败');
      }

    },
    handleImgRemove(file) {
      let index = 0;
      for (let i in this.imgList) {
        if (this.imgList[i]['uid'] == file.uid) {
          index = i;
          break;
        }
      }
      this.imgList.splice(index, 1);
      var str = "";
      for (var i = 0; i < this.imgList.length; i++) {
        str += this.imgList[i]['url'] + ",";
      }
      if (str.length > 0) {
        str = str.substr(0, str.length - 1);
      }
      this.form.motoleyUrl = str;
    },
    selectInsureTyepChange(val) {
      this.query.insuranceOn = val
    },
    selectTrailTyepChange(val) {
      this.query.trialOn = val;
    },
  },
  watch: {},
};
</script>

<style>
.companyList-upload .el-upload--picture-card {
  width: 178px;
  height: 178px;
  background-color: #ffffff;
}

.companyList-upload .el-input__inner {
  border: 1px solid #DCDFE6;
}

.companyList-upload .el-upload-list--picture-card .el-upload-list__item {
  width: 178px;
  height: 178px;
}

.motoley-img {
  margin-right: 10px;
}
</style>
