<template>
  <div class="user-add-or-update">
    <el-dialog
      width="530px"
      @close="closeDialog"
      :title="!dataForm.id ?  buttons.add :buttons.edit"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <!-- 取消    :rules="dataRule"-->
      <el-form :inline="true" :model="dataForm" label-position="top" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
        <el-form>
          <el-form-item :label="buttons.username||'用户账号'" prop="userName">
            <el-input v-model="dataForm.userName" style="width: 150px;" placeholder="登录帐号"></el-input>
          </el-form-item>
          <el-form-item :label="buttons.password||'密码'" prop="password" :class="{ 'is-required': !dataForm.id }">
            <el-input v-model="dataForm.password" style="width: 150px;" type="password" ></el-input>
          </el-form-item>
          <el-form-item :label="buttons.comfirmPassword||'确认密码'" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
            <el-input v-model="dataForm.comfirmPassword" style="width: 150px;" type="password"></el-input>
          </el-form-item>
        </el-form>
        <el-form>
          <el-form-item :label="buttons.userDisplay||'用户名'" prop="userDisplay">
            <el-input v-model="dataForm.userDisplay" style="width: 150px;" ></el-input>
          </el-form-item>
          <el-form-item :label="buttons.email||'邮箱'" prop="email">
            <el-input v-model="dataForm.email" style="width: 150px;" ></el-input>
          </el-form-item>
          <el-form-item :label="buttons.mobile||'手机号'" prop="mobile">
            <el-input v-model="dataForm.mobile" style="width: 150px;" placeholder="手机号"></el-input>
          </el-form-item>
        </el-form>
        <el-form>
          <el-form-item :label="buttons.site||'工厂'">
            <el-select v-model="dataForm.site" filterable clearable placeholder="请选择工厂" style="width: 150px;">
              <el-option
                v-for="i in siteOptions"
                :key="i.siteid"
                :label="i.sitename"
                :value="i.siteid">
              </el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="车间">-->
<!--            <el-select v-model="dataForm.workShopId" placeholder="请选择" style="width: 150px;"  clearable>-->
<!--              <el-option-->
<!--                v-for = "i in workShopList"-->
<!--                :key = "i.workShopId"-->
<!--                :label = "i.workShopName"-->
<!--                :value = "i.workShopId">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item v-if="showSupplierPicker">
            <span slot="label" style="" @click="getBaseList(501)"><a herf="#">{{'供应商'}}</a></span>
            <el-input v-model="dataForm.supplierNo" style="width: 150px;" placeholder="供应商"></el-input>
          </el-form-item>
        </el-form>
        <el-form>
          <el-form-item label="角色" size="mini" prop="roleIdList">
            <el-checkbox-group v-model="dataForm.roleIdList">
              <el-checkbox
                v-for="role in roleList"
                :key="role.roleId"
                :label="role.roleId">{{role.roleName}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <el-form>
          <el-form-item label="状态" size="mini" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="0">{{buttons.disable||'禁用'}}</el-radio>
              <el-radio :label="1">{{buttons.normal||'正常'}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="dataFormSubmit()">{{buttons.submit||'确定'}}</el-button>
         <el-button @click="visible = false">{{buttons.close||'取消'}}</el-button>
    </span>
    </el-dialog>

    <Chooselist ref="baseList"  @getBaseData="getBaseData"></Chooselist>
  </div>

</template>

<script>
  import Chooselist from '@/views/modules/common/Chooselist'
import {getEamWorkShop, getSite2} from "@/api/factory/site.js";
import {searchSysLanguage} from "@/api/sysLanguage.js"
  import {
    searchFunctionButtonList,
  } from "@/api/sysLanguage.js"
export default {
  components: {
    Chooselist
  },
  data() {
    return {
      tagNo:'',
      visible: false,
      roleList: [],
      factorys: [],
      languageList: [],
      dataForm: {
        id: 0,
        userName: '',
        password: '',
        comfirmPassword: '',
        languageDefault: 'cn',
        salt: '',
        email: '',
        mobile: '',
        roleIdList: [],
        status: 1,
        site: '',
        userDisplay: '',
        workShopId:'',
        supplierNo: '',
      },
      buttons: {
        add: '添加',
        edit: '编辑',
        username: '用户账号',
        userDisplay: '用户名',
        email: '邮箱',
        mobile: '手机号',
        status: '状态',
        disable: '禁用',
        normal: '正常',
        password:'密码',
        comfirmPassword:'确认密码',
        submit: '确定',
        close: '取消',
        site: '工厂',
        language: '语言',
      },
      workShopList:[],
      siteOptions: [],
      showSupplierPicker: false,
    }
  },
  watch: {
    'dataForm.roleIdList'(val) {
      const hasSupplier = Array.isArray(val) && val.some(id => {
        const role = this.roleList.find(r => r.roleId === id)
        return role && role.roleName === '供应商'
      })
      if (!hasSupplier) {
        // 取消供应商角色时清空供应商相关数据(按需保留/删除)
        this.dataForm.supplierNo = ''
      }
      this.showSupplierPicker = hasSupplier
    }
  },
  methods: {
    getFunctionButtonList() {
      let queryButton = {
        functionId: this.$route.meta.menuId,
        tableId: '*',
        languageCode: this.$i18n.locale,
        objectType: 'button'
      }
      searchFunctionButtonList(queryButton).then(({data}) => {
        if (data.code == 0 && data.data) {
          this.buttons = data.data
        }
      })
    },
    getBaseData(val){
      if (this.tagNo === 501){
        this.dataForm.supplierNo = val.supplier_no
      }
    },
    // 获取基础数据列表
    getBaseList(val){
      this.tagNo = val
      this.$nextTick(() => {
        let strVal = "";
        let conSql = "";
        if (val === 501) {
          if (!this.dataForm.site) {
            this.$message.warning('请先选择工厂')
            return
          }
          strVal = this.dataForm.supplierNo || ''
          conSql = " and  site = '"  + this.dataForm.site + "'"
        }
        this.$refs.baseList.init(val,strVal,conSql)
      })
    },
    // 加载工厂下拉（site表） - rqrq
    loadSiteOptions () {
      let inData = {
        username: this.$store.state.user.name,
        siteid: '',
        sitename: ''
      }
      getSite2(inData).then(({data}) => {
        if (data && data.code === 0) {
          this.siteOptions = data.rows || []
        } else {
          this.siteOptions = []
          this.$message.error((data && data.msg) || '加载工厂失败')
        }
      }).catch(() => {
        this.siteOptions = []
        this.$message.error('加载工厂失败')
      })
    },
    // 获取多语言列表
    getLanguageList() {
      let queryLanguage = { languageCode: this.$i18n.locale}
      searchSysLanguage(queryLanguage).then(({data}) => {
        this.languageList = data.rows
      })
    },

    init(id) {
      this.dataForm.id = id || 0
      this.loadSiteOptions()
      this.getLanguageList();
      this.$http({
        url: this.$http.adornUrl('/sys/role/select'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        this.roleList = data && data.code === 0 ? data.list : []
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.userName = data.user.username
              this.dataForm.salt = data.user.salt
              this.dataForm.email = data.user.email
              this.dataForm.mobile = data.user.mobile
              this.dataForm.roleIdList = data.user.roleIdList
              this.dataForm.status = data.user.status
              this.dataForm.languageDefault = data.user.languageDefault
              this.dataForm.site = data.user.site == null ? '' : data.user.site.toString()
              this.dataForm.userDisplay = data.user.userDisplay
              this.dataForm.workShopId = data.user.workShopId
              this.dataForm.supplierNo = data.user.supplierNo
            }
          })
        }
      })
      getEamWorkShop({}).then(({data}) => {
        if (data && data.code === 0) {
          this.workShopList=data.rows
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      if (!this.dataForm.site) {
        this.$message.warning('请选择工厂')
        return
      }
      if (!this.dataForm.userDisplay || !String(this.dataForm.userDisplay).trim()) {
        this.$message.warning('用户名不能为空')
        return
      }
      if (this.showSupplierPicker && !this.dataForm.supplierNo) {
          this.$message.warning('请选择供应商')
          return
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sys/user/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'userId': this.dataForm.id || undefined,
              'username': this.dataForm.userName,
              'password': this.dataForm.password,
              'salt': this.dataForm.salt,
              'email': this.dataForm.email,
              'mobile': this.dataForm.mobile,
              'status': this.dataForm.status,
              'roleIdList': this.dataForm.roleIdList,
              'languageDefault': this.dataForm.languageDefault,
              'site': this.dataForm.site,
              'userDisplay': this.dataForm.userDisplay,
              'workShopId': this.dataForm.workShopId,
              'supplierNo': this.dataForm.supplierNo,
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message.success( '操作成功')
              this.visible = false
              this.$emit('refreshDataList')
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    closeDialog(){
      this.dataForm.id = 0
      this.dataForm.userName = ''
      this.dataForm.password = ''
      this.dataForm.comfirmPassword = ''
      this.dataForm.email = ''
      this.dataForm.mobile = ''
      this.dataForm.roleIdList = []
      this.dataForm.status = 1
      this.dataForm.site = ''
      this.dataForm.userDisplay = ''
    }
  },
  created() {
    this.getFunctionButtonList()
  }
}
</script>
<style lang="scss" scoped>

</style>
