<template>
  <ele-modal
    width="75%"
    :append-to-body="true"
    custom-class="ele-dialog-form"
    :title="title"
    :visible.sync="visible"
    :maxable="true"
    @close="handleClose"
  >
    <header-title title="计划基本信息"></header-title>
    <el-form
      ref="addFormRef"
      :model="addForm"
      :rules="addFormRules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="编码" prop="code">
            <el-input
              v-model="addForm.code"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
            <!-- :disabled="type == 'view'" -->
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="名称"
            prop="name"
            :rules="{
              required: true,
              message: '请输入名称',
              trigger: 'change'
            }"
          >
            <el-input
              v-model="addForm.name"
              size="small"
              placeholder="请输入"
              :disabled="type == 'view'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="自动派单" prop="isSyncBill">
            <el-select
              v-model="addForm.isSyncBill"
              size="small"
              style="width: 100%"
              :disabled="type == 'view'"
            >
              <el-option :value="1" label="是"></el-option>
              <el-option :value="0" label="否"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="预计售后时长" prop="duration">
            <div style="display: flex">
              <el-input
                type="number"
                v-model="addForm.duration"
                size="small"
                placeholder="请输入"
                @input="formDataDurationTime"
                :disabled="type == 'view'"
              >
                <template #suffix>
                  <el-select
                    v-model="addForm.durationUnit"
                    size="small"
                    style="width: 120px"
                    :disabled="type == 'view'"
                  >
                    <el-option :value="'1'" label="分钟"></el-option>
                    <el-option :value="'2'" label="小时"></el-option>
                    <el-option :value="'3'" label="天"></el-option>
                  </el-select>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item
            label="部门"
            prop="executeGroupId"
            :rules="{
              required: true,
              message: '请选择部门',
              trigger: 'change'
            }"
          >
            <deptSelect
              v-model="addForm.executeGroupId"
              @changeGroup="searchDeptNodeClick"
              :disabled="type == 'view' && !isDispatch"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="工单执行人"
            prop="executeUserId"
            :rules="{
              required: true,
              message: '请选择工单执行人',
              trigger: 'change'
            }"
          >
            <el-select
              v-model="addForm.executeUserId"
              size="small"
              style="width: 100%"
              filterable
              @change="changeUser"
              :disabled="type == 'view' && !isDispatch"
            >
              <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="urgent">
            <DictSelection
              dictName="紧急程度"
              clearable
              v-model="addForm.urgent"
              :disabled="type == 'view'"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              resize="none"
              v-model="addForm.remark"
              :rows="2"
              placeholder="请详细说明"
              size="small"
              :disabled="type == 'view'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- ***改 -->
    <div class="ele-body-custom">
      <el-tabs v-model="activeName" style="width: 100%" type="border-card">
        <el-tab-pane label="需求信息" name="需求信息">
          <info
            ref="infoRef"
            v-if="operationalState"
            type="view"
            :isPurchaseNeed="false"
          ></info>
          <info
            ref="infoRef"
            v-else
            source="售后计划"
            type="view"
            state="可操作"
            :isPurchaseNeed="false"
          ></info>
        </el-tab-pane>
        <el-tab-pane label="方案" name="方案">
          <!-- :type="type" -->
          <spareParts
            obtain="仓库"
            ref="sparePartsRef"
            :type="title == '详情' ? 'view' : 'edit'"
          ></spareParts>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template v-slot:footer>
      <el-button @click="handleClose" :loading="loading">取消</el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="save('')"
        v-if="type != 'view'"
        >保存</el-button
      >
      <el-button
        type="primary"
        :loading="loading"
        @click="save('派单')"
        v-if="type == 'edit'"
        >派单</el-button
      >
      <el-button
        type="primary"
        :loading="loading"
        @click="save('')"
        v-if="isDispatch"
        >派单</el-button
      >
    </template>
  </ele-modal>
</template>

<script>
  import {
    getSalesPlanById,
    updateSalesPlan,
    dispatchOrders
  } from '@/api/salesServiceManagement/index';
  import { contactDetail } from '@/api/saleManage/contact';
  import { getUserPage } from '@/api/system/organization';

  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  // import fileMain from '@/components/addDoc/index.vue';
  import spareParts from '@/views/salesServiceManagement/components/sparePartsList.vue';
  import info from '@/views/salesServiceManagement/components/info.vue';
  import { getCurrentUser } from '@/utils/token-util';
  import { mapGetters } from 'vuex';
  let def = {
    name: '',
    isSyncBill: 1,
    duration: null,
    executeGroupId: '',
    executeGroupName: '',
    executeUserId: '',
    executeUserName: '',
    urgent: null,
    remark: '',
    durationUnit: '2'
  };
  export default {
    components: {
      deptSelect,
      // fileMain,
      spareParts,
      info
    },

    props: {},
    data() {
      return {
        activeName: '需求信息',
        addForm: {
          ...def
        },
        executorList: [], // 业务人员列表
        // 表单验证规则
        addFormRules: {},
        visible: false,

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

        // 提交状态
        loading: false,
        type: 'add',
        title: '',
        isDispatch: false,
        detailList: []
      };
    },

    computed: {
      ...mapGetters(['getDictValue']),
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      },
      // 需求信息操作状态
      operationalState() {
        if (this.title == '派单') {
          return false;
        }
        let flag = this.type == 'view';
        return flag;
      },
      // 部门下拉
      loginChangeGroupVOList() {
        return this.$store.state.user?.info?.loginChangeGroupVOList;
      }
    },
    watch: {},
    methods: {
      handleClose() {
        this.addForm = { ...def };
        this.visible = false;
        this.$refs.addFormRef.resetFields();
      },
      // 默认部门
      departmentAss() {
        let currentUser = getCurrentUser();
        if (
          this.loginChangeGroupVOList &&
          this.loginChangeGroupVOList.length > 0
        ) {
          let obj = this.loginChangeGroupVOList.find(
            (el) => el.groupId == currentUser.currentGroupId
          );
          this.addForm.executeGroupId = currentUser.currentGroupId || '';
          this.searchDeptNodeClick(currentUser.currentGroupId, {
            name: obj.groupName
          });
        }
      },
      // 初始化
      async init(row, type, isDispatch) {
        this.type = type;
        this.title = isDispatch ? '派单' : type == 'view' ? '详情' : '修改';
        this.isDispatch = isDispatch;
        if (row) {
          this.visible = true;
          this.getInfo(row.id);
          if (row.executeGroupId) {
            this.getUserList({ groupId: row.executeGroupId });
          }
        } else {
        }
      },

      formDataDurationTime(value) {
        if (value > 0) {
          this.addForm.duration = value.replace(/^[0]+/, '');
        } else {
          this.addForm.duration = 0;
        }
      },
      //选择部门(搜索)
      searchDeptNodeClick(info, data) {
        if (info) {
          // 根据部门获取人员
          this.addForm.executeGroupName = data.name;
          const params = { groupId: info };
          this.getUserList(params);
        } else {
          this.addForm.executeGroupId = 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) {}
      },
      changeUser(val) {
        this.executorList.map((item) => {
          if (item.id == val) {
            this.addForm.executeUserName = item.name;
          }
        });
      },
      async save(paramName) {
        try {
          let valid = await this.$refs.infoRef.getValidate();
          let data = this.$refs.infoRef.getValue();
          await this.$refs.sparePartsRef.getValidate();
          this.addForm.costListVOS = this.$refs.sparePartsRef.getTableValue();
          this.$refs.addFormRef.validate(async (valid, obj) => {
            if (obj) {
              let messages = Object.keys(obj).map((key) => obj[key][0]);
              if (messages.length > 0) {
                this.$message.warning(messages[0].message);
              }
            }
            if (valid) {
              let requestName = this.isDispatch
                ? dispatchOrders
                : updateSalesPlan;
              // *** 修改的时候也可以直接派单
              if (paramName) {
                requestName = dispatchOrders;
              }
              // *** 新增参数
              let obj = this.infoData(data);
              this.addForm.salesDemandUpdatePO = obj;
              this.loading = true;
              const res = await requestName(this.addForm);
              this.loading = false;
              if (!res) return;
              this.$message.success('操作成功');
              this.visible = false;
              this.$emit('reload');
            }
          });
        } catch (error) {
          this.loading = false;
        }
      },
      // *** 需求信息参数
      infoData(data) {
        let obj = JSON.parse(JSON.stringify(data));
        obj.productDetail = obj.tableList;
        delete obj.tableList;
        obj.id = this.addForm.afterSalesDemandVO.id;
        obj.productDetail.map((el) => delete el.produceTime);
        return obj;
      },
      async getInfo(id) {
        const res = await getSalesPlanById(id);
        if (!res) return;
        this.addForm = res;
        // 不存在部门就调用
        if (!res.executeGroupId) {
          this.departmentAss();
        }
        // 默认赋值 时间单位
        this.addForm.durationUnit = this.addForm.durationUnit
          ? this.addForm.durationUnit
          : '2';
        this.$nextTick(() => {
          this.$refs.infoRef.init(res.afterSalesDemandVO);
          this.$refs.sparePartsRef.setTableValue(res?.costListVOS || []);
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .marginBto {
    margin-bottom: 10px;

    span {
      margin-left: 50px;
    }

    .name {
      font-weight: 800;
      color: #40a9ff;
    }
  }
  :deep(.el-input__suffix .el-input__inner) {
    border: none;
    background: none;
  }

  .ele-body-custom {
    :deep(.divider) {
      display: none;
    }
  }
</style>
