<template>
  <div>
    <div class="my-title">{{ type === 1 ? "处理" : "修改" }}</div>
    <e-desc title="基本信息" column="3">
      <e-desc-item label="项目名称">{{ dataForm.projectName }}</e-desc-item>
      <e-desc-item label="任务号">{{ dataForm.orderCode }}</e-desc-item>
      <e-desc-item label="图号">{{ dataForm.mapNumber }}</e-desc-item>
      <e-desc-item label="物料名称">{{ dataForm.productName }}</e-desc-item>
      <e-desc-item label="数量">{{ dataForm.planCnt }}</e-desc-item>
      <e-desc-item label="状态">{{
        dataForm.state
          ? optionsStates.find((item) => item.value === dataForm.state).label
          : ""
      }}</e-desc-item>
      <e-desc-item label="合同交期">{{ dataForm.deliveryDate }}</e-desc-item>
      <e-desc-item label="责任人">{{
        dataForm.responsibilityPerson
      }}</e-desc-item>
    </e-desc>
    <e-desc title="技术协议">
      <e-desc-item v-if="dataForm.attachList1" label="技术协议" span="3">
        <div v-for="(item, index) in dataForm.attachList1" style="display: inline">
          <span v-if="index > 0">,</span>
          <a :key="item.fileName + index" type="primary" href="#" @click="previewFile(item.fileName, item.url)">{{
            item.fileName }}</a>
        </div>
      </e-desc-item>
    </e-desc>
    <e-desc title="技术文件">
      <e-desc-item v-if="dataForm.attachList2" label="技术文件" span="3">
        <div v-for="(item, index) in dataForm.attachList2" style="display: inline">
          <span v-if="index > 0">,</span>
          <a :key="item.fileName + index" type="primary" href="#" @click="previewFile(item.fileName, item.url)">{{
            item.fileName }}</a>
        </div>
      </e-desc-item>
    </e-desc>
    <e-desc title="工艺路线">
      <el-table :data="dataForm.proTechnologyStepNodeList" :row-style="tableRowStyle" border style="width: 100%">
        <el-table-column label="序号" type="index" width="50" align="center">
        </el-table-column>
        <el-table-column prop="nodeName" header-align="center" align="center" min-width="80"
          :show-tooltip-when-overflow="true" label="工种">
        </el-table-column>
        <el-table-column prop="require" header-align="center" align="center" min-width="400"
          :show-tooltip-when-overflow="true" label="工序要求">
        </el-table-column>
      </el-table>
    </e-desc>
    <e-desc title="编程列表">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" style="width: 100%">
        <!-- 编程列表 -->
        <el-table :data="dataForm.proProgramDetailsList || []" border style="width: 100%">
          <el-table-column label="序号" type="index" width="50" align="center">
          </el-table-column>
          <el-table-column prop="nodeName" header-align="center" align="center" min-width="80" label="节点名称">
          </el-table-column>
          <el-table-column prop="require" header-align="center" align="center" min-width="240" label="节点内容">
          </el-table-column>
          <el-table-column prop="preTaskTime" header-align="center" align="center" min-width="100" label="程序时间">
          </el-table-column>
          <el-table-column prop="num" header-align="center" align="center" min-width="100" label="程序数量">
          </el-table-column>
          <el-table-column prop="attachList" header-align="center" align="center" label="程序文件">
            <template slot-scope="scope">
              <el-button :disabled="!scope.row.attachList || scope.row.attachList.length === 0
                " type="text" size="small" @click="attachDetails(scope.row.attachList)">查看</el-button>
            </template>
          </el-table-column>

          <!-- Add dialog for row operations -->
          <el-table-column header-align="center" align="center" width="120" label="操作">
            <template slot-scope="scope">
              <el-button v-if="type === 2" type="text" size="small"
                @click="handleEdit(scope.row, scope.$index)">编辑</el-button>
              <el-button v-if="type === 1" type="text" size="small" style="color: red"
                @click="deleteRow(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- Add/Edit dialog -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
          <el-form :model="rowForm" ref="rowForm" label-width="100px">
            <el-form-item label="节点名称">
              <el-input v-model="rowForm.nodeName" placeholder="请输入节点名称"></el-input>
            </el-form-item>
            <el-form-item label="节点内容">
              <el-input v-model="rowForm.require" placeholder="请输入节点内容"></el-input>
            </el-form-item>
            <el-form-item label="预估工时">
              <el-input-number v-model="rowForm.preTaskTime" :min="1" placeholder="请输入预估工时"></el-input-number>
            </el-form-item>
            <el-form-item label="程序数量">
              <el-input-number v-model="rowForm.num" :min="1" placeholder="请输入程序数量"></el-input-number>
            </el-form-item>
            <el-form-item label="程序文件">
              <upload-component :display-title="false" :displayStar="false" :accept="'*'"
                :file-obj-list="rowForm.attachList" @uploadSuccess="handleUploadSuccess" />
            </el-form-item>
          </el-form>
          <span slot="footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRow">确 定</el-button>
          </span>
        </el-dialog>

        <el-row v-if="type === 1" style="text-align: center; margin-top: 10px">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd"></el-button>
        </el-row> </el-form>
    </e-desc>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onChose">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-reClick>确定</el-button>
    </span>
    <preview-component ref="preview" v-if="previewVisible" @onChose="previewVisible = false" />
    <attach-detail-dialog ref="attachDetail" />
  </div>
</template>

<script>
import EDesc from "../common/e-desc";
import EDescItem from "../common/e-desc-item";
import { getDetail } from "@/api/program";
import uploadComponent from "../common/upload-component";
import AttachDetailDialog from '../common/attach-detail-dialog'
import PreviewComponent from '@/views/modules/common/preview-component'
export default {
  name: "program-add-or-update",
  components: { EDesc, EDescItem, uploadComponent, AttachDetailDialog, PreviewComponent },
  data() {
    return {
      id: 0,
      type: 1,
      dataForm: {
        attachList1: [],
        attachList2: [],
        proTechnologyStepNodeList: [],
        proProgramDetailsList: [],
      },
      // 状态列表数据
      optionsStates: [
        { value: "1", label: "待处理" },
        { value: "2", label: "已处理" },
      ],
      previewVisible: false,
      dataRule: {},
      dialogVisible: false,
      dialogTitle: '',
      rowForm: {
        nodeName: '',
        require: '',
        preTaskTime: 0,
        num: 1,
        attachList: []
      },
      editIndex: -1
    };
  },
  created() { },
  methods: {
    init(id, type) {
      this.type = type;
      this.id = id || 0;
      // this.getMaterialList()
      this.getDetail();
    },
    onChose() {
      this.$emit("onChose");
    },
    getDetail() {
      getDetail(this.id).then(({ data }) => {
        if (data && data.code === "200") {
          this.dataForm = data.data;
          if (!this.dataForm.proProgramDetailsList) {
            this.dataForm.proProgramDetailsList = [];
          }
          if (!this.dataForm.proTechnologyStepNodeList) {
            this.dataForm.proTechnologyStepNodeList = [];
          }
          this.fileList1 = data.data.attachList1 || [];
          this.fileList2 = data.data.attachList2 || [];
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          // 检查proProgramDetailsList是否为空
          if (
            !this.dataForm.proProgramDetailsList ||
            this.dataForm.proProgramDetailsList.length === 0
          ) {
            this.$message.error("编程列表不能为空");
            return;
          }
          // proProgramDetailsList 中附件字段name转为fileName
          if (this.type === 1 && this.dataForm.proProgramDetailsList) {
            this.dataForm.proProgramDetailsList.forEach((item) => {
              item.attachList.forEach((attach) => {
                attach.fileName = attach.name;
              });
            });
          } else if (this.rowForm.attachList) {
            this.rowForm.attachList.forEach((attach) => {
              attach.fileName = attach.name;
            });
          }
          // console.log(this.rowForm)
          // return
          this.$http({
            url: this.type === 1
              ? this.$http.adornUrl(`/biz-service/proProgram/updateProcessing`)
              : this.$http.adornUrl(`/biz-service/proProgram/update`),
            method: "post",
            data: this.type === 1 ? this.$http.adornData({ ...this.dataForm, orgId: this.orgId }) : this.$http.adornData(this.rowForm),
          }).then(({ data }) => {
            if (data && data.code === "200") {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.onChose();
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 编程列表相关方法
    addRow() {
      if (!this.dataForm.proProgramDetailsList) {
        this.dataForm.proProgramDetailsList = [];
      }
      this.dataForm.proProgramDetailsList.push({
        nodeName: "",
        require: "",
        num: 1,
        preTaskTime: 1,
        attachList: [],
      });
    },
    deleteRow(index) {
      this.dataForm.proProgramDetailsList.splice(index, 1);
    },
    uploadProgramSuccess(fileList, index) {
      this.dataForm.proProgramDetailsList[index].attachList = fileList;
    },
    tableRowStyle({ row }) {
      return row.id === this.dataForm.nodeId
        ? { backgroundColor: "#ffcccc" }
        : {};
    },
    handleAdd() {
      this.dialogTitle = '新增编程项目'
      this.editIndex = -1
      this.rowForm = {
        nodeName: '',
        require: '',
        preTaskTime: 1,
        num: 1,
        attachList: []
      }
      this.dialogVisible = true
    },
    handleEdit(row, index) {
      this.dialogTitle = '编辑编程项目'
      this.editIndex = index
      console.log(row)
      this.rowForm = {
        ...row,
        attachList: row.attachList ? row.attachList.map(item => ({
          ...item,
          name: item.fileName,
          id: item.url
        })) : []
      }
      this.dialogVisible = true
    },
    saveRow() {
      if (this.editIndex === -1) {
        this.dataForm.proProgramDetailsList.push({ ...this.rowForm })
      } else {
        this.$set(this.dataForm.proProgramDetailsList, this.editIndex, { ...this.rowForm })
      }
      this.dialogVisible = false
    },
    handleUploadSuccess(fileList) {
      this.rowForm.attachList = fileList
    },
    attachDetails(attachList) {
      // 转换数据结构以匹配组件期望的格式
      const formattedList = attachList.map(item => ({
        fileName: item.fileName || item.name || item.originalName,
        url: item.url || item.path || item.src
      }))
      this.$refs.attachDetail.init(formattedList)
    },
    // 预览
    previewFile(fileName, url) {
      this.previewVisible = true
      this.$nextTick(() => {
        this.$refs.preview.init(fileName, url)
      })
    }
  },
};
</script>

<style></style>
