<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 #attorneyUrlForm="{ type, disabled }"> -->
        <!-- <div class="attorney-upload-container"> -->
          <!-- 文件上传组件 -->
          <!-- <div class="file-upload" style="margin-top: 10px;">
            <avue-upload
              v-model="form.attorneyUrl"
              :action="actionurl"
              list-type="picture-img"
              :accept="['image/png','image/jpeg','image/svg+xml','image/gif','image/x-photoshop']"
              :fileType="'image'"
              @success="handleUploadSuccess"
              :viewDisplay="true"
              :props="{ label: 'msg', value: 'msg' }"
              :propsHttp="{ url: 'msg'}"
              @change="handleAttorneyUpload">
              <template #attorneyUrlDesc>
                <div class="el-upload__tip">请下载模板填写后上传，支持JPG/PNG格式</div>
              </template>
            </avue-upload>
          </div> -->

          <!-- 模版下载链接 -->
          <!-- <div class="template-download">
            <el-button type="text" @click="handleTemplate()" :loading="templateLoading">
              点击下载模版
              <i class="el-icon-download el-icon--right"></i>
            </el-button>
          </div> -->

          <!-- 已上传文件预览 -->
          <!-- <div v-if="form.attorneyUrl" class="file-preview" style="margin-top: 10px;">
            <el-image
              style="width: 100px; height: 100px"
              :src="form.attorneyUrl"
              :preview-src-list="[form.attorneyUrl]">
            </el-image>
          </div> -->
        <!-- </div>

      </template> -->
      <template #attorneyUrlTemplateForm>
        <div class="template-download">
          <el-button type="text" @click="handleTemplate()" :loading="templateLoading">
            点击下载模版
            <i class="el-icon-download el-icon--right"></i>
          </el-button>
        </div>
      </template>

      <!-- 其他资料上传 -->
      <template #otherFileUrlListForm>
        <avue-upload
          v-model="form.otherFileUrlList"
          :action="actionurl18"
          :multiple="true"
          :propsHttp="{ url: 'path', name: 'name', res: 'data'}"
          :props="{ label: 'name', value: 'path' }"
          :upload-after="uploadAfter"
          :upload-delete="uploadDelete"
          @change="handleOtherFileUpload">
        </avue-upload>
      </template>

      <template #menu="{row}">
        <el-button size="small" type="text" @click="rowDel(row)">注销</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>

      <template slot="otherFileUrlListImgForm">
        <div style="width: 400px; height: 200px" >
          <p style="margin: 0;"  v-for="(item, index) in form.otherFileUrlList" :key="index">{{item.name}}</p>
        </div>
      </template>

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

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

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

function getPath(path, done) {
  console.log(path, 'path')
  if (!path) return  done();
  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: [],
      attorneyTemplateUrl: '', // 根据实际路径调整
      otherFileList: [],
      templateLoading: false,
    };
  },
  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,
              },
              {
                label: "授权书模版下载",
                span: 12,
                showFileList: false,
                multiple: false,
                formslot: true,
                size: "small",
                prop: "attorneyUrlTemplate",
                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: "attorneyUrl",
                action: putFile(5),
                viewDisplay: false,
                desc: 'hhhhhhhh'
              },

              {
                type: "upload",
                label: "其他资料上传",
                span: 12,
                showFileList: true,
                formslot: true,
                multiple: true,
                size: "small",
                prop: "otherFileUrlList",
                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: "attorneyUrlImg",
                formslot: true,
                editDisplay: false,
                addDisplay: false,
                viewDisplay: true,
              },
              {
                label: "其他资料",
                span: 12,
                prop: "otherFileUrlListImg",
                formslot: true,
                editDisplay: false,
                addDisplay: false,
                viewDisplay: true,
              },
            ],
          },
        ],
      }
    },
    actionurl() {
      return putFile(5)
    },
    actionurl18() {
      return putFileObj()
    }
  },
  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) {
      console.log(row, '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(() => {
        });
    },
    // 授权书上传
    handleAttorneyUpload(fileList, fileListAll) {
    //   console.log(fileList, fileListAll, '==========');
    // if (fileListAll && fileListAll.length > 0) {
    //   const file = fileListAll[0];
    //   if (file.response) {
    //     // 假设上传成功后返回的URL在 response.msg 中
    //     this.$set(this.form, 'attorneyUrl', file.response.msg);
    //   }
    // }
  },


  uploadAfter(res, done) {
    // 上传之后把数据存起来
    // if (this.form.otherFileUrlList.length > 0) {
    //   this.otherFileList = [...this.form.otherFileUrlList, res]
    // } else {
    //   this.otherFileList.push(res)
    // }
    this.otherFileList.push(res)
    done()
  },
  handleUploadSuccess(res) {
    console.log(res, '----')
    // 上传之后把数据存起来
    this.form.attorneyUrl = res.msg
    console.log(res,this.form.attorneyUrl, '----')
  },
  uploadDelete(file, column){
    if(column) {
      console.log('this.otherFileListhou',column, this.otherFileList)
      // 删除之后把数据删除
      let list = this.otherFileList.filter(item => item.path !== column.url)
      this.otherFileList = list
    }


  },

    rowSave(row, done, loading) {
      console.log('rowSave', row, this.otherFileList)
      row.authUrlId = getPath(row.authUrlId, done)
      row.identityUrl4Id = getPath(row.identityUrl4Id, done)
      row.identityUrl5Id = getPath(row.identityUrl5Id, done)
      row.attorneyUrl = getPath(row.attorneyUrl, done)

      row.otherFileUrlList = this.otherFileList
// dictValue
      // let jobCompanyIndustry = this.getTradeDicData.find(i => i.id === row.tradeId).name
      // let jobCompanyNature = this.getTradeDicData.find(i => i.dictKey === row.nature).dictValue
      console.log(row.$tradeId, '----------------------------------');
      companyInfoAdd({
        authUrlId: row.authUrlId,
        nature: row.nature,
        jobCompanyNature: row.$nature,
        tradeId: row.tradeId,
        jobCompanyIndustry: 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,
        otherFileUrlList: row.otherFileUrlList,
        attorneyUrl: row.attorneyUrl,
        manager: row.manager,
        masterIdentity: row.masterIdentity,
        masterName: row.masterName,
        percent: row.percent,
        stationId: row.stationId,
        telphone: row.telphone,
        managerIdCard: row.managerIdCard,
      }).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, done)
      row.identityUrl4Id = getPath(row.identityUrl4Id, done)
      row.identityUrl5Id = getPath(row.identityUrl5Id, done)
      row.attorneyUrl = getPath(row.attorneyUrl, done)

      // return console.log(row.otherFileUrlList, this.form.otherFileUrlList, this.otherFileList, '99999')
      row.otherFileUrlList = this.otherFileList

      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,
        otherFileUrlList: row.otherFileUrlList,
        manager: row.manager,
        masterIdentity: row.masterIdentity,
        masterName: row.masterName,
        percent: row.percent,
        stationId: row.stationId,
        telphone: row.telphone,
        authType: 0,
        managerIdCard: row.managerIdCard,
      }).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) {
      this.otherFileList = []
      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;
          this.otherFileList = res.data.data.otherFileUrlList;
          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();
    },
     /*下载任务模板 */
     handleTemplate() {
      this.templateLoading = true;
      getTemplate("wts")
        .then((rep) => {
          this.templateLoading = false;
          window.open(rep.data.data);
        })
        .catch(() => {
          this.templateLoading = false;
        });
    },
  },
  watch: {},
};
</script>

<style></style>
