<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model
        ref="form"
        :model="model"
        :rules="validatorRules"
        slot="detail"
      >
        <!-- 人员选择 -->
        <a-row style="padding-top: 20px">
          <DeptUserList
            :model-value.sync="divUsers"
            :data.sync="checkUsers"
          />
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import DeptUserList from '@views/workOrder/components/DeptUserList/index.vue'

export default {
  name: 'WorkDivisionForm',
  components: { DeptUserList },

  props: {
    disabled: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      checkUsers: [],     // 左侧可选人员
      divUsers: [],       // 子组件返回：[{executor, torType, ...}]
      model: {},

      confirmLoading: false,

      validatorRules: {},

      url: {
        userList: '/sys/user/departUserList1',
        divList: 'workOrder/workDivision/list',
        add: '/workOrder/workDivision/add',
        dsadd: '/workOrder/workDivision/add',
        edit: '/workOrder/workDivision/edit'
      }
    }
  },

  computed: {
    formDisabled() {
      return this.disabled
    }
  },

  created() {
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },

  methods: {
    /** 新增 */
    add(record) {
      this.edit(this.modelDefault)
      this.model.regularId = record.regularId
      this.model.workOrder = record.id
      this.model.deviceId = record.deviceId
      this.model.planId = record.planId
      this.loadUserList()
      this.loadDivisionUsers()
    },

    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
    },

    /** 可选人员 */
    loadUserList() {
      getAction(this.url.userList, { pageNo: 1, pageSize: 100 }).then(res => {
        if (res.success) {
          this.checkUsers = res.result.records
        }
      })
    },

    /** 已派工人员（编辑态） */
    loadDivisionUsers() {
      getAction(this.url.divList, {
        pageNo: 1,
        pageSize: 100,
        workOrder: this.model.workOrder
      }).then(res => {
        if (res.success) {
          this.divUsers = res.result.records
        }
      })
    },

    /** 提交 */
    submitForm() {
      if (!this.divUsers || this.divUsers.length === 0) {
        this.$message.warning('请选择派工人员！')
        return
      }

      // ✅ 负责人校验
      const leaders = this.divUsers.filter(u => u.torType === 0)
      if (leaders.length > 1) {
        this.$message.warning('负责人只能指定一人！')
        return
      }

      // ✅ 构造 executorList（后端需要的结构）
      this.model.executorList = this.divUsers.map(u => ({
        executor: u.executor,
        torType: u.torType
      }))

      const that = this
      this.$refs.form.validate(valid => {
        if (!valid) return

        that.confirmLoading = true
        const url = this.model.workOrder ? this.url.dsadd : this.url.add

        httpAction(url, this.model, 'post')
          .then(res => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          })
          .finally(() => {
            that.confirmLoading = false
          })
      })
    }
  }
}
</script>
