<template>
  <ele-modal
    :visible.sync="visible"
    :title="title"
    width="45vw"
    append-to-body
    @close="cancel"
    :maxable="true"
  >
    <!-- <div class="switch" v-if="type == 'detail'">
      <div class="switch_left">
        <ul>
          <li
            v-for="item in tabOptions"
            :key="item.key"
            :class="{ active: activeComp == item.key }"
            @click="activeComp = item.key"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div> -->
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="create-form"
      v-if="activeComp == 'main'"
    >
      <headerTitle title="基本信息" style="margin-top: 15px"></headerTitle>

      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="类型:" prop="type">
            <DictSelection
              dictName="请托类型"
              v-model="form.type"
              :disabled="type == 'detail'"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="紧急程度:" prop="priority">
            <el-select
              style="width: 100%"
              v-model="form.priority"
              placeholder="请选择"
              clearable
              :disabled="type == 'detail'"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 24 } : { span: 8 }">
          <el-form-item label="编码:" prop="code">
            <el-input v-model="form.code" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 24 } : { span: 8 }">
          <el-form-item label="名称:" prop="name">
            <el-input v-model="form.name" :disabled="type == 'detail'" />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 24 } : { span: 8 }">
          <el-form-item label="生产工单:" prop="workOrderCode">
            <el-input
              v-model="form.workOrderCode"
              placeholder="请选择"
              style="width: 100%"
              clearable
              :disabled="type == 'detail'"
              @click.native="addProduct"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 24 } : { span: 8 }">
          <el-form-item label="工序:" prop="procedureList">
            <el-select
              style="width: 100%"
              v-model="form.procedureList"
              multiple
              placeholder="请选择"
              clearable
              :disabled="type == 'detail'"
            >
              <el-option
                v-for="item in produceTaskList"
                :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="pleaseEntrustDeptName">
            <!-- <deptSelect
              :disabled="type == 'detail'"
              v-model="form.pleaseEntrustDeptId"
              @changeGroup="searchDeptNodeClick"
            /> -->
            <el-input v-model="form.pleaseEntrustDeptName" clearable disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="请托人:" prop="pleaseEntrustUserId">
            <el-input v-model="form.pleaseEntrustUserName" clearable disabled />

            <!-- <el-select
              :disabled="type == 'detail'"
              v-model="form.pleaseEntrustUserId"
              size="small"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="item in executorList"
                :key="item.id"
                :value="item.id"
                @click.native="changeExecutor(item)"
                :label="item.name"
              ></el-option>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 8 } : { span: 8 }">
          <el-form-item label="请托工厂:" prop="factoriesName">
            <el-input v-model="form.factoriesName" style="width: 100%" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="受托工厂:" prop="beEntrustedFactoriesId">
            <el-select
              style="width: 100%"
              v-model="form.beEntrustedFactoriesId"
              placeholder="请选择"
              clearable
              :disabled="type == 'detail'"
            >
              <el-option
                v-for="item in factoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="factoryListChange(item)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="受托部门:" prop="beEntrustedDeptId">
            <deptSelect
              :disabled="type == 'detail'"
              v-model="form.beEntrustedDeptId"
              @changeGroup="beEntrustedDeptIdChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="完成时间:" prop="finishTime">
            <el-date-picker
              style="width: 100%"
              v-model="form.finishTime"
              type="date"
              value-format="yyyy-MM-dd"
              :disabled="type == 'detail'"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      
        <el-col v-bind="styleResponsive ? { lg: 24, md: 24 } : { span: 24 }">
          <el-form-item label="需求描述:">
            <el-input
              v-model="form.describes"
              type="textarea"
              :rows="2"
              :disabled="type == 'detail'"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          s
        </el-col> -->
      </el-row>
      <headerTitle title="产品信息" style="margin-top: 15px"></headerTitle>

      <el-table :data="form.pleaseEntrustObjList" border height="40vh">
        <el-table-column label="序号" align="center" width="60">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column label="产品名称" align="center" prop="productName">
        </el-table-column>
        <el-table-column label="产品编码" align="center" prop="productCode">
        </el-table-column>
        <el-table-column label="牌号" align="center" prop="brandNo">
        </el-table-column>
        <el-table-column label="批次号" align="center" prop="batchNo">
        </el-table-column>
        <!-- <el-table-column label="型号" align="center" prop="model">
        </el-table-column> -->
        <el-table-column label="规格" align="center" prop="specification">
        </el-table-column>
        <el-table-column label="数量" align="center" prop="productNumber">
          <template slot-scope="scope">
            <el-form-item
              label-width="0px"
              :prop="'pleaseEntrustObjList.' + scope.$index + '.productNumber'"
              :rules="[
                {
                  required: true,
                  message: '请输入数量',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                :disabled="type == 'detail'"
                v-model.number="scope.row.productNumber"
                size="small"
                oninput="value=value.replace(/[^\d]/g,'')"
                style="width: 100%"
                placeholder="输入数量"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="完成时间"
          align="center"
          prop="finishTime"
          width="180"
        >
          <template slot-scope="scope">
            <el-form-item
              label-width="0px"
              :prop="'pleaseEntrustObjList.' + scope.$index + '.finishTime'"
              :rules="[
                {
                  required: true,
                  message: '请选择',
                  trigger: 'blur'
                }
              ]"
            >
              <el-date-picker
                :disabled="type == 'detail'"
                style="width: 100%"
                v-model="scope.row.finishTime"
                type="date"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>
      <el-button
        type="primary"
        @click="save"
        :loading="loading"
        v-if="type != 'detail'"
      >
        确定
      </el-button>
    </template>
    <detail
      v-if="activeComp === 'bpm' && form.processInstanceId"
      :id="form.processInstanceId"
    ></detail>

  </ele-modal>
</template>

<script>
import { save } from '@/api/entrust/index';
import detail from '@/views/bpm/processInstance/detail.vue';
import deptSelect from '@/components/CommomSelect/dept-select.vue';
import { getProduceTaskList } from '@/api/aps';
import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';

const defaultForm = function () {
  return {
    createTime: '', //创建时间
    code: '', //编码
    name: '', //名称
    workOrderCode: '', //工单编码
    pleaseEntrustUserId: '', //请托人id
    pleaseEntrustUserName: '', //请托人名称
    pleaseEntrustDeptId: '', //请托人部门id
    pleaseEntrustDeptName: '', //请托人部门名称
    beEntrustedDeptId: '', //受托人部门id
    beEntrustedDeptName: '', //受托人部门名称
    produceRoutingId: null,
    produceRoutingName: '',
    procedureList: [],
    pleaseEntrustObjList: [], //具体请托对象
    type: '', //类型
    status: '',
    describes: '', //描述
    finishTime: '', //完成时间
    processInstanceId: '', //流程实例id
    factoriesName: '',
    factoriesId: '',
    priority: '',
    beEntrustedFactoriesId: '', //受托工厂id
    beEntrustedFactoriesName: '' //受托工厂名称
  };
};
export default {
  components: { detail, deptSelect },
  data() {
    return {
      visible: false,
      loading: false,
      activeComp: 'main',
      options: [
        {
          name: '一般',
          value: 1
        },
        {
          name: '紧急',
          value: 2
        }
      ],
      tabOptions: [
        { key: 'main', name: '异常详情' },
        { key: 'bpm', name: '流程详情' }
      ],
      form: { ...defaultForm() },
      // 表单验证规则
      rules: {
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        name: [{ required: true, message: '请输入', trigger: 'change' }],

        workOrderCode: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        beEntrustedDeptId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        finishTime: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      type: '',
      title: '创建',
      produceTaskList: [],
      factoryList: []
    };
  },

  computed: {
    // 是否开启响应式布局
    styleResponsive() {
      return this.$store.state.theme.styleResponsive;
    }
  },
  created() {
    this.getFactoryList();
  },
  methods: {
    open(type, row) {
      this.visible = true;

      (this.activeComp = 'main'), (this.type = type);
      if (type != 'add') {
        this.form = JSON.parse(JSON.stringify(row));
        this.getProduceTaskList();
        this.form.procedureList = this.form.procedureList.map(
          (item) => item.produceTaskId
        );
        this.form.type = this.form.type + '';
      }
      this.title = type == 'add' ? '新增' : type == 'edit' ? '修改' : '详情';
    },

    addProduct() {
      this.$refs.produceOrderRef.open();
    },

    beEntrustedDeptIdChange(val, row) {
      this.form.beEntrustedDeptName = row.name;
    },
    factoryListChange(row) {
      this.form.beEntrustedFactoriesName = row.name;
    },
    async getFactoryList() {
      const { list } = await warehouseDefinition.getFactoryarea({
        pageNum: 1,
        size: 999,
        type: 1
      });
      this.factoryList = list || [];
    },
    cancel() {
      this.form = { ...defaultForm() };
      this.produceTaskList=[]
      this.visible = false;
    },
    choose(data) {
      this.form.workOrderCode = data.code;
      this.form.produceRoutingId = data.produceRoutingId;
      this.form.produceRoutingName = data.produceRoutingName;
      this.form.pleaseEntrustObjList = [data];
      this.form.procedureList = [];
      this.getProduceTaskList();
    },
    async getProduceTaskList() {
      const res = await getProduceTaskList({
        isDetail: true,
        pageNum: 1,
        routingId: this.form.produceRoutingId,
        size: -1
      });
      console.log(res, 'res');
      this.produceTaskList = res.list;
    },
    /* 保存编辑 */
    save() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }

        // for (let key in this.form) {
        //   if (key.includes('create')) {
        //     this.form[key] = '';
        //   }
        // }
        this.loading = true;
        let data = JSON.parse(JSON.stringify(this.form));
        data.procedureList = data.procedureList.map((item) => {
          return {
            produceTaskId: item,
            produceTaskName: this.produceTaskList.find((val) => val.id == item)
              .name
          };
        });
        // console.log(data);
        // return;
        save(data)
          .then((res) => {
            this.loading = false;
            this.$message.success('成功');
            this.cancel();
            this.$emit('refresh');
          })
          .catch((e) => {
            this.loading = false;
          });
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.basic-details-title {
  margin: 10px 0;
}

.add-product {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 30px;
  color: #1890ff;
  margin: 10px 0;
  cursor: pointer;
}

.create-form .el-form-item {
  margin-bottom: 15px !important;
}
</style>
