<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :append-to-body="false"
    :close-on-click-modal="false"
    width="60%"
    :before-close="cancel"
    :maxable="true"
    :resizable="true"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="el-form-box"
      :disabled="title == '详情'"
    >
      <headerTitle title="产品信息"> </headerTitle>
      <el-row>
        <el-col :span="12">
          <el-form-item label="编码" prop="code">
            <el-input
              clearable
              readonly
              v-model="form.code"
              @click.native="$refs.produceRef.open()"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input clearable disabled v-model="form.name" placeholder=" " />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工厂名称:" prop="factoriesId">
            <el-select
              style="width: 100%"
              clearable
              v-model="form.factoriesId"
              placeholder="请选择所属工厂"
            >
              <el-option
                v-for="item in factoryList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
                @click.native="change_factoryId(item)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <headerTitle title="产线节拍"> </headerTitle>
      <ele-pro-table
        :columns="columns"
        :datasource="form.list"
        ref="table"
        height="400px"
        full-height="calc(100vh - 116px)"
        :needPage="false"
        :selection.sync="selection"
      >
        <template v-slot:toolbar v-if="title != '详情'">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="handParent()"
          >
            新增
          </el-button>
          <el-popconfirm
            class="ele-action"
            title="确定要删除选中的信息吗？"
            @confirm="remove()"
          >
            <template v-slot:reference>
              <el-button
                type="danger"
                :underline="false"
                icon="el-icon-delete"
                :disabled="selection?.length === 0"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
        <template v-slot:taktTime="{ row, $index }">
          <el-form-item
            label-width="0"
            :prop="'list.' + $index + '.taktTime'"
            :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
          >
            <el-input
              clearable
              v-model.number="row.taktTime"
              placeholder="请输入"
            />
          </el-form-item>
        </template>
        <template v-slot:priority="{ row, $index }">
          <el-form-item
            label-width="0"
            :prop="'list.' + $index + '.priority'"
            :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
          >
            <el-input
              clearable
              v-model.number="row.priority"
              placeholder="请输入"
            />
          </el-form-item>
        </template>
        <template v-slot:productionLineId="{ row, $index }">
          <el-form-item
            label-width="0"
            :prop="'list.' + $index + '.productionLineId'"
            :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
          >
            <el-select
              style="width: 100%"
              clearable
              v-model="row.productionLineId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in productionLineList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
                @click.native="change_productionLineId(item, $index)"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-slot:remark="{ row }">
          <el-input clearable v-model="row.remark" placeholder="请输入" />
        </template>
        <template v-slot:columnRequired="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
      </ele-pro-table>
    </el-form>
    <div slot="footer">
      <el-button
        type="primary"
        @click="save()"
        v-lodading="loading"
        v-if="title != '详情'"
        >保存</el-button
      >

      <el-button @click="cancel">返回</el-button>
    </div>
    <ProductModal
      ref="produceRef"
      @changeParent="produceConfirm"
    ></ProductModal>
  </ele-modal>
</template>
<script>
  const defForm = {
    code: '', //编码
    name: '', //名称
    productId: '', //物品id
    factoriesId: '', //工厂id
    factoriesName: '', //工厂名称
    list: [] //表格数据
  };
  import {
    getFactoryarea,
    listFactoryLineByFactoryId
  } from '@/api/factoryModel';

  import ProductModal from '@/components/productList/product-list.vue';
  import {
    saveOrUpdate,
    getById
  } from '@/api/productionScheduling/productionLineBeat';

  export default {
    components: { ProductModal },
    computed: {},
    data() {
      return {
        lodading: false,
        title: '',
        addOrEditDialogFlag: false,
        form: { ...defForm },
        rules: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'change' }
          ],
          factoriesId: [
            { required: true, message: '请选择工厂', trigger: 'change' }
          ],
          code: [{ required: true, message: '编码不能为空', trigger: 'change' }]
        },
        factoryList: [],
        selection: [],
        productionLineList: [],
        columns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            fixed: 'left',
            align: 'center'
          },
          {
            width: 60,
            type: 'index',
            columnKey: 'index',
            label: '序号',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'productionLineName',
            slot: 'productionLineId',
            headerSlot: 'columnRequired',
            label: '产线名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            prop: 'taktTime',
            slot: 'taktTime',
            headerSlot: 'columnRequired',
            label: '产线节拍(分钟)',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            prop: 'priority',
            slot: 'priority',
            headerSlot: 'columnRequired',
            label: '优先顺序',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },
          {
            prop: 'remark',
            slot: 'remark',
            label: '备注',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 200
          }
        ],
        loading: false
      };
    },
    mounted() {},
    created() {
      this.getFactoryList();
    },

    methods: {
      //初始化
      async open(row = {}, type) {
        this.addOrEditDialogFlag = true;
        this.title = type == 'add' ? '新增' : type == 'edit' ? '修改' : '详情';

        if (type !== 'add') {
          this.form = await getById(row.id);
          this.form.list.forEach((item, index) => {
            item.key = index;
          });
          if (this.form.factoriesId) {
            this.change_factoryId({ id: this.form.factoriesId });
          }
        }
      },
      handParent() {
        this.form.list.push({
          productionLineName: '',
          productionLineId: '',
          taktTime: '',
          remark: '',
          key: this.form.list?.length || 0
        });
      },
      async getFactoryList() {
        const { list } = await getFactoryarea({
          pageNum: 1,
          size: 999,
          type: 1,
          enable: 1
        });
        this.factoryList = list || [];
      },
      /* 获取产线 */

      async change_factoryId(item) {
        this.productionLineList = await listFactoryLineByFactoryId([
          this.form.factoriesId
        ]);
        this.form.factoriesName = item.name;
      },
      change_productionLineId(item, index) {
        this.$set(this.form.list[index], 'productionLineName', item.name);
      },
      produceConfirm(data) {
        this.form.name = data[0].name;
        this.form.code = data[0].code;
        this.form.productId = data[0].id;
        this.form.brandNo = data[0].brandNum;
        this.form.modelType = data[0].modelType;
        this.form.specification = data[0].specification;
      },
      remove() {
        let keys = this.selection.map((item) => item.key);
        this.form.list = this.form.list.filter(
          (item) => !keys.includes(item.key)
        );

        this.selection = [];
      },

      save() {
        this.$refs.form.validate((valid) => {
          if (!this.form.list?.length) {
            this.$message.error('节拍信息不能为空');
            return;
          }
          if (valid) {
            let priorityList = this.form.list.map((item) => item.priority);

            if (new Set(priorityList).size !== priorityList.length) {
              this.$message.error('优先顺序不能重复');
              return;
            }
            this.loading = true;
            saveOrUpdate(this.form)
              .then((res) => {
                this.$message.success('操作成功');
                this.cancel();
                this.$emit('done');
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },

      //关闭弹窗
      cancel() {
        this.addOrEditDialogFlag = false;
        this.form = {
          ...defForm
        };
        this.form.list = [];
      }
    }
  };
</script>
<style scoped lang="scss">
  // :deep(.el-form-item--medium) {
  //   display: none;
  // }
</style>
