<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
<!--        <a-row>-->
<!--          <a-col :span="10">-->
<!--            <a-form-model-item label="人员类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="torType">-->
<!--              <j-dict-select-tag v-model="model.torType" dictCode="tor_type" placeholder="请选择人员类型" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="14">-->
<!--            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">-->
<!--              <a-input v-model="model.remark" placeholder="请输入备注" ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--        </a-row>-->
        <a-row style="padding-top: 20px">
          <DeptUserList :model-value.sync="setUsers" :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: 'WorkDivisionSetForm',
    components: {
      DeptUserList
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        checkUsers: [],     // 左侧可选人员
        setUsers: [],       // 子组件返回：[{executor, torType, ...}]
        model: {},

        confirmLoading: false,

        validatorRules: {},
        url: {
          userList: "/sys/user/departUserList1",
          setList: "workOrder/workDivisionSet/list",
          add: "/workOrder/workDivisionSet/add",
          dsadd: "/workOrder/workDivision/add",
          edit: "/workOrder/workDivisionSet/edit",
          queryById: "/workOrder/workDivisionSet/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add (record) {
        this.edit(this.modelDefault);
        this.model.regularId = record.regularId;
        this.model.workOrder = record.workOrder;
        this.model.deviceId = record.deviceId;
        this.model.planId = record.planId;
        this.checkUserList();
        this.setedUserList();
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      checkUserList() {
        getAction(this.url.userList,{pageNo: 1,pageSize:100}).then(res=>{
          if (res.success) {
            this.checkUsers = res.result.records;
          }
        });
      },
      setedUserList() {

        getAction(this.url.setList,{pageNo: 1,pageSize:100,regularId:this.model.regularId}).then(res=>{
          if (res.success) {
            this.setUsers = res.result.records;
          }
        });
      },
      submitForm () {
        const newUsers = this.setUsers.filter(item=>item.id===undefined)
        if(newUsers == null||newUsers.length===0){
          this.$message.warning("请选择派工人员！");
          return
        }
        // ✅ 负责人校验
        const leaders = this.setUsers.filter(u => u.torType === 0)
        if (leaders.length > 1) {
          this.$message.warning('负责人只能指定一人！')
          return
        }

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

        // 根据是否有工单判断是否是预设派工
        if(this.model.workOrder){
          const that = this;
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.confirmLoading = true;
              httpAction(this.url.dsadd,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;
              });
            }
          });
        }else {
          const that = this;
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.confirmLoading = true;
              let httpurl = this.url.add;
              let method = 'post';
              httpAction(httpurl, this.model, method).then((res) => {
                if (res.success) {
                  that.$message.success(res.message);
                  // that.$emit('ok');
                } else {
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
              })
            }

          })
        }
      },
    }
  }
</script>