<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"
               @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange"
               @on-load="onLoad">
      <!--      <template slot="menu" slot-scope="{row}">-->
      <!--        <el-button-->
      <!--          v-if="vaildData(permission.manage_station_mainList_stop, false) && row.status !== 9"-->
      <!--          size="small"-->
      <!--          icon="el-icon-delete"-->
      <!--          @click.stop="stop(row)"-->
      <!--          type="text"-->
      <!--        >终止合作</el-button>-->
      <!--      </template>-->


      <template #menu>
        <el-button size="small" type="text" @click="rowDel">注销</el-button>
      </template>
      <template slot="authUrlIdImgForm">
        <el-image style="width: 100px; height: 100px" :src="form.authUrlId"
                  :preview-src-list="[form.authUrlId]"></el-image>
      </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="attorneyUrlImgForm">
        <el-image style="width: 100px; height: 100px" :src="form.attorneyUrl"
                  :preview-src-list="[form.attorneyUrl]"></el-image>
      </template>


    </avue-crud>
  </basic-container>
</template>

<script>
import {
  companyInfoAdd,
  companyStationInfo,
  companyDetail,
  companyUpdate,
  stationStop,
  removeMainList
} from "@/api/manage/main";
// import { getStationDic } from "@/api/manage/station";
import {mapGetters} from "vuex";
import {isMobile, check18IdCardNo, validatenull} from "@/util/validate";
import {putFile} from "@/api/resource/oss";
import {getTradeDic} from "@/api/manage/trade";
import {addressColumn, companyEnum} from "@/common/dic"
import {getDeptMyTree} from "@/api/tenant/talents";

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

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

export default {
  name: "manage_station_mainList",
  data() {
    return {
      depTree: [],
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      checkDrawer: false,
      data: [],
    };
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permission.manage_station_mainList_add,
          false
        ),
        viewBtn: this.vaildData(
          this.permission.manage_station_mainList_view,
          false
        ),
        editBtn: this.vaildData(
          this.permission.manage_station_mainList_edit,
          false
        ),
      };
    },
    option() {
      return {
        height: "auto",
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: "序号",
        viewBtn: true,
        delBtn: false,
        menuWidth: 250,
        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: "comname",
            search: true,
            display: false,
          },
          {
            label: "联系人",
            prop: "manager",
            search: false,
            display: false,
          },
          {
            label: "手机号码",
            prop: "telphone",
            display: false,
          }
        ],
        group: [
          {
            label: "",
            column: [
              {
                type: "input",
                label: "统一信用代码",
                span: 12,
                display: true,
                size: "small",
                prop: "companyTid",
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入统一信用代码",
                  },
                  {
                    message: "请输入正确的统一信用代码",
                    min: 18,
                    max: 18,
                  },
                ],
                placeholder: "18位统一社会信用代码",
              },
              {
                type: "input",
                label: "用工单位",
                span: 12,
                display: true,
                size: "small",
                prop: "comname",
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入用工单位",
                  },
                ],
              },
              {
                type: "input",
                label: "法人姓名",
                span: 12,
                display: true,
                size: "small",
                prop: "masterName",
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入法人姓名",
                  },
                ],
              },
              {
                type: "input",
                label: "法人身份证号",
                span: 12,
                display: true,
                size: "small",
                prop: "masterIdentity",
                rules: [
                  {
                    required: true,
                    message: "请输入身份证号",
                  },
                  {
                    validator: (rule, value, callback) => {
                      if (check18IdCardNo(value)) {
                        callback();
                      } else {
                        callback(new Error("身份证格式不正确"));
                      }
                    }
                  },
                ],
              },
              {
                type: "select",
                label: "所在地区",
                prop: "cityId",
                span: 12,
                dicData: addressColumn,
                display: true,
                rules: [
                  {
                    required: true,
                    message: "请选择所在地区",
                  },
                ],
              },
              {
                type: "input",
                label: "详细地址",
                span: 12,
                display: true,
                size: "small",
                prop: "companyAddress",
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入详细地址",
                  },
                ],
              },
              {
                type: "input",
                label: "经办人信息",
                span: 12,
                display: true,
                size: "small",
                prop: "manager",
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入联系人",
                  },
                ],
              },
              {
                type: "input",
                label: "经办人身份证号",
                span: 12,
                display: true,
                size: "small",
                prop: "managerIdCard",
                rules: [
                  {
                    required: true,
                    message: "请输入身份证号",
                  },
                  {
                    validator: (rule, value, callback) => {
                      if (check18IdCardNo(value)) {
                        callback();
                      } else {
                        callback(new Error("身份证格式不正确"));
                      }
                    }
                  },
                ],
              },
              {
                type: "input",
                label: "手机号码",
                span: 12,
                display: true,
                size: "small",
                prop: "telphone",
                rules: [
                  {
                    required: true,
                    validator: (rule, value, callback) => {
                      if (validatenull(value)) {
                        callback(new Error("请输入手机号码"));
                      } else if (isMobile(value)) {
                        callback();
                      } else {
                        callback(new Error("手机号码不正确"));
                      }
                    }
                  },
                ],
              },
              {
                label: "用工单位性质",
                prop: "nature",
                type: 'select',
                dicUrl: "/api/jobslink-api/system/dict-biz/dictionary?code=company_nature",
                dataType: "number",
                props: {
                  label: "dictValue",
                  value: "dictKey",
                },
                // dicData: companyEnum,
                rules: [
                  {
                    required: true,
                    message: "请输入用工单位性质",
                    trigger: "blur",
                  },
                ],
                span: 12,
              },
              {
                type: "select",
                label: "行业",
                size: "small",
                prop: "tradeId",
                dicUrl: getTradeDic(),
                props: {
                  label: "name",
                  value: "id"
                },
                dicFormatter(resp) {
                  var result = [];
                  resp.data.forEach(ele => {
                    if (ele.name != "1") {
                      result.push(ele)
                    }
                  });
                  return result;
                },
                rules: [
                  {
                    required: true,
                    validator: (rule, value, callback) => {
                      if (value == '请选择行业') {
                        callback(new Error('请选择行业'));
                      } else {
                        callback();
                      }
                    },
                    trigger: 'blur'
                  }
                ]
              },
              {
                type: "textarea",
                label: "用工单位介绍",
                span: 20,
                display: true,
                size: "small",
                prop: "companyDesc",
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入用工单位介绍",
                  },
                ],
              },
              {
                type: "upload",
                label: "法人身份证（人像）",
                span: 12,
                showFileList: false,
                listType: "picture-img",
                multiple: false,
                propsHttp: {
                  // res: "data",
                  url: "msg",
                },
                canvasOption: {},
                headers: [],
                data: [],
                accept,
                size: "small",
                prop: "identityUrl4Id",
                action: putFile(5),
                viewDisplay: false,
              },
              {
                type: "upload",
                label: "法人身份证（国徽）",
                span: 12,
                showFileList: false,
                listType: "picture-img",
                multiple: false,
                propsHttp: {
                  // res: "data",
                  url: "msg",
                },
                canvasOption: {},
                headers: [],
                data: [],
                accept,
                size: "small",
                prop: "identityUrl5Id",
                action: putFile(5),
                viewDisplay: false,
              },
              {
                type: "upload",
                label: "营业执照",
                span: 12,
                showFileList: false,
                listType: "picture-img",
                multiple: false,
                propsHttp: {
                  // res: "data",
                  url: "msg",
                },
                accept,
                canvasOption: {},
                headers: [],
                data: [],
                size: "small",
                prop: "authUrlId",
                action: putFile(5),
                viewDisplay: false,
              },
              {
                type: "upload",
                label: "授权书",
                span: 12,
                showFileList: false,
                listType: "picture-img",
                multiple: false,
                formslot: true,
                propsHttp: {
                  // res: "data",
                  url: "msg",
                },
                accept,
                canvasOption: {},
                headers: [],
                data: [],
                size: "small",
                prop: "attorneyUrl",
                action: putFile(5),
                viewDisplay: false,
              },
              // 图片预览
              {
                label: "法人身份证（人像）",
                span: 12,
                prop: "identityUrl4IdImg",
                formslot: true,
                editDisplay: false,
                addDisplay: false,
                viewDisplay: true,
              },
              {
                label: "法人身份证（国徽）",
                span: 12,
                prop: "identityUrl5IdImg",
                formslot: true,
                editDisplay: false,
                addDisplay: false,
                viewDisplay: true,
              },
              {
                label: "营业执照照片",
                span: 12,
                prop: "authUrlIdImg",
                formslot: true,
                editDisplay: false,
                addDisplay: false,
                viewDisplay: true,
              },
              {
                label: "授权书",
                span: 12,
                prop: "attorneyUrl",
                formslot: true,
                editDisplay: false,
                addDisplay: false,
                viewDisplay: true,
              },
            ],
          },
        ],
      }
    }
  },
  created() {
    this.getDept()
  },
  methods: {
    async getDept() {
      let params = {
        tenantId: '000000'
      }
      let resData = await getDeptMyTree(params)
      if (resData.data.code === 200) {
        this.depTree = resData.data.data
      }
    },
    initData() {
      this.onLoad(this.page, this.query);
    },
    rowDel(row) {
      const h = this.$createElement;
      this.$confirm(
        h("div", null, [
          h("p", {style: "font-size: 16px"}, "您确定要注销此消息吗? "),
          h("p", {style: "color: red"}, "一旦注销则无法找回"),
        ]),
        {
          type: "warning",
          showClose: false,
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }
      )
        .then(() => {
          return removeMainList({id: row.id, isDeleted: 1});
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.refreshChange();
        })
        .catch(() => {
        });
    },
    rowSave(row, done, loading) {
      console.log('rowSave')
      row.authUrlId = getPath(row.authUrlId)
      row.identityUrl4Id = getPath(row.identityUrl4Id)
      row.identityUrl5Id = getPath(row.identityUrl5Id)
      row.attorneyUrl = getPath(row.attorneyUrl)
      // console.log(row, '----------------------------------');
      companyInfoAdd({
        authUrlId: row.authUrlId,
        nature: row.nature,
        tradeId: row.tradeId,
        companyDesc: row.companyDesc,
        cityId: row.cityId,
        companyAddress: row.companyAddress,
        companyName: row.companyName,
        companyTid: row.companyTid,
        comname: row.comname,
        identityUrl4Id: row.identityUrl4Id,
        identityUrl5Id: row.identityUrl5Id,
        attorneyUrl: row.attorneyUrl,
        manager: row.manager,
        masterIdentity: row.masterIdentity,
        masterName: row.masterName,
        percent: row.percent,
        stationId: row.stationId,
        telphone: row.telphone,
      }).then(
        () => {
          this.onLoad(this.page, this.params);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          // 数据回调进行刷新
          done(row);
        },
        () => {
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      // console.log(row, 'rowUpdate')
      row.authUrlId = getPath(row.authUrlId)
      row.identityUrl4Id = getPath(row.identityUrl4Id)
      row.identityUrl5Id = getPath(row.identityUrl5Id)
      row.attorneyUrl = getPath(row.attorneyUrl)
      companyUpdate({
        id: row.id,
        nature: row.nature,
        tradeId: row.tradeId,
        companyDesc: row.companyDesc,
        authUrlId: row.authUrlId,
        cityId: row.cityId,
        companyAddress: row.companyAddress,
        companyName: row.companyName,
        companyTid: row.companyTid,
        comname: row.comname,
        identityUrl4Id: row.identityUrl4Id,
        identityUrl5Id: row.identityUrl5Id,
        attorneyUrl: row.attorneyUrl,
        manager: row.manager,
        masterIdentity: row.masterIdentity,
        masterName: row.masterName,
        percent: row.percent,
        stationId: row.stationId,
        telphone: row.telphone,
        authType: 0
      }).then(
        () => {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          // 数据回调进行刷新
          done(row);
        },
        () => {
          loading();
        }
      );
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    beforeOpen(done, type) {
      if (["add", "edit"].includes(type)) {
        this.initData();
        done();
      }
      if (["edit", "view"].includes(type)) {
        this.loading = true;
        var params = {
          id: this.form.id,
          authType: 0
        }
        companyDetail(params).then((res) => {
          this.loading = false;
          this.form = res.data.data;
          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;
      companyStationInfo(
        page.currentPage,
        page.pageSize,
        Object.assign(this.query, params)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    stop(row) {
      let h = this.$createElement;
      this.$confirm(
        h("p", {style: "color: #F56C6C"}, "一旦终止结算将会终止"),
        "您确定要终止与此公司的合作吗？",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      )
        .then(() => {
          this.loading = true;
          var params = {
            companyId: row.id,
            flag: 0,
            authType: 0
          }
          stationStop(params)
            .then(() => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.loading = false;
              this.onLoad(this.page, this.params);
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch();
    },
  },
  watch: {},
};
</script>

<style></style>
