<template>
  <el-dialog title="快捷创建检验任务" :visible.sync="dialogVisible" width="800px" append-to-body @close="handleClose" :close-on-click-modal="false">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="0px" style="margin-bottom: 12px;">
      <el-form-item prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入方案名称搜索"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 280px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="el-icon-plus" size="mini" @click="schemeAddOpen = true">新增方案</el-button>
      </el-form-item>
    </el-form>

    <div style="display: flex; gap: 12px; min-height: 360px; max-height: 450px;">
      <div style="width: 35%; border: 1px solid #ebeef5; border-radius: 4px; overflow-y: auto; max-height: 100%;">
        <div
          v-for="item in templateList"
          :key="item.templateId"
          style="padding: 10px 12px; cursor: pointer; border-bottom: 1px solid #ebeef5; transition: background 0.2s;"
          :style="{ background: selectedTemplate && selectedTemplate.templateId === item.templateId ? '#ecf5ff' : 'transparent' }"
          @click="handleSchemeClick(item)"
        >
          <div style="font-size: 14px; font-weight: 500; color: #303133;">{{ item.templateName }}</div>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">所属单位：{{ item.templateUnit || '-' }}</div>
          <div v-if="item.templateDesc" style="font-size: 12px; color: #909399; margin-top: 2px;">{{ item.templateDesc }}</div>
        </div>
        <el-empty v-if="templateList.length === 0" description="暂无方案" :image-size="60" />
      </div>

      <div style="width: 65%; border: 1px solid #ebeef5; border-radius: 4px; padding: 8px; overflow-y: auto;">
        <div v-if="!selectedTemplate" style="text-align: center; padding-top: 120px; color: #c0c4cc; font-size: 14px;">
          <i class="el-icon-document" style="font-size: 48px; display: block; margin-bottom: 8px;"></i>
          请先在左侧选择一个检验方案
        </div>
        <template v-else>
          <div style="font-size: 13px; font-weight: 500; color: #606266; margin-bottom: 8px; padding-bottom: 8px; border-bottom: 1px solid #ebeef5;">
            检验项列表（{{ checkItemList.length }} 项）
          </div>
          <el-table v-loading="checkItemLoading" :data="checkItemList" border size="small" style="width: 100%">
            <el-table-column label="检验项名称" prop="itemName" min-width="120" />
            <el-table-column label="标准值" prop="standardTarget" width="80" align="center" />
            <el-table-column label="上限" prop="targetUpper" width="80" align="center" />
            <el-table-column label="下限" prop="targetLower" width="80" align="center" />
            <el-table-column label="单位" prop="unit" width="60" align="center" />
            <el-table-column label="类型" width="60" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.qualitativeQuantitative === 1 ? '定量' : '定性' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </div>

    <div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid #ebeef5;">
      <el-form :model="form" ref="taskForm" label-width="80px" size="small">
        <el-form-item label="任务编号" prop="taskCode" :rules="[{ required: true, message: '请输入任务编号', trigger: 'blur' }]">
          <el-input v-model="form.taskCode" placeholder="请输入任务编号" style="width: 280px;" />
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 8px;">
        <CoilSelector use-trigger multiple @confirm="handleCoilConfirm">
          <el-button type="primary" plain icon="el-icon-plus" size="small">选择钢卷</el-button>
        </CoilSelector>
        <span v-if="selectedCoils.length > 0" style="margin-left: 8px; font-size: 13px; color: #67c23a;">
          已选 {{ selectedCoils.length }} 卷
        </span>
        <el-button v-if="selectedCoils.length > 0" type="text" size="small" style="margin-left: 4px; color: #f56c6c;" @click="selectedCoils = []">清除</el-button>
      </div>
      <div v-if="selectedCoils.length > 0" style="display: flex; flex-wrap: wrap; gap: 8px;">
        <div v-for="(coil, index) in selectedCoils" :key="coil.coilId || index" style="display: flex; align-items: center; gap: 4px;">
          <CurrentCoilNo @click.native="handleClickCoil(coil)" :currentCoilNo="coil.currentCoilNo || coil.coilNo || ''" />
          <el-button type="text" icon="el-icon-close" size="mini" @click="selectedCoils.splice(index, 1)"></el-button>
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button :disabled="!canConfirm" type="primary" @click="handleConfirm">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>

    <el-dialog title="新增检验方案" :visible.sync="schemeAddOpen" width="700px" append-to-body @close="schemeAddOpen = false">
      <el-form ref="schemeAddForm" :model="schemeAddForm" :rules="schemeAddRules" label-width="80px" size="small">
        <el-form-item label="方案名称" prop="templateName">
          <el-input v-model="schemeAddForm.templateName" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="方案单位" prop="templateUnit">
          <el-select v-model="schemeAddForm.templateUnit" placeholder="请选择方案单位" filterable allow-create style="width: 100%;">
            <el-option v-for="unit in templateUnitOptions" :key="unit" :label="unit" :value="unit" />
          </el-select>
        </el-form-item>
        <el-form-item label="方案描述" prop="templateDesc">
          <el-input v-model="schemeAddForm.templateDesc" type="textarea" :rows="3" placeholder="请输入方案描述" />
        </el-form-item>
        <el-form-item label="待检项" prop="inspectionItem">
          <CheckItemTransfer v-model="schemeAddForm.inspectionItem" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="schemeAddForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="schemeAddLoading" type="primary" @click="submitSchemeAdd">确 定</el-button>
        <el-button @click="schemeAddOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { listInspectionItemTemplate, addInspectionItemTemplate } from "@/api/mes/qc/inspectionItemTemplate";
import { getInfoByInspectionItem } from "@/api/mes/qc/inspectionItemTemplate";
import CoilSelector from "@/components/CoilSelector/index.vue";
import CurrentCoilNo from "@/components/KLPService/Renderer/CurrentCoilNo.vue";
import CheckItemTransfer from '@/components/KLPService/CheckItemSelect/index'

export default {
  name: "SchemeSelect",
  components: {
    CoilSelector,
    CurrentCoilNo,
    CheckItemTransfer
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      total: 0,
      templateList: [],
      selectedTemplate: null,
      checkItemList: [],
      checkItemLoading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 999,
        templateName: undefined
      },
      selectedCoils: [],
      form: {
        taskCode: undefined
      },
      schemeAddOpen: false,
      schemeAddLoading: false,
      schemeAddForm: {
        templateName: undefined,
        templateUnit: undefined,
        templateDesc: undefined,
        inspectionItem: undefined,
        remark: undefined
      },
      schemeAddRules: {
        templateName: [
          { required: true, message: '请输入方案名称', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    canConfirm() {
      return this.selectedTemplate && this.form.taskCode;
    },
    templateUnitOptions() {
      return [...new Set(this.templateList.map(item => item.templateUnit).filter(Boolean))].sort();
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
      if (val) {
        this.selectedTemplate = null;
        this.checkItemList = [];
        this.form.taskCode = undefined;
        this.selectedCoils = [];
        this.getList();
      }
    }
  },
  methods: {
    getList() {
      this.loading = true;
      listInspectionItemTemplate(this.queryParams).then(response => {
        this.templateList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams.templateName = undefined;
      this.handleQuery();
    },
    handleSchemeClick(row) {
      this.selectedTemplate = row;
      this.loadCheckItems(row);
    },
    loadCheckItems(template) {
      if (!template.inspectionItem) {
        this.checkItemList = [];
        return;
      }
      this.checkItemLoading = true;
      getInfoByInspectionItem(template.inspectionItem).then(response => {
        this.checkItemList = response.data || [];
        this.checkItemLoading = false;
      }).catch(() => {
        this.checkItemList = [];
        this.checkItemLoading = false;
      });
    },
    handleCoilConfirm(coils) {
      this.selectedCoils = coils;
    },
    handleClickCoil(coil) {
      this.$router.push('/wms/coil/' + coil.coilId);
    },
    handleConfirm() {
      this.$refs["taskForm"].validate(valid => {
        if (valid && this.selectedTemplate) {
          const coilIds = this.selectedCoils.map(c => c.coilId).join(",");
          this.$emit("confirm", {
            template: this.selectedTemplate,
            taskCode: this.form.taskCode,
            coilIds: coilIds || undefined
          });
          this.dialogVisible = false;
        }
      });
    },
    submitSchemeAdd() {
      this.$refs["schemeAddForm"].validate(valid => {
        if (!valid) return;
        this.schemeAddLoading = true;
        addInspectionItemTemplate(this.schemeAddForm).then(response => {
          this.$modal.msgSuccess("新增方案成功");
          this.schemeAddOpen = false;
          this.schemeAddForm = { templateName: undefined, templateUnit: undefined, templateDesc: undefined, inspectionItem: undefined, remark: undefined };
          this.getList();
        }).finally(() => {
          this.schemeAddLoading = false;
        });
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.$emit("update:visible", false);
      this.$emit("close");
    }
  }
};
</script>
