<template>
  <div>
    <el-form :model="formData" :rules="formRules" ref="dataForm">
      <el-card style="margin-top: -30px">
        <el-button-group style="display: flex">
          <el-button type="primary" @click.native="submitUpload()" style="margin: 0 60px 10px auto; height: 35px"
                     :loading="loading">提交
          </el-button>
        </el-button-group>
        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>人员类别：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="userType">
              <el-select v-model="formData.userType" style="width: 100%" placeholder="请选择人员类别"
                         clearable="true" @change="thirdSysChange">
                <el-option
                  v-for="item in deviceUserType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                  <span style="float: left;font-size: 13px">{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <div class="ao-text">
              <span>人员名称：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="userName">
              <el-input v-model="formData.userName" auto-complete="off" :disabled="editTye == 2"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>联系电话：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="contact1">
              <el-input v-model="formData.contact1" auto-complete="off" ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <div class="ao-text">
              <span>其他联系方式：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="contact2">
              <el-input v-model="formData.contact2" auto-complete="off" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>备注：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="remark">
              <el-input v-model="formData.remark" auto-complete="off" type="textarea" autosize></el-input>
            </el-form-item>
          </el-col>

        </el-row>

      </el-card>
    </el-form>

  </div>
</template>

<script>
import draggable from "vuedraggable";
import store from "../../../store";
import { filterDeviceUser,insertCompanyUser,deleteDeviceUser,updateDeviceUser } from '@/api/dev/deviceUser'
import ElImageViewer from "element-ui/packages/image/src/image-viewer"

export default {
  name: "depUserAddDialog",
  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    deviceUserType: {
      type: Array,
      required: true,
    },
    inputQuery: {
      type: Object,
      required: true,
    },
    editTye: {
      type: Object,//1:新增，2：编辑
      required: true,
    },
    addType: {
      type: Object,
      required: true,
    },

  },
  data() {
    /* 手机号 */
    var isMobileNumber = (rule, value, callback) => {
      if (!value) {
        return new Error('请输入电话号码')
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        const isPhone = reg.test(value)
        value = Number(value) //转换为数字
        if (typeof value === 'number' && !isNaN(value)) {
          //判断是否为数字
          value = value.toString() //转换成字符串
          if (value.length < 0 || value.length > 12 || !isPhone) {
            //判断是否为11位手机号
            callback(new Error('手机号码格式如:138xxxx8754'))
          } else {
            callback()
          }
        } else {
          callback(new Error('请输入电话号码'))
        }
      }
    }

    return {
      BASE_URL: process.env.VUE_APP_BASE_API,
      code: "",
      isCleck:false,
      formData: {
        devCodeFk: null,
        type: 0,
        contact1: null,
        contact2: null,
        remark: null,
        userType: null,
        userName: null,
        auditStatus: 6
      },
      formRules: {
        contact1: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: isMobileNumber, trigger: 'blur' }
        ],
        userName: [
          {required: true, message: "请输入人员名称", trigger: "blur"}
        ],
        userType: [
          {required: true, message: "请选择人员类别", trigger: "blur"}
        ],
      },
      loading: false,
      uploadUrl: "",
      fileList: [],
      headers: {},
      choiceFile: "选取文件",

    };
  },
  components: {
    draggable,
    ElImageViewer
  },
  methods: {
    submitUpload() {
      this.$refs["dataForm"].validate(valid => {
        if (!valid) {
          this.$message.error("请核对表单内容是否合法");
          return
        } else {
          this.onSubmit()
        }
      })
    },
    onConfirmSubmit(val) {
      this.formData.repeatUpload = val;
      if (this.$isNotBlank(this.formData.filePath)) {
        if (this.$refs.upload.uploadFiles.length > 0) {
          this.$refs.upload.submit();
          this.onSubmit();
        } else {
          this.onSubmit();
        }

      } else {
        if (this.$refs.upload.uploadFiles.length > 0) {
          this.$refs.upload.submit();
        } else {
          this.$message.warning(`请选择文件`);
        }
      }

    },

    onSubmit() {
        this.formData.devCodeFk = this.inputQuery.devCodeFk;
        if (this.editTye == 1) {
          insertCompanyUser(this.formData).then(response => {
            this.loading = false;
            if (response.code === 20000) {
              this.$message.success("添加成功");
              this.closeDialog(true);
            } else {
              this.$message.error(response.message);
            }
          });
        } else {
          updateDeviceUser(this.formData).then(response => {
            this.loading = false;
            if (response.code === 20000) {
              this.$message.success("添加成功");
              this.closeDialog(true);
            } else {
              this.$message.error(response.message);
            }
          });
        }
      },
    uploadHandleRemove(file, fileList) {
      this.formData.filePath="";
      for (var i=0;i<fileList.length;i++){
        this.formData.filePath+=fileList[i].response.data.name+",";
      }
    },
    uploadHandlePreview(file) {

    },
    uploadHandleExceed(files, fileList) {

    },
    uploadOnchange(file, fileList) {
      let fileName = file.name;
      let uid = file.uid
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (lastName.toLowerCase() !== ".jpg" && lastName.toLowerCase() !== ".png" && lastName.toLowerCase() !== ".doc") {
        this.$message.error("上传文件只能是 jpg,png格式");
        for (let i = 0; i < fileList.length; i++) {//从list删除
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
        return;
      }
      // 限制上传文件的大小
      const isLt = file.size / 1024 / 1024 / 3 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不能超过 3MB");
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
      }
      return isLt;
    },
    uploadHandleSuccess(response, file, fileList) {
      if (response.code === 20000) {
        if(this.formData.filePath==null || this.isCleck==true){
          this.formData.filePath=response.data.name+",";
          this.isCleck=false;
        }else{
          this.formData.filePath+=response.data.name+",";
        }
      } else {
        this.$message.error("文件上传失败：" + response.message);
      }
    },
    uploadHandleError() {

    },

    toViewCompanyCert() {
      this.certFileUrl = this.BASE_URL + "/udiwms/image/register/file/getImage?type=image2&name=";
      window.open(this.certFileUrl + this.formData.filePath);
    },
  },
  filters: {},
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
  },
  created() {
    this.uploadUrl = this.BASE_URL + "/udiwms/upload/register/file";
    this.headers = {
      ADMINID: store.getters.adminId,
      ADMINTOKEN: store.getters.token,
    };
    if (this.inputQuery.formData == null) {
      this.formData = {}
    } else if (this.inputQuery.formData != null && this.inputQuery.formData.addType == 1) {
      this.formData = {}
    } else {
      this.formData = this.inputQuery.formData;
    }
    if (this.formData.filePath != null) {
      this.choiceFile = "更换文件";
      this.isCleck=true;
    } else {
      this.choiceFile = "选取文件";
    }
  },
};
</script>
<style scoped>

.ao-text {
  width: 100%;
  font-size: 13px;
  font-family: "Microsoft YaHei";
  float: right;
  text-align: right;
  margin-top: 10px;
}

</style>



