<template>
  <ele-modal
    :visible.sync="visible"
    :title="title"
    width="75%"
    append-to-body
    @close="handleCancel"
    :maxable="true"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="90px"
      class="create-form"
    >
      <headerTitle title="基本信息" style="margin-top: 15px"></headerTitle>
      <el-row :gutter="24">
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="编码:" prop="code">
            <el-input v-model="form.code" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="工单名称:" prop="name">
            <el-input v-model="form.name" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="领用部门:" prop="receivingDeptName">
            <el-input v-model="form.receivingDeptName" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="领用人:" prop="recipientName">
            <el-input v-model="form.recipientName" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item
            label="使用时间:"
            prop="usageTime"
            :rules="{
              required: true,
              message: '请选择使用时间',
              trigger: 'change'
            }"
          >
            <el-date-picker
              style="width: 100%"
              v-model="form.usageTime"
              type="date"
              placeholder="选择"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6">
          <el-form-item label="使用部门" prop="useDeptName">
            <el-input v-model="form.useDeptName" />
          </el-form-item>
        </el-col>-->
        <el-col :span="6">
          <el-form-item
            label="使用部门"
            prop="useDeptId"
            :rules="{
              required: true,
              message: '请选择使用部门',
              trigger: 'change'
            }"
          >
            <deptSelect
              v-model="form.useDeptId"
              @changeGroup="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="使用人"
            prop="userId"
            :rules="{
              required: true,
              message: '请选择使用人',
              trigger: 'change'
            }"
          >
            <el-select
              v-model="form.userId"
              size="small"
              style="width: 100%"
              filterable
              @change="changeUser"
            >
              <el-option
                v-for="item in executorList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6">
          <el-form-item label="使用人" prop="userName">
            <el-input v-model="form.userName" />
          </el-form-item>
        </el-col>-->

        <el-col v-bind="styleResponsive ? { lg: 6, md: 24 } : { span: 6 }">
          <el-form-item label="用途:" prop="purpose">
            <el-input v-model="form.purpose" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>

      <headerTitle title="配件信息" style="margin-top: 15px"></headerTitle>

      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="tableList"
        row-key="id"
        height="30vh"
        :needPage="false"
      >
        <template v-slot:toolbar>
          <div class="add-product" @click="addEquipment" v-if="inlet != 1">
            <i class="el-icon-circle-plus-outline"></i>
          </div>
        </template>

        <template v-slot:totalCount="{ row, $index }">
          <el-input
            type="number"
            placeholder="请输入"
            v-model="row.totalCount"
            @input="handleInput(row, $index)"
            min="0"
            :disabled="inlet == 1"
          />
        </template>
        <template v-slot:singlePrice="{ row, $index }">
          <el-input
            type="number"
            placeholder="请输入"
            v-model="row.singlePrice"
            @input="handleInput(row, $index)"
            min="0"
            :disabled="inlet == 1"
          />
        </template>
        <template v-slot:action="{ row }">
          <el-popconfirm
            class="ele-action"
            title="确定要删除吗？"
            @confirm="del(row.id)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete"
                >删除</el-link
              >
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-form>

    <template v-slot:footer v-if="this.inlet != 1">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading"
        >提交</el-button
      >
    </template>
    <process-submit-dialog
      :isNotNeedProcess="false"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
    <AssetsDialog
      ref="selectStockLedgerDialogRef"
      :assetType="6"
      @choose="confirmChoose"
    ></AssetsDialog>
    <!-- <product-list
      ref="productListRef"
      classType="1"
      :is-get-inventory-total="true"
      @choose="confirmChoose"
      :ids="[6]"
      :isFirstRefreshTable="true"
    ></product-list> -->
  </ele-modal>
</template>

<script>
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';

  import {
    saveOrUpdateSalesWorkOrder,
    saveOrUpdateSalesPlan,
  } from '@/api/salesServiceManagement/index';
  import AssetsDialog from './AssetsDialog.vue';
  // import productList from '@/BIZComponents/product-list.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import { getUserPage } from '@/api/system/organization';
  export default {
    components: {
      AssetsDialog,
      deptSelect,
      processSubmitDialog
      // productList
    },
    props: {
      inlet: {
        type: Number,
        default: null
      }
    },
    data() {
      return {
        visible: false,
        loading: false,
        title: '配件申请单',
        processSubmitDialogFlag: false, // 加载状态
        type: '',
        form: {
          code: '',
          name: '',
          receivingDeptName: '',
          recipientName: '',
          usageTime: '',
          useDeptName: '',
          userName: '',
          purpose: '',
          userId: '',
          useDeptId: ''
        },
        rules: {},
        tableList: [],
        columns: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },

          {
            prop: 'categoryCode',
            label: '物品编码',
            align: 'center'
          },
          {
            prop: 'categoryName',
            label: '物品名称',
            align: 'center'
          },

          {
            prop: 'categoryModel',
            label: '型号',
            align: 'center'
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center'
          },
          {
            prop: 'level',
            label: '级别',
            align: 'center'
          },
          {
            prop: 'totalCount',
            label: '数量',
            align: 'center',
            width: 100,
            slot: 'totalCount'
          },
          {
            prop: 'singlePrice',
            label: '单价',
            align: 'center',
            width: 100,
            slot: 'singlePrice'
          },
          {
            prop: 'totalPrice',
            label: '总价',
            align: 'center',
            width: 100
          },
          //   {
          //     prop: 'measureQuantity',
          //     label: '库存',
          //     align: 'center'
          //   },
          {
            prop: 'measureUnit',
            label: '计量单位',
            align: 'center'
          },
          {
            prop: 'warehouseName',
            label: '仓库',
            align: 'center'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 140,
            align: 'center',
            resizable: false,
            fixed: 'right',
            slot: 'action',
            showOverflowTooltip: true,
            show: this.inlet != 1
          }
        ],
        executorList: [], // 使用人列表
        receptionUserId: '' // 领用人id
      };
    },

    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {},
    methods: {
      // 出库数量限制
      handleInput(row, index) {
        // if (row.totalCount > row.measureQuantity) {
        //   this.$set(this.tableList[index], 'totalCount', row.measureQuantity);
        // }
        if (row.singlePrice == 0) {
          this.$set(this.tableList[index], 'totalPrice', 0);
        } else {
          this.$set(
            this.tableList[index],
            'totalPrice',
            Number(row.singlePrice) * Number(row.totalCount)
          );
        }
      },
      // 使用人
      changeUser(e) {
        let data = this.executorList.find((item) => item.id == e);
        this.form.userName = data.name;
      },
      //选择部门(搜索)
      searchDeptNodeClick(info, data,type) {
        if (info) {
          // 根据部门获取人员
          this.form.useDeptName = data.name;
          const params = { groupId: info };
          this.getUserList(params);
          if(type && type == 'init'){
            return;
          }
          this.form.userName = '';
          this.$set(this.form, 'userId', '');
        } else {
          this.form.useDeptId = null;
        }
      },
      // 获取审核人列表、巡点检人员
      async getUserList(params) {
        try {
          let data = { pageNum: 1, size: -1 };
          // 如果传了参数就是获取巡点检人员数据
          if (params) {
            data = Object.assign(data, params);
          }
          const res = await getUserPage(data);
          if (params) {
            this.executorList = res.list;
          }
        } catch (error) {}
      },
      async open(row, type) {
        this.visible = true;
        this.type = type;
        this.getSalesWorkOrderDetail(row);
      },
      async getSalesWorkOrderDetail(row) {
        this.form = row || {};
        this.receptionUserId = row.receptionUserId;
        this.tableList = row.details || [];
        let info = this.$store.state.user?.info;
        this.$set(this.form, 'useDeptId', info.groupId);
        this.searchDeptNodeClick(info.groupId, { name: info.groupName },'init');
      },
      del(id) {
        this.tableList = this.tableList.filter((item) => item.id != id);
      },
      handleCancel() {
        this.tableList = [];
        this.form = {};
        this.visible = false;
        this.executorList = [];
        this.$refs['form'].resetFields();
      },
      async addEquipment() {
        this.$refs.selectStockLedgerDialogRef.open(this.tableList);
      },
      /* 保存编辑 */
      async save() {
        if (this.tableList.length == 0) {
          this.$message.warning('请至少添加一条配件信息');
          return;
        }
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            this.loading = true;
            let requestName =
              this.type == 'work'
                ? saveOrUpdateSalesWorkOrder
                : saveOrUpdateSalesPlan;
            const res = await requestName({
              ...this.form,
              details: this.tableList
            });

            this.loading = false;
            if (!res) return;
            this.processSubmitDialogFlag = true;
            this.$nextTick(() => {
              let params = {
                businessId: res.id,
                businessKey: 'eom_sh_bpbj',
                formCreateUserId: this.receptionUserId,
                variables: {
                  businessCode: res.code,
                  businessName: res.receivingDeptName,
                  businessType: '申请备品备件'
                }
              };
              this.$refs.processSubmitDialogRef.init(params);
            });
            // this.$message({
            //   type: 'success',
            //   message: '提交成功'
            // });
            this.$emit('reload');
            this.handleCancel();
            this.loading = false;
          }
        });
      },
      confirmChoose(data) {
        data.map((item) => {
          item.singlePrice = item.unitPrice;
          delete item.id;
          return {
            ...item
          };
        });
        this.tableList = JSON.parse(JSON.stringify(data));
      }
    }
  };
</script>
<style lang="scss" scoped>
  .basic-details-title {
    margin: 10px 0;
  }

  .title {
    font-size: 16px;
    line-height: 45px;
  }

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