<!--
 * @FilePath: index.vue
 * @Author: 旭颖
 * @Date: 2022-12-13 11:41:05
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-02-01 19:55:07
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    :before-close="handleClose"
    title="驻派工厂"
    width="600px"
  >
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="驻派工厂:">
        <el-select
          v-model="factory_id"
          filterable
          :loading="loading"
          placeholder="请选择驻派工厂"
          style="width: 100%"
        >
          <el-option
            v-for="item in companyList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="sure">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
  // import { getFactory } from './api/index'
  import { useUserStore } from '@/store/modules/user'
  export default defineComponent({
    name: 'RoleManagementEdit',

    setup() {
      const state = reactive({
        formRef: null,
        dialogVisible: false,
        factory_id: '',
        companyList: [],
      })

      const showEdit = () => {
        factoryList()
        state.dialogVisible = true
      }
      const handleClose = () => {
        state.dialogVisible = false
      }
      const sure = () => {
        state.companyList.map((item) => {
          if (item.id == state.factory_id) {
            localStorage.setItem('factory', JSON.stringify(item))
          }
        })
        state.dialogVisible = false
        setTimeout(() => {
          location.reload()
        }, 1000)
      }
      //工厂列表
      const factoryList = async () => {
        const userStore = useUserStore()
        const { factories } = storeToRefs(userStore)
        state.companyList = factories
        let factory = localStorage.getItem('factory')
        factory = factory ? JSON.parse(factory) : ''
        if (factory) {
          state.factory_id = factory.id
        } else {
          state.factory_id = state.companyList ? state.companyList[0].id : ''
          localStorage.setItem('factory', JSON.stringify(state.companyList[0]))
        }
        state.loading = false
      }
      onMounted(() => {})
      return {
        ...toRefs(state),
        showEdit,
        factoryList,
        sure,
        handleClose,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .text {
    display: flex;
    line-height: 28px;
    .label {
      flex: 0 0 80px;
    }
    .people {
      display: inline-block;
      margin-right: 5px;
    }
  }
</style>
