<template>
  <el-dialog
    :title="!dataForm.id ? '新建' : '编辑'"
    :visible.sync="dialogVisible"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="dataForm" :rules="dataRule" size="small" label-width="100px" label-position="right">
      <template v-if="!loading">
        <el-form-item label="工艺流程" prop="techProc">
          <JnpfInput v-model="techProcDisplay" placeholder="请选择工序生成工艺流程" clearable :style="{ width: '100%' }" :disabled="true">
          </JnpfInput>
        </el-form-item>
        <input type="hidden" v-model="dataForm.techProc" />
        <el-form-item label="状态" prop="enabledStatus">
          <JnpfSelect v-model="dataForm.enabledStatus" placeholder="请选择状态" :options="enabledStatusOptions" :props="enabledStatusProps" clearable :style="{ width: '100%' }">
          </JnpfSelect>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <JnpfTextarea v-model="dataForm.remark" placeholder="请输入备注" :style="{ width: '100%' }" :autoSize="{ minRows: 4, maxRows: 4 }" type="textarea">
          </JnpfTextarea>
        </el-form-item>

        <!-- 分割线 -->
        <div style="border-top: 1px solid #e8e8e8; margin: 20px 0;"></div>
        
        <!-- 工序列表 -->
        <div style="padding: 0 10px;">
          <div style="font-weight: bold; margin-bottom: 12px; color: #606266;">工序信息</div>
          <el-table
            :data="procList"
            :border="true"
            :style="{ width: '100%', maxHeight: '300px', overflow: 'auto' }"
            @selection-change="handleProcSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="procCd" label="工序编码" align="center"></el-table-column>
            <el-table-column prop="procName" label="工序名称" align="center"></el-table-column>
            <el-table-column prop="remark" label="备注" align="center"></el-table-column>
            <el-table-column prop="createUserName" label="创建人" align="center"></el-table-column>
            <el-table-column prop="creatorTime" label="创建时间" align="center" :formatter="jnpf.tableDateFormat1"></el-table-column>
          </el-table>
        </div>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading" :disabled="!hasSelectedProcs">保 存</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { mapGetters } from 'vuex'

export default {
  components: {},
  props: [],
  data() {
    return {
      dialogVisible: false,
      loading: false,
      btnLoading: false,
      formRef: 'formRef',
      eventType: '',
      techProcDisplay: '',
      dataForm: {
        id: '',
        techProc: undefined,
        enabledStatus: 1,
        remark: undefined,
        procList: []
      },
      dataRule: {
        
        enabledStatus: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change',
          },
        ],
      },
      enabledStatusOptions: [
        { fullName: "启用", id: 1 },
        { fullName: "未启用", id: 2 },
      ],
      enabledStatusProps: { label: "fullName", value: "id" },
      procList: [],
      selectedProcs: [],
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    // 判断是否有选中的工序
    hasSelectedProcs() {
      return this.selectedProcs && this.selectedProcs.length > 0;
    },
  },
  created() {
    this.getProcList();
  },
  methods: {
    init(id) {
      this.dataForm.id = id || '';
      this.dialogVisible = true;
      this.loading = true;
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();
        if (this.dataForm.id) {
          request({
            url: `/api/example/techproc/${this.dataForm.id}`,
            method: 'get'
          }).then(res => {
            this.dataForm = res.data
            // 将存储的编码拼接转换为名称拼接显示
            this.convertCodeToName(res.data.techProc)
            this.loading = false
          })
        } else {
          this.loading = false
        }
      });
    },
    // 获取工序列表（不分页）
    getProcList() {
      request({
        url: `/api/example/proc/getProcList`,
        method: 'get'
      }).then(res => {
        this.procList = res.data || [];
      });
    },
    // 将编码拼接转换为名称拼接显示
    convertCodeToName(codeStr) {
      if (!codeStr) {
        this.techProcDisplay = ''
        return
      }
      const codes = codeStr.split('_')
      const names = codes.map(code => {
        const proc = this.procList.find(item => item.procCd === code)
        return proc ? proc.procName : code
      })
      this.techProcDisplay = names.join('_')
    },
    // 工序选择变化处理 - 按列表顺序排列
    handleProcSelectionChange(val) {
      this.selectedProcs = val;
      // 获取选中的编码集合
      const selectedCodes = new Set(val.map(item => item.procCd));
      // 按列表顺序过滤选中的工序
      const sortedSelected = this.procList.filter(item => selectedCodes.has(item.procCd));
      // 显示用：工序名称拼接（按列表顺序）
      this.techProcDisplay = sortedSelected.map(item => item.procName).join('_');
      // 存储用：工序编码拼接（按列表顺序）
      this.dataForm.techProc = sortedSelected.map(item => item.procCd).join('_');
      // 保存选中的工序编码列表（按列表顺序）
      this.dataForm.procList = sortedSelected.map(item => item.procCd);
    },
    dataFormSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          const isEdit = !!this.dataForm.id;
          const url = isEdit ? `/api/example/techproc/${this.dataForm.id}` : '/api/example/techproc';
          const method = isEdit ? 'put' : 'post';

          request({
            url: url,
            method: method,
            data: this.dataForm
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.btnLoading = false;
                this.dialogVisible = false;
                this.$emit('refresh', true)
              }
            })
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    handleClose() {
      this.dialogVisible = false;
      this.$emit('refresh',true)
    },
    changeData(model, index) {
      this.isEdit = true
    }
  }
}
</script>