<template>
  <el-form
    ref="form"
    :model="form"
    :rules="rules"
    label-width="100px"
    class="create-form"
  >
    <headerTitle
      title="基本信息"
      style="margin-top: 8px"
      v-if="isPurchaseNeed"
    ></headerTitle>
    <headerTitle
      title="需求信息"
      style="margin-top: 8px"
      v-if="!isPurchaseNeed"
    ></headerTitle>
    <el-row :gutter="24" v-if="source != '报工信息'">
      <el-col :span="6">
        <el-form-item label="需求编码:">
          <el-input v-model="form.code" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item
          label="关联类型:"
          prop="associationType"
          :rules="{
            required: true,
            message: '请选择关联类型',
            trigger: 'change'
          }"
        >
          <el-select
            style="width: 100%"
            v-model="form.associationType"
            placeholder="请选择"
            :disabled="type == 'view'"
            @change="selectType"
          >
            <el-option
              v-for="item in associationTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item
          label="需求名称:"
          prop="name"
          :rules="{
            required: true,
            message: '请选择/填写需求名称',
            trigger: 'blur'
          }"
        >
          <el-select
            style="width: 100%"
            :disabled="type == 'view'"
            v-model="form.name"
            filterable
            allow-create
            default-first-option
            placeholder="请选择需求名称"
          >
            <el-option
              v-for="item in demandList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item
          label="客户名称:"
          prop="contractInfo.contactName"
          :rules="{
            required: true,
            message: '请选择客户',
            trigger: 'change'
          }"
        >
          <el-input
            v-model="form.contractInfo.contactName"
            readonly
            @click.native="handHead"
            placeholder="请选择"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6" v-if="form.associationType == '1'">
        <el-form-item
          label="发货单:"
          prop="orderCode"
          :rules="{
            required: true,
            message: '请选择发货单',
            trigger: 'change'
          }"
        >
          <el-input
            v-model="form.orderCode"
            readonly
            :disabled="type == 'view'"
            @click.native="invoiceDialogOpen"
            placeholder="请选择"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6" v-if="form.associationType == '2'">
        <el-form-item
          label="销售订单:"
          prop="orderCode"
          :rules="{
            required: true,
            message: '请选择销售订单',
            trigger: 'change'
          }"
        >
          <el-input
            v-model="form.orderCode"
            readonly
            :disabled="type == 'view'"
            @click.native="saleorderDialogOpen"
            placeholder="请选择"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6" v-if="form.associationType == '3'">
        <el-form-item label="产品:">
          <el-input
            v-model="form.orderCode"
            readonly
            :disabled="type == 'view'"
            @click.native="customersDialogOpen"
            placeholder="请选择"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="客户编码:" prop="code">
          <el-input
            v-model="form.contractInfo.code"
            readonly
            :disabled="type == 'view'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="客户代号:" prop="serialNo">
          <el-input
            v-model="form.contractInfo.serialNo"
            readonly
            :disabled="type == 'view'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="业务员:" prop="salesmanName">
          <el-input
            v-model="form.contractInfo.salesmanName"
            readonly
            :disabled="type == 'view'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item
          label="报修地址:"
          prop="contactAddress"
          :rules="{
            required: true,
            message: '请填写报修地址',
            trigger: 'change'
          }"
        >
          <el-input
            :disabled="type == 'view'"
            v-model="form.contactAddress"
            :readonly="type == 'view'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="故障等级:" prop="faultLevel">
          <DictSelection
            dictName="故障等级"
            :disabled="type == 'view'"
            clearable
            v-model="form.faultLevel"
          ></DictSelection>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="期望解决时间:" prop="expectedTime">
          <el-date-picker
            :disabled="type == 'view'"
            style="width: 100%"
            v-model="form.expectedTime"
            type="date"
            :picker-options="pickerOptions"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>
    <div class="after_sales_target" v-if="salesShow">
      <headerTitle
        title="售后对象"
        style="margin-top: 10px"
        v-if="isPurchaseNeed"
      ></headerTitle>
      <ele-pro-table
        ref="tableRef3"
        :columns="columnsDetail"
        :datasource="form.tableList"
        :need-page="false"
        :toolbar="false"
        maxHeight="300px"
        row-key="id"
        default-expand-all
      >
        <template v-slot:measureQuantity="{ row }">
          <el-input
            @input="totalCountChange(row, 'measureQuantity')"
            v-model="row.measureQuantity"
            type="number"
            :min="1"
            placeholder="请输入"
            :disabled="!tableOperate"
          ></el-input>
        </template>
        <template v-slot:batchNo="{ row }">
          <el-input
            v-model="row.batchNo"
            placeholder="请输入"
            :disabled="!tableOperate"
          ></el-input>
        </template>
        <template v-slot:barcodes="{ row }">
          <el-input
            v-model="row.barcodes"
            placeholder="请输入"
            :disabled="!tableOperate"
          ></el-input>
        </template>
        <template v-slot:shipmentDate="{ row }">
          <el-date-picker
            v-model="row.shipmentDate"
            type="datetime"
            placeholder="选择结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </template>
        <template v-slot:expand="{ row, $index }">
          <div
            style="
              width: calc(100% - 55px);
              min-height: 60px;
              margin-left: 55px;
            "
            v-if="row.faultDetails && row.faultDetails.length > 0"
          >
            <ele-pro-table
              :columns="faultList"
              :datasource="row.faultDetails || []"
              :need-page="false"
              maxHeight="300px"
              class="el-form-box"
              :toolkit="[]"
            >
              <template v-slot:type="{ row, $index: idx }">
                <el-form-item
                  :prop="`tableList.${$index}.faultDetails.${idx}.type`"
                  :rules="{
                    required: true,
                    message: '请选择故障类型',
                    trigger: 'change'
                  }"
                >
                  <el-select
                    v-model="row.type"
                    :disabled="change_permission"
                    :placeholder="`请选择`"
                  >
                    <el-option
                      v-for="item in typeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </template>
              <template v-slot:faultPhenomenon="{ row, $index: idx }">
                <el-form-item
                  :prop="`tableList.${$index}.faultDetails.${idx}.faultPhenomenon`"
                  :rules="{
                    required: true,
                    message: '请输入故障现象',
                    trigger: 'change'
                  }"
                >
                  <el-input
                    v-model="row.faultPhenomenon"
                    placeholder="请输入"
                    :disabled="change_permission"
                  ></el-input>
                </el-form-item>
              </template>
              <template
                v-slot:faultReason="{ row, $index: idx }"
                v-if="source == '报工信息'"
              >
                <el-form-item
                  :prop="`tableList.${$index}.faultDetails.${idx}.faultReason`"
                  :rules="{
                    required: true,
                    message: '请输入故障原因',
                    trigger: 'change'
                  }"
                >
                  <el-input
                    v-model="row.faultReason"
                    placeholder="请输入"
                    :disabled="change_permission"
                  ></el-input>
                </el-form-item>
              </template>
              <template v-slot:faultReason="{ row }" v-else>
                <el-input
                  v-model="row.faultReason"
                  placeholder="请输入"
                  :disabled="change_permission"
                ></el-input>
              </template>
              <template
                v-slot:maintenanceProcess="{ row, $index: idx }"
                v-if="source == '报工信息'"
              >
                <el-form-item
                  :prop="`tableList.${$index}.faultDetails.${idx}.maintenanceProcess`"
                  :rules="{
                    required: true,
                    message: '请输入维修过程',
                    trigger: 'change'
                  }"
                >
                  <el-input
                    v-model="row.maintenanceProcess"
                    placeholder="请输入"
                    :disabled="change_permission"
                  ></el-input>
                </el-form-item>
              </template>
              <template v-slot:maintenanceProcess="{ row }" v-else>
                <el-input
                  v-model="row.maintenanceProcess"
                  placeholder="请输入"
                  :disabled="change_permission"
                ></el-input>
              </template>
              <template v-slot:attachments="{ row }">
                <fileMain v-model="row.attachments" :type="fileStr"></fileMain>
              </template>
              <template v-slot:imageUrl="{ row }">
                <el-button type="primary" plain @click="seeImage(row)"
                  >拍照列表({{ imageUrleng(row) }})</el-button
                >
              </template>
              <template v-slot:action="{ row: data, $index }">
                <el-popconfirm
                  class="ele-action"
                  title="确定要删除当前故障吗？"
                  @confirm="delSon(row, $index)"
                >
                  <template v-slot:reference>
                    <el-link
                      type="danger"
                      v-if="faultOperate(data)"
                      :underline="false"
                      icon="el-icon-delete"
                      >删除</el-link
                    >
                  </template>
                </el-popconfirm>
              </template>

              <template v-slot:headerType="{ column }">
                <span class="is-required">{{ column.label }}</span>
              </template>
              <template v-slot:headerPhenomenon="{ column }">
                <span class="is-required">{{ column.label }}</span>
              </template>
              <template
                v-slot:headerMaintenance="{ column }"
                v-if="source == '报工信息'"
              >
                <span class="is-required">{{ column.label }}</span>
              </template>
              <template
                v-slot:headerFaultReason="{ column }"
                v-if="source == '报工信息'"
              >
                <span class="is-required">{{ column.label }}</span>
              </template>
            </ele-pro-table>
          </div>
        </template>
        <template v-slot:useLocation="{ row, $index }">
          <el-form-item :prop="`tableList.${$index}.useLocation`">
            <el-input
              v-model="row.useLocation"
              :disabled="type == 'view'"
            ></el-input>
          </el-form-item>
        </template>
        <template v-slot:action="{ row, $index }">
          <el-link
            type="primary"
            :underline="false"
            v-if="tableOperate"
            @click="addProblem(row)"
            >添加故障</el-link
          >
          <el-link
            type="danger"
            :underline="false"
            icon="el-icon-delete"
            v-if="type != 'view'"
            @click="del(row, $index)"
            >删除</el-link
          >
        </template>
      </ele-pro-table>
    </div>
    <div class="fault_infor" v-else>
      <headerTitle title="故障信息" style="margin-top: 10px"></headerTitle>

      <ele-pro-table
        :columns="faultList"
        :datasource="form.faultDetailList"
        :need-page="false"
        maxHeight="300px"
        class="el-form-box"
        :toolkit="[]"
      >
        <template v-slot:toolbar>
          <el-button type="primary" v-if="tableOperate" @click="addFaults"
            >添加故障</el-button
          >
        </template>
        <template v-slot:type="{ row, $index: idx }">
          <el-form-item
            :prop="`faultDetailList.${idx}.type`"
            :rules="{
              required: true,
              message: '请选择故障类型',
              trigger: 'change'
            }"
          >
            <el-select
              v-model="row.type"
              :disabled="change_permission"
              :placeholder="`请选择`"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-slot:faultPhenomenon="{ row, $index: idx }">
          <el-form-item
            :prop="`faultDetailList.${idx}.faultPhenomenon`"
            :rules="{
              required: true,
              message: '请输入故障现象',
              trigger: 'change'
            }"
          >
            <el-input
              v-model="row.faultPhenomenon"
              placeholder="请输入"
              :disabled="change_permission"
            ></el-input>
          </el-form-item>
        </template>
        <template
          v-slot:faultReason="{ row, $index: idx }"
          v-if="source == '报工信息'"
        >
          <el-form-item
            :prop="`faultDetailList.${idx}.faultReason`"
            :rules="{
              required: true,
              message: '请输入故障原因',
              trigger: 'change'
            }"
          >
            <el-input
              v-model="row.faultReason"
              placeholder="请输入"
              :disabled="change_permission"
            ></el-input>
          </el-form-item>
        </template>
        <template v-slot:faultReason="{ row }" v-else>
          <el-input
            v-model="row.faultReason"
            placeholder="请输入"
            :disabled="change_permission"
          ></el-input>
        </template>
        <template
          v-slot:maintenanceProcess="{ row, $index: idx }"
          v-if="source == '报工信息'"
        >
          <el-form-item
            :prop="`faultDetailList.${idx}.maintenanceProcess`"
            :rules="{
              required: true,
              message: '请输入维修过程',
              trigger: 'change'
            }"
          >
            <el-input
              v-model="row.maintenanceProcess"
              placeholder="请输入"
              :disabled="change_permission"
            ></el-input>
          </el-form-item>
        </template>
        <template v-slot:maintenanceProcess="{ row }" v-else>
          <el-input
            v-model="row.maintenanceProcess"
            placeholder="请输入"
            :disabled="change_permission"
          ></el-input>
        </template>
        <template v-slot:attachments="{ row }">
          <fileMain v-model="row.attachments" :type="fileStr"></fileMain>
        </template>
        <template v-slot:imageUrl="{ row }">
          <el-button type="primary" plain @click="seeImage(row)"
            >拍照列表({{ imageUrleng(row) }})</el-button
          >
        </template>
        <template v-slot:action="{ row: data, $index }">
          <el-popconfirm
            class="ele-action"
            title="确定要删除当前故障吗？"
            @confirm="faultDel($index)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete"
                >删除</el-link
              >
            </template>
          </el-popconfirm>
        </template>

        <template v-slot:headerType="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
        <template v-slot:headerPhenomenon="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
        <template
          v-slot:headerMaintenance="{ column }"
          v-if="source == '报工信息'"
        >
          <span class="is-required">{{ column.label }}</span>
        </template>
        <template
          v-slot:headerFaultReason="{ column }"
          v-if="source == '报工信息'"
        >
          <span class="is-required">{{ column.label }}</span>
        </template>
      </ele-pro-table>
    </div>
    <headerTitle
      title="联系人信息"
      style="margin-top: 10px"
      v-if="isPurchaseNeed"
    ></headerTitle>
    <ele-pro-table
      :style="{ marginTop: isPurchaseNeed ? 0 : '10px' }"
      ref="table"
      :columns="bankColumns"
      :datasource="form.contactInfoVOS"
      :toolkit="[]"
      class="el-form-box"
      :need-page="false"
      @selection-change="handleSelectionChange"
      v-if="source != '报工信息'"
    >
      <!-- 表头工具栏 -->
      <template v-slot:toolbar>
        <el-button type="primary" v-if="tableOperate" @click="addBank"
          >添加</el-button
        >
        <el-button type="danger" v-if="type != 'view'" @click="delContact"
          >删除</el-button
        >
        <span class="reserve" v-if="type != 'view'"
          >请至少留一条联系人数据</span
        >
      </template>
      <template v-slot:headerContactName="{ column }">
        <span class="is-required">{{ column.label }}</span>
      </template>
      <template v-slot:action="{ row, $index }">
        <!-- v-if="type != 'view'" -->
        <el-link
          type="danger"
          :underline="false"
          icon="el-icon-delete"
          v-if="faultOperate(row)"
          @click="handleBankDel(row, $index)"
          >删除</el-link
        >
      </template>

      <template v-slot:contactName="{ row, $index }">
        <el-form-item
          :prop="`contactInfoVOS.${$index}.contactName`"
          :rules="{
            required: true,
            message: '请输入联系人名称',
            trigger: 'change'
          }"
        >
          <el-input
            v-model="row.contactName"
            placeholder="请输入"
            :disabled="change_permission"
            maxlength="50"
          ></el-input>
        </el-form-item>
      </template>
      <template v-slot:contactPhone="{ row }">
        <el-input
          v-model="row.contactPhone"
          placeholder="请输入"
          :disabled="change_permission"
        ></el-input>
      </template>
      <template v-slot:post="{ row }">
        <el-input
          v-model="row.post"
          placeholder="请输入"
          :disabled="change_permission"
        ></el-input>
      </template>
      <template v-slot:telephone="{ row }">
        <el-input
          v-model="row.telephone"
          placeholder="请输入"
          :disabled="change_permission"
        ></el-input>
      </template>
      <template v-slot:email="{ row }">
        <el-input
          v-model="row.email"
          placeholder="请输入"
          :disabled="change_permission"
        ></el-input>
      </template>
      <template v-slot:wechat="{ row }">
        <el-input
          v-model="row.wechat"
          placeholder="请输入"
          :disabled="change_permission"
        ></el-input>
      </template>
      <template v-slot:deptName="{ row }">
        <el-input
          v-model="row.deptName"
          placeholder="请输入"
          :disabled="change_permission"
        ></el-input>
      </template>
      <template v-slot:remark="{ row }">
        <el-input
          v-model="row.remark"
          placeholder="请输入"
          :disabled="change_permission"
        ></el-input>
      </template>
    </ele-pro-table>
    <PhotoList
      v-if="phoneVisible"
      :phoneVisible="phoneVisible"
      :imagesList="phoneList"
      @closePhone="closePhone"
    />
    <parentList ref="parentRef" @changeParent="changeParent"></parentList>
    <invoiceDialog
      ref="invoiceDialogRef"
      @changeParent="invoiceChange"
    ></invoiceDialog>
    <SaleorderDialog ref="saleorderDialogRef" @changeParent="saleorderChange" />
    <ProductDialog ref="productDialogRef" @changeParent="productChange" />
  </el-form>
</template>

<script>
  import fileMain from '@/components/addDoc/index.vue';
  import dictMixins from '@/mixins/dictMixins';
  import PhotoList from './photoList.vue';
  import { mapGetters } from 'vuex';
  import { contactDetail } from '@/api/saleManage/contact';
  import parentList from '@/views/saleManage/contact/components/parentList.vue';
  import invoiceDialog from './invoiceDialog.vue';
  import SaleorderDialog from './saleorderDialog.vue';
  import ProductDialog from './productDialog.vue';
  export default {
    mixins: [dictMixins],
    components: {
      parentList,
      invoiceDialog,
      PhotoList,
      SaleorderDialog,
      fileMain,
      ProductDialog
    },
    computed: {
      ...mapGetters(['getDictValue']),
      salesShow() {
        if (this.form.associationType == '1') {
          return true;
        }
        if (this.form.tableList.length > 0) {
          return true;
        }
        if (this.form.associationType == '2' && this.isOrder == false) {
          return true;
        }
        return false;
      },
      bankColumns() {
        return [
          {
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center'
          },
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            show: this.type != 'view'
          },
          {
            label: '姓名',
            prop: 'contactName',
            slot: 'contactName',
            headerSlot: 'headerContactName',
            align: 'center'
          },
          {
            label: '手机',
            prop: 'contactPhone',
            slot: 'contactPhone',
            align: 'center'
          },
          {
            label: '电话',
            prop: 'telephone',
            slot: 'telephone',
            align: 'center'
          },

          {
            label: '微信号',
            prop: 'wechat',
            slot: 'wechat',
            align: 'center'
          },
          {
            label: '邮箱',
            prop: 'email',
            slot: 'email',
            align: 'center'
          },
          {
            label: '部门',
            prop: 'deptName',
            slot: 'deptName',
            align: 'center'
          },
          {
            label: '职务',
            prop: 'post',
            slot: 'post',
            align: 'center'
          },
          {
            label: '备注',
            prop: 'remark',
            slot: 'remark',
            align: 'center'
          },
          {
            action: 'action',
            slot: 'action',
            label: '操作',
            align: 'center',
            fixed: 'right',
            showOverflowTooltip: true
            // show: this.type != 'view'
          }
        ];
      },
      columnsDetail() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            width: 45,
            type: 'expand',
            columnKey: 'expand',
            align: 'center',
            slot: 'expand'
          },
          {
            prop: 'productCategoryName',
            label: '类型',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryCode',
            label: '编码',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'categoryName',
            label: '名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryModel',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'batchNo',
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 135
          },
          {
            slot: 'barcodes',
            prop: 'barcodes',
            label: '发货条码',
            align: 'center',
            minWidth: 135
          },
          {
            slot: 'shipmentDate',
            prop: 'shipmentDate',
            label: '发货时间',
            align: 'center',
            minWidth: 180
          },
          {
            prop: 'guaranteePeriodDeadline',
            label: '有效期',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'warrantyStatus',
            label: '质保状态',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              return _row.warrantyStatus == 1 ? '有效期外' : '有效期内';
            }
          },
          {
            slot: 'measureQuantity',
            prop: 'measureQuantity',
            label: '计量数量',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'singlePrice',
            label: '单价（元）',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            resizable: false,
            slot: 'action',
            // fixed: 'right',
            showOverflowTooltip: true
            // show: this.type != 'view'
          }
        ];
      },
      // 故障描述 ***
      faultList() {
        return [
          {
            type: 'index',
            label: '序号',
            align: 'center',
            width: 60
          },
          {
            prop: 'type',
            slot: 'type',
            label: '故障类型',
            align: 'center',
            headerSlot: 'headerType',
            showOverflowTooltip: true,
            width: 120
          },
          {
            prop: 'faultPhenomenon',
            slot: 'faultPhenomenon',
            headerSlot: 'headerPhenomenon',
            label: '故障现象',
            align: 'center',
            minWidth: 240
          },
          {
            prop: 'faultReason',
            slot: 'faultReason',
            headerSlot: 'headerFaultReason',
            label: '故障原因',
            align: 'center',
            minWidth: 340
          },
          {
            prop: 'maintenanceProcess',
            slot: 'maintenanceProcess',
            headerSlot: 'headerMaintenance',
            label: '维修过程',
            align: 'center',
            width: 340
          },
          {
            prop: 'attachments',
            slot: 'attachments',
            label: '附件',
            align: 'center',
            width: 120
          },
          {
            prop: 'imageUrl',
            slot: 'imageUrl',
            label: '查看拍照',
            align: 'center',
            width: 120,
            show: this.type != 'add'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            resizable: false,
            slot: 'action',
            // fixed: 'right',
            showOverflowTooltip: true
          }
        ];
      },
      // 需求表格修改权限 ***
      tableOperate() {
        if (this.isReportDetails) {
          return false;
        }
        let flag = this.type != 'view' || this.state == '可操作';
        return flag;
      },

      // 故障列表删除权限
      faultOperate() {
        return (row) => {
          let flag = (this.state == '可操作' && !row.id) || this.type != 'view';
          return flag;
        };
      },

      // 故障/联系人列表更改权限 ***
      change_permission() {
        let flag = this.type === 'view';
        if (this.source) {
          return false;
        }
        return flag;
      },

      // 附件上传 更改设置
      fileStr() {
        let str;
        if (this.isReportDetails) {
          return 'view';
        }
        if (this.source) {
          return 'add';
        }
        str = this.type == 'view' ? 'view' : 'add';
        return str;
      },
      // 图片
      imageUrleng() {
        return (row) => {
          if (!row.imageUrl) {
            return 0;
          }
          return row.imageUrl.length;
        };
      }
    },
    props: {
      type: '',
      isPurchaseNeed: {
        default: true,
        type: Boolean
      },
      // 来源页面 ***
      source: {
        default: '',
        type: String
      },

      // 表格数据 更改状态
      state: {
        default: '',
        type: String
      },

      // 是否是报工售后工单详情进入
      isReportDetails: {
        default: false,
        type: Boolean
      },

      demandList: {
        type: Array,
        default: () => []
      }
    },
    watch: {
      demandList: {
        handler(val) {
          this.demandList = val;
        },
        deep: true,
        immediate: true
      }
    },
    data() {
      return {
        tableList: [],
        selection: [],
        // 日期选择器配置
        pickerOptions: {
          disabledDate(time) {
            // 禁用今天之前的日期
            return time.getTime() < new Date().setHours(0, 0, 0, 0);
          }
        },
        typeOptions: [
          { label: '维修', value: '1' },
          { label: '保养', value: '2' },
          { label: '安装', value: '3' }
        ],
        form: {
          contractInfo: {},
          tableList: [],
          contactInfoVOS: [],
          faultDetailList: [],
          associationType: '1'
        },
        rules: {},
        radio: null,
        phoneList: [],
        phoneVisible: false,
        associationTypeList: [
          {
            value: '1',
            label: '发货单'
          },
          {
            value: '2',
            label: '销售订单'
          },
          {
            value: '3',
            label: '客户'
          }
        ],
        isOrder: false // 是否为销售订单数据
      };
    },
    created() {},
    methods: {
      async init(res) {
        let productDetail = res.productDetail ? res.productDetail : [];
        this.$set(this.form, 'tableList', productDetail);
        this.$set(this.form, 'orderCode', res.orderCode);
        this.$set(this.form, 'orderId', res.orderId);
        this.$set(this.form, 'contactInfoVOS', res.contactInfoVOS);
        this.$set(this.form, 'name', res.name);
        let faultLevel = res.faultLevel ? String(res.faultLevel) : '';
        this.$set(this.form, 'faultLevel', faultLevel);
        this.$set(this.form, 'code', res.code);
        this.$set(this.form, 'expectedTime', res.expectedTime);
        if (res.contactAddress) {
          this.$set(this.form, 'contactAddress', res.contactAddress);
        }
        this.contactDetail(res.contactId, 'init');
        this.form.associationType = res.associationType
          ? String(res.associationType)
          : '1';
        let faultDetailList = res.faultDetailList ? res.faultDetailList : [];
        this.$set(this.form, 'faultDetailList', faultDetailList);
        if (faultDetailList.length > 0) {
          this.isOrder = true;
        }
      },
      getValue() {
        return this.form;
      },
      seeImage(row) {
        this.phoneList = row.imageUrl || [];
        this.phoneVisible = true;
      },
      closePhone() {
        this.phoneList = [];
        this.phoneVisible = false;
      },
      //客户选择
      handHead() {
        if (this.type != 'view') {
          this.$refs.parentRef.open();
        }
      },
      changeParent(res) {
        this.contactDetail(res.id);
      },
      //客户回调
      async contactDetail(id, type) {
        if (!id) {
          this.contractInfo = {};
          return;
        }
        let { base, other, linkList } = await contactDetail(id);
        base.contactName = base.name;
        let addressName = '';
        if (other.addressName) {
          addressName += other.addressName;
        }
        if (other.address) {
          addressName += other.address;
        }
        this.$set(this.form, 'contractInfo', base);
        if (type != 'init') {
          this.$set(this.form, 'contactAddress', addressName);
          this.$set(
            this.form,
            'contactInfoVOS',
            linkList.map((item) => {
              item['contactName'] = item.linkName;
              item['contactPhone'] = item.mobilePhone;
              item['telephone'] = item.phone;
              return item;
            })
          );
          if (this.form.associationType != '3') {
            // 清空发货单的数据 *** 初次进来不清空
            this.$set(this.form, 'orderCode', '');
            this.$set(this.form, 'orderId', '');
            this.$set(this.form, 'tableList', []);
          }
        }
      },
      //发货单回调
      invoiceChange(data) {
        this.$set(this.form, 'orderCode', data.orderCode);
        this.$set(this.form, 'orderId', data.orderId);
        let list = JSON.parse(JSON.stringify(data.tableList));
        // 如果计量数量没有的话默认是 1
        list.map(
          (el) =>
            (el.measureQuantity = el.measureQuantity ? el.measureQuantity : 1)
        );
        this.$set(this.form, 'tableList', list);
      },
      //发货单选择
      invoiceDialogOpen() {
        if (!this.form?.contractInfo?.id) {
          this.$message.warning('请先选择客户名称!');
          return;
        }
        this.form.tableList = [];
        if (this.type != 'view') {
          let obj = {
            tableList: this.form.tableList || [],
            orderCode: this.form.orderCode || '',
            orderId: this.form.orderId || ''
          };
          this.$refs.invoiceDialogRef.open(this.form.contractInfo.id, obj);
        }
      },
      totalCountChange(data, name) {
        data[name] = data[name].replace(/[^\d]/g, '').replace(/^0+/, '') || '1';
      },
      addBank() {
        this.form.contactInfoVOS.push({
          contactName: '',
          contactPhone: '',
          remark: ''
        });
      },
      // *** 添加问题
      addProblem(row) {
        if (!row.faultDetails) this.$set(row, 'faultDetails', []);
        let len = row.faultDetails.length;
        this.$set(row.faultDetails, len, {
          maintenanceProcess: '',
          type: '',
          faultPhenomenon: ''
        });
      },
      // *** 删除问题
      delSon(row, idx) {
        row.faultDetails.splice(idx, 1);
        this.$forceUpdate();
      },
      //
      handleSelectionChange(rows) {
        this.selection = rows;
      },
      // *** 删除联系人
      delContact() {
        if (this.selection.length == 0) {
          this.$message.warning('请至少选择一条联系人信息');
          return;
        }
        this.form.contactInfoVOS = this.form.contactInfoVOS.filter(
          (row) => !this.selection.includes(row)
        );
      },
      handleBankDel(row, index) {
        this.form.contactInfoVOS.splice(index, 1);
      },
      del(row, index) {
        this.form.tableList.splice(index, 1);
      },

      getValidate() {
        return new Promise((resolve, reject) => {
          this.$refs.form.validate((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) {
              reject(false);
            } else {
              resolve(true);
            }
          });
        });
      },
      catch() {
        this.form = {
          tableList: [],
          contractInfo: {},
          contactInfoVOS: [],
          faultDetailList: [],
          orderCode: '',
          orderId: ''
        };
        this.$refs.form.resetFields();
      },

      // 销售订单选择
      saleorderDialogOpen() {
        if (!this.form?.contractInfo?.id) {
          this.$message.warning('请先选择客户名称!');
          return;
        }
        this.form.tableList = [];
        if (this.type != 'view') {
          let obj = {
            // tableList: this.form.tableList || [],
            tableList: [],
            orderCode: this.form.orderCode || '',
            orderId: this.form.orderId || ''
          };
          this.$refs.saleorderDialogRef.open(this.form.contractInfo.id, obj);
        }
      },
      //  销售订单回调
      saleorderChange(data) {
        this.$set(this.form, 'orderCode', data.orderCode);
        this.$set(this.form, 'orderId', data.orderId);
        let list = JSON.parse(JSON.stringify(data.tableList));
        // 如果计量数量没有的话默认是 1
        list.map(
          (el) =>
            (el.measureQuantity = el.measureQuantity ? el.measureQuantity : 1)
        );
        this.$set(this.form, 'tableList', list);
        if (list.length == 0) {
          this.isOrder = true;
        } else {
          this.$set(this.form, 'faultDetailList', []);
        }
      },
      // 产品选择
      customersDialogOpen() {
        this.$refs.productDialogRef.open();
      },
      // 产品选择回调
      productChange(data) {
        this.$set(this.form, 'faultDetailList', []);
        this.$set(this.form, 'orderCode', data.orderCode);
        this.$set(this.form, 'orderId', data.orderId);
        let list = JSON.parse(JSON.stringify(data.tableList));
        // 如果计量数量没有的话默认是 1
        list.map(
          (el) =>
            (el.measureQuantity = el.measureQuantity ? el.measureQuantity : 1)
        );
        this.$set(this.form, 'tableList', list);
      },
      // 新增故障 一级( 没有售后对象 )
      addFaults() {
        this.form.faultDetailList.push({
          maintenanceProcess: '',
          type: '',
          faultPhenomenon: ''
        });
      },

      faultDel(index) {
        this.form.faultDetailList.splice(index, 1);
      },
      selectType(e) {
        this.$set(this.form, 'tableList', []);
        this.$set(this.form, 'faultDetailList', []);
        this.$set(this.form, 'orderCode', '');
        this.$set(this.form, 'orderId', '');
        if (e == '1') {
          this.isOrder = false;
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  :deep(.el-table__body .el-form-item__content) {
    margin-left: 0px !important;
  }
  :deep(.el-table__body .el-form-item) {
    margin-bottom: 0px !important;
  }

  .reserve {
    margin-left: 16px;
    color: #e6a23c;
  }
</style>
