<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="1060px"
    :visible="visible"
    v-if="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改工艺路线' : '添加工艺路线'"
    @update:visible="updateVisible"
    :maxable="true"
  >
    <header-title title="基本信息"> </header-title>
    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="工艺路线编码:">
            <el-input
              clearable
              disabled
              v-model="form.code"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="工艺路线名称:" prop="name">
            <el-input v-model="form.name" clearable placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属工厂:" prop="factoryId">
            <el-select
              v-model="form.factoryId"
              placeholder="请选择"
              filterable
              :disabled="isUpdate"
            >
              <el-option
                v-for="item in fList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="8">
          <el-form-item label="工艺类型:" prop="produceVersionId">
            <el-select v-model="form.produceVersionId" filterable placeholder="请选择" :style="{ width: '100%' }"
              :disabled="isUpdate">
              <el-option v-for="item in versionList" :key="item.code" :label="item.code + '-' + item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col> -->

        <el-col :span="8">
          <el-form-item label="工艺路线版本:" prop="version">
            <el-input disabled v-model="form.version" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态:" prop="status">
            <el-select v-model="form.status" placeholder="" filterable>
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8" v-if="isUpdate">
          <el-form-item label="版本是否升级:" prop="versionUpgradeType">
            <el-select v-model="form.versionUpgradeType" placeholder="请选择">
              <el-option label="不升级" :value="0" />
              <el-option label="小版本" :value="1" />
              <el-option label="大版本" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="排序:" prop="sort">
            <el-input  v-model="form.sort" type="number" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="类型:" prop="routeType">
            <el-select v-model="form.routeType" placeholder="请选择">
              <el-option label="生产" :value="1" />
              <el-option label="委外" :value="2" />
              <el-option label="质检" :value="3" />
            </el-select>
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>

    <user-taskinstance
      :isEdit="isUpdate"
      ref="taskRef"
      :taskInfo="form"
      @taskList="taskList"
      @remove="remove"
    />

    <template v-slot:footer>
      <el-button type="primary" v-click-once @click="save"> 确定 </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import route from '@/api/technology/route';
  import { pageList } from '@/api/technology/version/version.js';
  import UserTaskinstance from './user-taskinstance.vue';
  export default {
    components: {
      UserTaskinstance
    },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      isUpdate: Boolean,
      // 修改回显的数据
      data: Object,
      isBomRoute: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const defaultForm = {
        code: '',
        name: '',
        factoryId: '',
        status: 1,
        categoryId: '',
        produceVersionId: '',
        version: '1.0',
        id: '',
        // routeType: '',
        versionUpgradeType: 0
      };
      return {
        defaultForm,
        fList: [], //仓库列表

        // 表单数据
        form: { ...defaultForm },

        statusList: [
          { label: '草稿', value: -1 },
          { label: '失效', value: 0 },
          { label: '生效', value: 1 }
        ],

        // 表单验证规则
        rules: {
          name: [
            { required: true, message: '请输入工艺路线名称', trigger: 'blur' }
          ],
          code: [
            { required: true, message: '请输入工艺路线编码', trigger: 'blur' }
          ],
          factoryId: [
            { required: true, message: '请输入工艺路线', trigger: 'blur' }
          ],

          status: [
            { required: true, message: '请输入工艺路线版本', trigger: 'blur' }
          ],
          version: [
            { required: true, message: '请输入工艺路线版本', trigger: 'blur' }
          ],
          produceVersionId: [
            { required: true, message: '请输入工艺类型', trigger: 'blur' }
          ]

          // routeType: [
          //   { required: true, message: '请选择类型', trigger: 'blur' }
          // ]
        },
        versionList: [],
        // 提交状态

        // 是否是修改
        isUpdate: false,

        taskInstanceList: [],
        removeList: []
      };
    },

    mounted() {
      console.log(this.isBomRoute, 'isBomRoute');
      if (this.isBomRoute) {
        this.form.status = 1;
      }
    },

    computed: {
      statusTitle() {
        return this.isUpdate ? '修改' : '保存';
      },
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.$refs.taskRef.getTaskList();
          if (!this.data) {
            delete this.form.id;
          }

          if (this.taskInstanceList.length == 0) {
            this.$message.warning('至少配置一条工序才能保存');
            return;
          }

          const isValid = this.validateFieldUniqueness(
            this.taskInstanceList,
            'orderNum'
          );
          if (!isValid) {
            return;
          }

          let isFalse = this.hasPropertyEqualToSeven(
            this.taskInstanceList,
            'type'
          );
          if (isFalse) {
            let _arr = JSON.parse(JSON.stringify(this.taskInstanceList));
            _arr.sort((a, b) => a.orderNum - b.orderNum);

            if (_arr[0].type != 7) {
              this.$message.warning('有生产准备工序，请将生产准备放在首位');
              return;
            }
          }

          let param = {
            taskInstanceList: this.taskInstanceList,
            routingInfo: this.form,
            removeList: this.removeList
          };

          route
            .taskinstanceSave(param)
            .then((res) => {
              console.log(res, 'msg77777');

              // if (msg) {
              this.$message.success(res.message);
              this.updateVisible(false);
              this.$emit('done', res.data);
              // }
            })
            .finally(() => {});
        });
      },

      hasPropertyEqualToSeven(arr, property) {
        for (let i = 0; i < arr.length; i++) {
          if (
            Object.prototype.hasOwnProperty.call(arr[i], property) &&
            arr[i][property] === 7
          ) {
            return true; // 找到属性等于7的对象
          }
        }
        return false; // 没有找到属性等于7的对象
      },

      validateFieldUniqueness(array, fieldName) {
        const seenValues = new Set();
        for (const item of array) {
          if (!item[fieldName]) {
            this.$message.warning(` 排序不能为空，`);
            return false;
          }
          if (seenValues.has(item[fieldName])) {
            this.$message.warning(`排序不能重复，`);
            return false;
          }
          seenValues.add(item[fieldName]);
        }
        return true;
      },

      async getVersionList() {
        const res = await pageList({
          pageNum: 1,
          size: 100
        });

        this.versionList = res.list;
      },

      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      },

      taskList(list) {
        this.taskInstanceList = list;
      },
      remove(list) {
        this.removeList = list;
      }
    },

    watch: {
      async visible(visible) {
        if (visible) {
          this.getVersionList();
          const res = await route.Flist({
            pageNum: 1,
            size: -1,
            type: 1
          });
          this.fList = res.list;
          if (this.data) {
            const res = await route.getById(this.data.id);
            this.$util.assignObject(this.form, {
              ...res,
              versionUpgradeType: 0
            });
            this.isUpdate = true;
          } else {
            // const res = await route.getCode();
            // this.form.code = res;
            // this.isUpdate = false;
          }

          this.$nextTick(() => {
            this.$refs.taskRef.getList();
          });
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
        }
      },
      isUpdate(v) {
        console.log(v, 66666);
        this.isUpdate = v;
      }
    }
  };
</script>
