<template>
  <!-- 添加或修改项目信息对话框 -->
  <div class="el-drawer__wrapper company-list">
    <el-drawer :title="title" v-model="visible" direction="rtl" size="100%">
      <div class="page-container form-container">
        <!-- 功能按钮区域 -->
        <div class="form-btns-container">
          <span class="title-label"
            ><el-icon>
              <Document />
            </el-icon>
            客户表单</span
          >

          <el-button
            v-if="editStatus"
            type="primary"
            size="small"
            icon="Finished"
            @click="submitForm"
            >保存</el-button
          >
          <template v-else>
            <el-button
              v-hasPermi="['business:company:edit']"
              type="warning"
              size="small"
              icon="Edit"
              @click="editStatus = true"
              >修改</el-button
            >
          </template>
          <el-button
            v-if="form.id && editStatus"
            type="info"
            size="small"
            icon="Close"
            @click="
              () => {
                editStatus = false;
                getForm();
              }
            "
            >取消修改</el-button
          >
          <el-button
            v-if="form.id"
            type="success"
            size="small"
            icon="refresh"
            @click="getForm"
          >
            刷新</el-button
          >

          <div class="screen-btn" @click="handleScreen">
            <template v-if="!isFullscreen">
              <i class="fa fa-window-maximize" aria-hidden="true" />
              <!-- <span>全屏</span> -->
            </template>
            <template v-else>
              <i class="fa fa-window-restore" aria-hidden="true" />
              <!-- <span>还原</span> -->
            </template>
          </div>
          <div class="close-btn" @click="cancel">
            <i class="fa fa-times" aria-hidden="true" />
            <!-- <span>关闭</span> -->
          </div>
        </div>
        <div
          class="Y-scrollbar"
          style="
            position: absolute;
            top: 32px;
            bottom: 0;
            width: 100%;
            overflow: auto;
          "
        >
          <!-- 主表 -->
          <el-form
            ref="companyRef"
            class="master-container"
            size="small"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <div class="radio-scroll">
              <el-radio-group
                v-model="queryRadio"
                style="margin-left: 20px"
                size="small"
                @change="scrollTargetTo"
              >
                <el-radio-button label="base-form">基本信息</el-radio-button>
                <el-radio-button label="business-form"
                  >工商信息</el-radio-button
                >
                <el-radio-button label="tax-form">税务信息</el-radio-button>
                <el-radio-button label="linkman-form">联系人</el-radio-button>
                <el-radio-button v-if="form.id" label="follow-form"
                  >跟进动态</el-radio-button
                >
              </el-radio-group>
            </div>
            <div
              class="scroll-view"
              style="
                position: absolute;
                top: 50px;
                bottom: 20px;
                right: 0px;
                left: 0px;
                overflow: auto;
              "
            >
              <div class="details-container" style="margin-top: 8px">
                <div id="base-form" class="details-head">
                  <div class="title">
                    <i class="fa fa-th-list" aria-hidden="true" /> 基本信息
                  </div>
                </div>
                <el-row :gutter="30" style="margin-top: 10px">
                  <el-col :span="12">
                    <el-form-item label="客户编码：" prop="code">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.code"
                        size="small"
                        type="text"
                        style="width: 100%"
                        placeholder="客户编码"
                        :clearable="true"
                      />
                      <span v-else>{{ form.code }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="客户名称：" required prop="name">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.name"
                        size="small"
                        type="text"
                        placeholder="客户名称"
                        :clearable="true"
                      />
                      <span v-else>{{ form.name }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="简称：" prop="shortName">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.shortName"
                        size="small"
                        type="text"
                        placeholder="简称"
                        :clearable="true"
                      />
                      <span v-else>{{ form.shortName }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" style="width: 100%">
                    <el-form-item label="客户来源：" prop="sourceCategoryName">
                      <CustomerFormCom
                        ref="CustomerFormComRef"
                        :edit-status="editStatus"
                        :form-data="form"
                        :source-categories="sourceCategories"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" >
                    <el-form-item label="客户标签" prop="customerLabelId" >
                      <el-select v-model="form.customerLabelId"  style="width:100%"
                      v-if="editStatus"
                      >
                      <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.lable"
                      :value="item.id"
                    />
                    </el-select>
                    <span v-else>{{ selectedOptionLabel }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="备注：">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.remark"
                        type="text"
                        width="100%"
                        size="small"
                        placeholder="备注"
                        :clearable="true"
                      />
                      <span v-else>{{ form.remark }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <br />

                <div id="business-form" class="details-head">
                  <div class="title">
                    <i class="fa fa-th-list" aria-hidden="true" /> 工商信息
                  </div>
                </div>
                <el-row :gutter="30" style="margin-top: 10px">
                  <el-col :span="8">
                    <el-form-item
                      label="税号："
                      prop="socialCreditCode"
                    >
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.socialCreditCode"
                        size="small"
                        type="text"
                        placeholder="税号"
                        :clearable="true"
                      />
                      <span v-else>{{ form.socialCreditCode }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="主营行业：">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.mainBusiness"
                        size="small"
                        type="text"
                        placeholder="主营行业"
                        :clearable="true"
                      />
                      <span v-else>{{ form.mainBusiness }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="企业类型：">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.type"
                        size="small"
                        type="text"
                        placeholder="企业类型"
                        :clearable="true"
                      />
                      <span v-else>{{ form.type }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="法定代表人：">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.legalRepresentative"
                        size="small"
                        type="text"
                        placeholder="法定代表人"
                        :clearable="true"
                      />
                      <span v-else>{{ form.legalRepresentative }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="成立日期：">
                      <el-date-picker
                        v-if="editStatus"
                        v-model.trim="form.foundationDate"
                        size="small"
                        :clearable="true"
                        style="width: 100%"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        align="center"
                        type="date"
                        placeholder="成立日期"
                      />
                      <span v-else>{{ form.foundationDate }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="出执照日期：">
                      <el-date-picker
                        v-if="editStatus"
                        v-model.trim="form.licenceDate"
                        size="small"
                        :clearable="true"
                        style="width: 100%"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        align="center"
                        type="date"
                        placeholder="出执照日期"
                      />
                      <span v-else>{{ form.licenceDate }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="营业开始日期："
                      prop="createTime"
                      class="date-layout"
                    >
                      <template v-if="editStatus">
                        <el-date-picker
                          v-model="form.businessStartDate"
                          size="small"
                          :clearable="true"
                          style="width: 100%"
                          format="YYYY-MM-DD"
                          value-format="YYYY-MM-DD"
                          align="center"
                          type="date"
                          placeholder="开始日期"
                        />
                      </template>
                      <span v-else>
                        {{
                          form.businessStartDate == null
                            ? ""
                            : form.businessStartDate
                        }}</span
                      >
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="营业截止日期："
                      prop="createTime"
                      class="date-layout"
                    >
                      <template v-if="editStatus">
                        <el-date-picker
                          v-model="form.businessEndDate"
                          size="small"
                          :clearable="true"
                          style="width: 100%"
                          format="YYYY-MM-DD"
                          value-format="YYYY-MM-DD"
                          :disabled="PermanentlyEffective"
                          align="center"
                          type="date"
                          placeholder="结束日期"
                        />
                      </template>
                      <span v-else-if="form.isPermanentlyEffective == 0">
                        {{
                          form.businessEndDate == null
                            ? ""
                            : form.businessEndDate
                        }}
                      </span>
                      <span v-else-if="form.isPermanentlyEffective == 1">
                        {{ "无固定期限" }}
                      </span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <div
                      style="display: inline; height: 28pxs; margin-left: -70px"
                    >
                      <el-form-item>
                        <template v-if="editStatus">
                          <span
                            style="
                              font-size: 12px;
                              margin-left: -16px;
                              margin-right: 8px;
                            "
                            >无固定期限</span
                          >
                          <el-checkbox v-model="PermanentlyEffective" />
                        </template>
                      </el-form-item>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="注册资金：">
                      <el-input
                        v-if="editStatus"
                        v-model.number="form.registerMoney"
                        number
                        size="small"
                        id="inputField"
                        min="0"
                        placeholder="注册资金"
                        :clearable="true"
                        controls-position="right"
                        style="width: 100%"
                        @input="handleInput"
                        @change="handleCompute"
                      >
                        <template #append>万元</template>
                      </el-input>
                      <span v-else
                        >{{ rowNum(form.registerMoney) }}{{ "万元" }}
                      </span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item
                      label="注册省市区："
                      prop="provinceCode"
                    >
                      <template v-if="editStatus">
                        <el-select
                          v-model="form.provinceCode"
                          placeholder="省份"
                          style="width: 33.33%"
                          @change="handleSelectProvince"
                        >
                          <el-option
                            v-for="item in provinces"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                          />
                        </el-select>
                        <el-select
                          v-model="form.cityCode"
                          placeholder="城市"
                          style="width: 33.33%"
                          @change="handleSelectCity"
                        >
                          <el-option
                            v-for="item in cities"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                          />
                        </el-select>
                        <el-select
                          v-model="form.districtCode"
                          placeholder="行政区"
                          style="width: 33.33%"
                          @change="handleSelectDistrict"
                        >
                          <el-option
                            v-for="item in districts"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                          />
                        </el-select>
                        <!-- <EluiChinaAreaDht v-model="area" @change="handleAreaChange" /> -->
                      </template>
                      <span v-else>{{
                        form.province +
                        (form.city ? " - " + form.city : "") +
                        (form.district ? " - " + form.district : "")
                      }}</span>
                    </el-form-item>
                  </el-col>

                  <el-col :span="16">
                    <el-form-item label="详细地址：">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.address"
                        size="small"
                        type="text"
                        placeholder="详细地址："
                        :clearable="true"
                      />
                      <div
                        v-else
                        style="
                          display: flex;
                          align-items: center;
                          height: 28px;
                          line-height: normal;
                        "
                      >
                        <span>{{ form.address }}</span>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24" style="height: auto; min-height: 60px">
                    <el-form-item label="经营范围：">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.businessField"
                        maxlength="200"
                        type="textarea"
                        :rows="5"
                        width="100%"
                        size="small"
                        placeholder="经营范围"
                        show-word-limit
                        :clearable="true"
                      />
                      <span v-else>{{ form.businessField }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <br />
                <div id="tax-form" class="details-head">
                  <div class="title">
                    <i class="fa fa-th-list" aria-hidden="true" /> 税务信息
                  </div>
                </div>
                <el-row :gutter="30" style="margin-top: 10px">
                  <el-col :span="6">
                    <el-form-item label="纳税性质：" prop="taxType">
                      <el-select
                        v-if="editStatus"
                        v-model="form.taxType"
                        placeholder="请选择纳税性质"
                        size="small"
                        :clearable="true"
                        @change="taxTypeChange"
                      >
                        <el-option
                          v-for="item in taxTypes"
                          :key="item.label"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <span v-else>{{ form.taxType }} </span>
                    </el-form-item>
                  </el-col>
                  <el-col v-if="form.taxType === '个体工商户'" :span="6">
                    <el-form-item label="征收方式：" required>
                      <el-select
                        v-if="editStatus"
                        v-model="form.collectionMethod"
                        placeholder="请选择征收方式"
                        size="small"
                        :clearable="true"
                      >
                        <el-option
                          v-for="item in collectionMethods"
                          :key="item.label"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <span v-else>{{ form.collectionMethod }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col v-if="form.collectionMethod === '定期定额'" :span="6">
                    <el-form-item label="定额金额：" required>
                      <el-input-number
                        v-if="editStatus"
                        v-model="form.quotaAmount"
                        placeholder="请输入定额金额"
                        :min="0"
                        :precision="2"
                        controls-position="right"
                        :controls="false"
                        size="small"
                      />
                      <span v-else>{{ form.quotationAmount }}</span>
                    </el-form-item>
                  </el-col>

                  <el-col :span="6">
                    <el-form-item label="是否零申报：">
                      <el-select
                        v-if="editStatus"
                        v-model="form.isZero"
                        placeholder="请选择"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="item in yesOrNo"
                          :key="item.label"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <span v-else>{{
                        form.isZero === 1 ? "是" : form.isZero === 0 ? "否" : ""
                      }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="主管税务机关：">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.competentTaxAuthority"
                        size="small"
                        type="text"
                        placeholder="主管税务机关"
                        :clearable="true"
                      />
                      <span v-else>{{ form.competentTaxAuthority }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="税务专管员">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.taxCollectorName"
                        size="small"
                        type="text"
                        placeholder="税务专管员"
                        :clearable="true"
                      />
                      <span v-else>{{ form.taxCollectorName }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="专管员电话：">
                      <el-input
                        v-if="editStatus"
                        v-model.trim="form.taxCollectorPhone"
                        size="small"
                        type="text"
                        placeholder="专管员电话"
                        minlength="1"
                        maxlength="11"
                        oninput="value=value.replace(/[^\d]/g, '')"
                        :clearable="true"
                      />
                      <span v-else>{{ form.taxCollectorPhone }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="核税月份：">
                      <el-date-picker
                        v-if="editStatus"
                        v-model.trim="form.taxMonth"
                        size="small"
                        :clearable="true"
                        format="YYYY-MM"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        align="center"
                        type="month"
                        placeholder="核税月份"
                      />
                      <span v-else> {{ form.taxMonth }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="年收入：" prop="annualIncome">
                      <el-select
                        style="width: 100%"
                        v-if="editStatus"
                        v-model="form.annualIncome"
                        placeholder="请选择年收入"
                      >
                        <el-option
                          v-for="item in incomeDefault"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <span v-else>{{ form.annualIncome }} </span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <br />
                <div id="linkman-form" class="details-head">
                  <div class="title">
                    <i class="fa fa-th-list" aria-hidden="true" /> 联系人
                  </div>
                  <div v-if="editStatus" class="details-btns-container">
                    <el-button
                      type="primary"
                      size="small"
                      icon="Plus"
                      @click="handleAddContactor"
                    >
                      添加联系人</el-button
                    >
                  </div>
                </div>
                <el-row :gutter="10" style="height: 200px">
                  <el-col :span="24">
                    <div class="details-body">
                      <el-table
                        ref="contactorsable"
                        :data="form.contactors"
                        size="small"
                        border
                        header-row-class-name="list-header-row"
                        max-height="200"
                      >
                        <el-table-column
                          type="index"
                          label="序号"
                          width="47"
                          align="center"
                        />
                        <el-table-column label="姓名" width="70" align="center">
                          <template #default="scope">
                            <div v-if="editStatus">
                              <el-input
                                v-model="scope.row.name"
                                size="small"
                                placeholder="姓名"
                              />
                              <span class="required">*</span>
                            </div>
                            <div v-else>
                              {{ scope.row.name }}
                              <span class="required">*</span>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="角色"
                          width="130"
                          align="center"
                        >
                          <template #default="scope">
                            <div v-if="editStatus">
                              <el-select
                                v-model="scope.row.position"
                                size="small"
                                placeholder="角色"
                              >
                                <el-option
                                  v-for="(item, index) in contact_role"
                                  :key="index"
                                  :label="item.label"
                                  :value="item.label"
                                />
                              </el-select>
                            </div>
                            <div v-else>
                              {{ scope.row.position }}
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="联系电话"
                          width="100"
                          align="center"
                        >
                          <template #default="scope">
                            <div v-if="editStatus">
                              <el-input
                                v-model="scope.row.phone"
                                size="small"
                                minlength="1"
                                maxlength="11"
                                placeholder="联系电话"
                                oninput="value=value.replace(/[^\d]/g, '')"
                              />
                            </div>
                            <div v-else>{{ scope.row.phone }}</div>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="主联系人"
                          width="100"
                          align="center"
                        >
                          <template #default="scope">
                            <div v-if="editStatus">
                              <el-select
                                v-model="scope.row.isMain"
                                class="txtC"
                                size="small"
                                placeholder="请选择"
                              >
                                <el-option
                                  v-for="(item, index) in confirmDefaultRef"
                                  :key="index"
                                  :label="item.label"
                                  :value="item.label"
                                />
                              </el-select>
                            </div>
                            <div v-else>
                              {{ scope.row.isMain }}
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="备注"
                          prop="remark"
                          header-align="center"
                        >
                          <template #default="scope">
                            <div v-if="editStatus">
                              <el-input
                                v-model="scope.row.remark"
                                size="small"
                                placeholder="备注"
                              />
                            </div>
                            <div v-else>{{ scope.row.remark }}</div>
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" width="50" align="center">
                          <template #default="scope">
                            <div>
                              <el-button
                                v-if="editStatus"
                                size="small"
                                link
                                type="danger"
                                @click="handleDelContactor(scope.$index)"
                                >删除</el-button
                              >
                              <span v-else>-</span>
                            </div>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </el-col>
                </el-row>
                <br />
                <div v-if="form.id" id="follow-form" class="details-head">
                  <div class="title">
                    <i class="fa fa-th-list" aria-hidden="true" /> 跟进动态
                  </div>
                </div>
                <el-row v-if="form.id" :gutter="30" style="margin-top: 10px">
                  <el-col :span="6">
                    <el-form-item label="跟进方式：" required>
                      <el-select
                        v-model.trim="followData.followTypeId"
                        placeholder="跟进方式"
                        size="small"
                        :clearable="true"
                      >
                        <el-option
                          v-for="item in follow_modes"
                          :key="item.label"
                          :label="item.label"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="跟进类型：" required>
                      <el-select
                        v-model.trim="followData.followCategoryId"
                        placeholder="跟进类型"
                        size="small"
                        :clearable="true"
                      >
                        <el-option
                          v-for="item in follow_categories"
                          :key="item.label"
                          :label="item.label"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="跟进时间：" required>
                      <el-date-picker
                        v-model="followData.followDate"
                        style="width: 100%"
                        size="small"
                        format="YYYY-MM-DD HH:mm"
                        type="datetime"
                        placeholder="选择日期"
                        value-format="YYYY-MM-DD HH:mm"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="下次跟进时间">
                      <el-date-picker
                        v-model="followData.nextFollowDate"
                        :disabled-date="nextFollowDateDisable"
                        style="width: 100%"
                        size="small"
                        format="YYYY-MM-DD HH:mm"
                        type="datetime"
                        placeholder="选择日期"
                        value-format="YYYY-MM-DD HH:mm"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24" style="height: auto; min-height: 24px">
                    <el-form-item label="跟进内容：" required>
                      <el-input
                        v-model.trim="followData.content"
                        maxlength="200"
                        type="textarea"
                        :rows="2"
                        width="100%"
                        size="small"
                        placeholder="请填写跟进内容"
                        :clearable="true"
                        show-word-limit
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24" style="padding: 15px 15px 16px 15px">
                    <div class="details-btns-container">
                      <el-form-item label="上传附件" required>
                        <el-upload
                          action="#"
                          :http-request="upload"
                          :with-credentials="true"
                          :show-file-list="false"
                          multiple
                        >
                          <el-button size="small" type="primary" icon="Upload"
                            >点击上传</el-button
                          >
                        </el-upload>
                      </el-form-item>
                    </div>
                    <div class="details-body" style="height: 100px">
                      <el-table
                        ref="filesTable"
                        :data="fileList"
                        size="small"
                        height="100%"
                        border
                        header-row-class-name="list-header-row"
                      >
                        <el-table-column
                          label="文件名"
                          prop="fileName"
                          align="center"
                        >
                          <template #default="scope">
                            <el-link
                              :href="`${baseUrl}${scope.row.fileUrl}`"
                              :underline="false"
                              target="_blank"
                              type="primary"
                            >
                              {{ scope.row.fileName }}
                            </el-link>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="文件类型"
                          prop="fileType"
                          width="90"
                          align="center"
                        >
                          <template #default="scope">
                            <el-link :underline="false" target="_blank">
                              {{ scope.row.fileType }}
                            </el-link>
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" width="60" align="center">
                          <template #default="scope">
                            <el-button
                              link
                              size="small"
                              type="danger"
                              @click="handleDelFile(scope.$index)"
                              >删除</el-button
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </el-col>
                  <el-col
                    :span="24"
                    style="
                      text-align: center;
                      display: flex;
                      flex-direction: row;
                      justify-content: center;
                    "
                  >
                    <el-button
                      size="small"
                      type="primary"
                      style="width: 160px"
                      @click="followSaveHandler"
                      >发 布</el-button
                    >
                  </el-col>
                  <br />
                  <el-col :span="24">
                    <br />
                    <div class="details-head">
                      <div class="title">
                        <i class="fa fa-th-list" aria-hidden="true" /> 跟进记录
                      </div>
                      <div class="details-btns-container" style="display: flex">
                        <el-switch
                          v-model="followQuery.asc"
                          style="display: inline-block height:28px; line-height:28px;"
                          active-color="#13ce66"
                          inactive-color="#ff4949"
                          active-text="正序"
                          inactive-text="倒序"
                          size="small"
                        />
                      </div>
                    </div>
                    <div class="details-body" style="height: 200px">
                      <el-table
                        ref="filesTable"
                        :data="form.followDetails"
                        size="small"
                        height="100%"
                        border
                        header-row-class-name="list-header-row"
                      >
                        <el-table-column
                          type="index"
                          label="序号"
                          width="47"
                          align="center"
                        />
                        <el-table-column
                          label="跟进方式"
                          prop="followMode"
                          align="center"
                          width="120"
                        />
                        <el-table-column
                          label="跟进类型"
                          prop="followCategory"
                          align="center"
                          width="120"
                        />
                        <el-table-column
                          label="跟进时间"
                          prop="followDate"
                          align="center"
                          width="140"
                        />
                        <el-table-column
                          label="跟进内容"
                          prop="content"
                          align="center"
                        />
                        <el-table-column
                          label="下次跟进时间"
                          prop="nextFollowDate"
                          align="center"
                          width="140"
                        />
                        <el-table-column label="操作" align="center">
                          <template #default="scope">
                            <el-button
                              link
                              size="small"
                              type="primary"
                              @click="handleImageView(scope.row)"
                              >查看</el-button
                            >
                            <el-button
                              link
                              size="small"
                              type="danger"
                              @click="handleDelFollow(scope.row)"
                              >删除</el-button
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                    <br />
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-form>
        </div>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="currentFileList"
      @close="closeImages"
      :initial-index="showIndex"
    />
    <fileDialog ref="fileDialogRef" />
  </div>
</template>
<script setup>
import { getToken } from "@/utils/auth";
import { EluiChinaAreaDht } from "elui-china-area-dht";
import {
  addFollow,
  listFollow,
  delFollow,
} from "@/api/business/crm/companyFollowDetail";
import { regionData, codeToText } from "element-china-area-data";
import CustomerFormCom from "@/components/CustomerFormCom";
import fileDialog from "@/views/dialog/fileDialog.vue";
import {
  getCompany,
  addCompany,
  updateCompany,
} from "@/api/business/crm/company";
import useUserStore from "@/store/modules/user";
import { listSource } from "@/api/settings/source";
import { deepClone } from "@/utils";
import { rowNum } from "@/utils/index";
import { uploadFile } from "@/api/tool/file";
import { ref } from "vue";
import {
  incomeDefault,
  taxTypes,
  confirmDefault,
  collectionMethods,
  yesOrNo,
} from "@/utils/default";
const { proxy } = getCurrentInstance();
/** 父组件传参 */
const props = defineProps({
  getList: {
    type: Function,
    default: () => {},
  },
});

const registerMoneyUnits = ref([]);
const mainBusinesses = ref([]);
const taxDishes = ref([]);
const { getList } = toRefs(props);
const options = ref([]);
/** 字典数组区 */
const { develop_type } = proxy.useDict("develop_type");
const { follow_categories } = proxy.useDict("follow_categories");
const { contact_role } = proxy.useDict("contact_role");
const { follow_modes } = proxy.useDict("follow_modes");
const confirmDefaultRef = ref(confirmDefault);
import { listLableNoPage } from "@/api/business/lable";
const CustomerFormComRef = ref(null);
/** 表单抽屉 页变量 */
const title = ref("");
const loading = ref(false);
const multiple = ref(true);
const visible = ref(false);
const editStatus = ref(false);
const isFullscreen = ref(false);
const addDetailNum = ref(1);
const currentMember = {};
const provinces = ref(proxy.region.getProvinces());
provinces.value.unshift({ code: "", name: "全部" });
const cities = ref([]);
const fileDialogRef = ref(null);

const districts = ref([]);
const sourceCategories = ref([]);
const area = ref([]);
const fileList = ref([]);
const PermanentlyEffective = ref(false);
const showViewer = ref(false);
const currentFileList = ref([]);
const showIndex = ref(0);
const types = ref([]);
const taxDeclarationCategories = ref([]);

const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);

const webHost = import.meta.env.VITE_APP_BASE_API;
const setHeaders = {
  Authorization: getToken(),
};
const data = reactive({
  form: {},
  followData: {},
  followQuery: {
    isAsc: "asc",
  },
  rules: {
    name: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
    // socialCreditCode: [
    //   { max: 18, min: 18, message: "税号为18位", trigger: "blur" },
    // ],
    // provinceCode: [{ validator: areaValidator, trigger: "blur" }],
    taxType: [{ require: true, message: "纳税性质不能为空", trigger: "blur" }],
    sourceCategoryName: [
      { validator: sourceValidator, trigger: "change" },
      { required: true, message: "客户来源不能为空", trigger: "change" },
    ],
  },
});

const { form, rules, followData, followQuery } = toRefs(data);

watch(
  followQuery,
  () => {
    if (followQuery.value.asc) {
      followQuery.value.isAsc = "asc";
    } else {
      followQuery.value.isAsc = "desc";
    }
    loadFollow();
  },
  { deep: true }
);

const contactorEmptyData = {
  id: null,
  name: "",
  position: "",
  gender: "男",
  phone: "",
  email: "",
  isMain: "是",
  remark: "",
};
const companyEmptyData = {
  id: null,
  code: "",
  name: "",
  oldName: "",
  shortName: "",
  ownerId: "",
  ownerName: "",
  sourceCategoryId: "",
  sourceCategoryName: "",
  sourceId: "",
  sourceName: "",
  stageId: "",
  stageName: "",
  phone: "",
  email: "",
  contactAddress: "",
  remark: "",
  socialCreditCode: "",
  mainBusinessId: "",
  mainBusinessName: "",
  typeId: "",
  typeName: "",
  legalRepresentative: "",
  foundationDate: "",
  licenceDate: "",
  businessStartDate: "",
  collectionMethod: "",
  businessEndDate: "",
  isPermanentlyEffective: "",
  registerMoney: "",
  registerMoneyUnitId: "",
  registerMoneyUnitName: "",
  provinceCode: "",
  province: "",
  cityCode: "",
  city: "",
  districtCode: "",
  district: "",
  address: "",
  businessField: "",
  taxTypeId: "",
  taxTypeName: "",
  taxDeclarationCategoryId: "",
  taxDeclarationCategoryName: "",
  isZero: "",
  taxDishId: "",
  taxDishName: "",
  competentTaxAuthority: "",
  annualIncome: "",
  taxType: "",
  taxCollectorName: "",
  taxCollectorPhone: "",
  taxMonth: "",
  openingBank: "",
  bankAccount: "",
  companyTags: [],
  companyTagIds: [],
  contactors: [],
  serviceTeams: [],
  companyFiles: [],
  stores: [],
  creatorId: useUserStore().user.id,
};
const queryRadio = ref("base-form");
const defaultIsZero = ref(0);
/***********************  表单页方法 ****************************/

function sourceValidator(rule, value, callback) {
  if (form.value.sourceCategoryName === "") {
    callback(new Error("来源类型不能为空"));
    return;
  }
  if (
    form.value.referrerDataSource !== "" &&
    form.value.referrerDataSource != null &&
    (form.value.sourceName === "" || form.value.sourceName == null)
  ) {
    callback(new Error("来源不能为空"));
    return;
  }
  return callback();
}

/** 抽屉打开 */
function open(id, position) {
  reset();
  visible.value = true;

  if (id) {
    getCompany(id).then((response) => {
      form.value = response.data;
      defaultIsZero.value = Number(response.data.isZero);
      initRegion();
      editStatus.value = false;
      title.value = "修改客户";

      nextTick((_) => {
        if (position) {
          scrollTargetTo(position);
        } else {
          scrollTargetTo("base-form");
        }
      });
    });
  } else {
    editStatus.value = true;
    title.value = "添加客户";
  }
  getOption()
  console.log("字典", contact_role.value);
}
function getOption(){
  listLableNoPage().then(res =>{
     options.value = res.data
  })
}
const selectedOptionLabel = computed(() => {
      const selectedOption = options.value.find(option => option.id === form.value.customerLabelId);
      return selectedOption ? selectedOption.lable : '';
    });
/** 注册资金限制 */
function handleInput(event) {
  if (event) {
    var str = event;
    var len1 = str.substr(0, 1);
    var len2 = str.substr(1, 1);
    //如果第一位是0，第二位不是点，就用数字把点替换掉
    if (str.length > 1 && len1 == 0 && len2 != ".") {
      str = str.substr(1, 1);
    }
    //第一位不能是.
    if (len1 == ".") {
      str = "";
    }
    //限制只能输入一个小数点
    if (str.indexOf(".") != -1) {
      var str_ = str.substr(str.indexOf(".") + 1);
      if (str_.indexOf(".") != -1) {
        str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
      }
    }
    //正则替换，保留数字和小数点
    str = str.replace(/[^\d^\.]+/g, "");
    form.value.registerMoney = str;
  }
}

/** 注册资金计算保留两位小数 */
function handleCompute() {
  form.value.registerMoney = Math.round(form.value.registerMoney * 100) / 100;
}

function init() {
  listSource()
    .then((res) => {
      sourceCategories.value = res.rows;
    })
    .catch((err) => {
      console.log(err);
    });
}

/**  取消按钮 */
function cancel() {
  visible.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = deepClone(companyEmptyData);
  if (CustomerFormComRef.value) CustomerFormComRef.value.reset();
  followData.value = {};
  proxy.resetForm("companyRef");
}

/** 上传后方法处理 */
function uploadSuccess(res) {
  if (res.code == 200) {
    const newAttach = {
      name: res.data.name,
      url: res.data.url,
    };
    form.value.attaches.push(newAttach);
  } else {
    proxy.$modal.msgError("上传失败" + res.msg);
  }
}

function handleDownLoad(url) {
  window.open(webHost + url);
}

// 全屏缩放
function handleScreen() {
  const dom = document.querySelector(
    ".list-container > .el-drawer__wrapper > .el-overlay"
  );
  isFullscreen.value = !isFullscreen.value;
  dom.style.position = isFullscreen.value ? "fixed" : "absolute";
}

function getForm() {
  loading.value = true;
  getCompany(form.value.id).then((response) => {
    reset();
    loading.value = false;
    form.value = response.data;
    PermanentlyEffective.value = form.value.isPermanentlyEffective == 1;
    // CustomerFormCom.value.setForm(form.value);
    console.log("刷新表单", form.value);
  });
}

function checkZero() {
  if (defaultIsZero.value === 1) {
    return true;
  } else if (
    defaultIsZero.value != form.value.isZero &&
    form.value.isZero === 1
  ) {
    proxy.$modal.msgError("不可将非零申报客户改为零申报");

    return false;
  } else {
    return true;
  }
}

/** 提交保存 */
function submitForm() {
  console.log("提交表单", form.value);
  form.value.isPermanentlyEffective = PermanentlyEffective.value ? 1 : 0;
  proxy.$refs["companyRef"].validate((valid) => {
    if (valid && validDetails() && checkZero()) {
      if (form.value.id) {
        updateCompany(form.value).then((response) => {
          proxy.$modal.msgSuccess("保存成功!");
          editStatus.value = false;
          form.value = response.data;
          defaultIsZero.value = Number(response.data.isZero);
          getList.value();
        });
      } else {
        addCompany(form.value).then((res) => {
          proxy.$modal.msgSuccess("保存成功!");
          editStatus.value = false;
          form.value = response.data;
          defaultIsZero.value = Number(response.data.isZero);
          getList.value();
        });
      }
    }
  });
}

/** 添加从表 */
function handleAdd() {
  for (var i = 0; i < addDetailNum.value; i++) {
    form.value.members.push({});
  }
}

/** 删除从表 */
function handleDel(index) {
  proxy.$modal
    .confirm("确定删除?")
    .then(() => {
      form.value.members.splice(index, 1);
    })
    .catch(() => {
      proxy.$modal.msg("已取消删除");
    });
}

function handleDelAttach(index) {
  proxy.$modal
    .confirm("确定删除?")
    .then(() => {
      form.value.attaches.splice(index, 1);
    })
    .catch(() => {
      proxy.$modal.msg("已取消删除");
    });
}

/** 单选添加 */
function handleDialogOpen(person) {
  multiple.value = false;
  currentMember.value = person;
  proxy.$refs.personRef.open();
}

/** 多选添加 */
function handleAddBatch() {
  multiple.value = true;
  proxy.$refs.personRef.open();
}

function handleSingleSelected(person) {
  if (
    form.value.members.findIndex((item) => item.personId === person.id) === -1
  ) {
    currentMember.value.personId = person.id;
    currentMember.value.name = person.name;
    currentMember.value.code = person.code;
    currentMember.value.gender = person.gender;
    currentMember.value.age = person.age;
    currentMember.value.phone = person.phone;
  } else {
    proxy.$modal.msgError(person.name + "已存在,请勿重复添加！");
  }
}

function handleMultipleSelected(selection) {
  for (var i = 0; i < selection.length; ++i) {
    const newPerson = {};
    if (
      form.value.members.findIndex(
        (item) => item.personId === selection[i].id
      ) === -1
    ) {
      newPerson.personId = selection[i].id;
      newPerson.name = selection[i].name;
      newPerson.code = selection[i].code;
      newPerson.gender = selection[i].gender;
      newPerson.age = selection[i].age;
      newPerson.phone = selection[i].phone;
      form.value.members.push(newPerson);
    } else {
      proxy.$modal.msgError(selection[i].name + "已存在,请勿重复添加！");
    }
  }
}

function scrollTargetTo(target) {
  const targetElement = document.getElementById(target);
  if (targetElement) {
    targetElement.scrollIntoView();
  }
}

async function followSaveHandler() {
  if (
    followData.value.followTypeId === null ||
    followData.value.followTypeId === "0"
  ) {
    proxy.$modal.msgWarning("请选择跟进方式");
    return;
  }
  if (
    followData.value.followCategoryId === null ||
    followData.value.followCategoryId === "0"
  ) {
    proxy.$modal.msgWarning("请选择跟进类型");
    return;
  }
  if (followData.value.content == null || followData.value.content === "") {
    proxy.$modal.msgWarning("请输入跟进内容");
    return;
  }
  followData.value.companyId = form.value.id;
  followData.value.files = fileList.value;
  const res = await addFollow(followData.value);
  if (res.code === 200) {
    editStatus.value = false;
    getForm(form.value.id);
    getList.value();
    followData.value = {};
    fileList.value = [];
    proxy.$modal.msgSuccess("发布成功");
  } else {
    proxy.$modal.msgError(res.message);
  }
}

function handleAddContactor() {
  const contactor = JSON.parse(JSON.stringify(contactorEmptyData));
  form.value.contactors.push(contactor);
  return;
}
// function areaValidator(rule, value, callback) {
//   console.log("省份验证");
//   if (form.value.provinceCode === "") {
//     callback(new Error("省份不能为空"));
//     return;
//   }
//   if (form.value.cityCode === "") {
//     callback(new Error("城市不能为空"));
//     return;
//   }
//   if (form.value.districtCode === "") {
//     callback(new Error("行政区不能为空"));
//     return;
//   }

//   return callback();
// }

function handleSelectProvince() {
  const _provinceCode = form.value.provinceCode;
  const _province = provinces.value.find(function (item) {
    return item.code === _provinceCode;
  });
  form.value.province = _province.name;
  cities.value = proxy.region.getCities(_provinceCode);
  if (cities.value.length === 0) {
    // 清空城市数据
    form.value.cityCode = "";
    form.value.city = "";
    cities.value = [{ code: "", name: "全部" }];
    // 清空行政区数据
    form.value.districtCode = "";
    form.value.district = "";
    districts.value = [];
  } else {
    cities.value.unshift({ code: "", name: "全部" });
    form.value.cityCode = cities.value[0].code;
    form.value.city = cities.value[0].name;
    handleSelectCity();
  }
}

function handleSelectCity() {
  console.log("市");
  const _cityCode = form.value.cityCode;
  const _city = cities.value.find(function (item) {
    return item.code === _cityCode;
  });
  form.value.city = _city.name;
  districts.value = proxy.region.getDistricts(_cityCode);
  if (districts.value.length === 0) {
    // 清空行政区数据
    form.value.districtCode = "";
    form.value.district = "";
    districts.value = [{ code: "", name: "全部" }];
  } else {
    districts.value.unshift({ code: "", name: "全部" });
    form.value.districtCode = districts.value[0].code;
    form.value.district = districts.value[0].name;
  }
}

function handleSelectDistrict() {
  console.log("区");
  const _districtCode = form.value.districtCode;
  const _district = districts.value.find(function (item) {
    return item.code === _districtCode;
  });
  form.value.district = _district.name;
}

function validDetails() {
  const contactors = form.value.contactors;
  if (contactors.length === 0) {
    return true;
  }
  form.value.contactors.forEach(function (val, index) {
    if (val.name === "") {
      proxy.$modal.msgError(`第 ${index + 1} 行联系人的姓名不能为空`);
      _isNull = true;

      return false;
    } else if (val.position === "") {
      proxy.$modal.msgError(`第 ${index + 1} 行联系人的角色不能为空`);
      _isNull = true;

      return false;
    }
  });
  return true;
}

function handleDelContactor(index) {
  proxy.$modal.confirm("是否确认删除选中的数据项？").then(() => {
    form.value.contactors.splice(index, 1);
  });
}

function handleAreaChange(arg) {
  if (arg != null && arg.length === 3) {
    form.value.provinceCode = arg[0];
    form.value.cityCode = arg[1];
    form.value.districtCode = arg[2];

    form.value.province = codeToText[arg[0]];
    form.value.city = codeToText[arg[1]];
    form.value.district = codeToText[arg[2]];
  }
}

function upload(param) {
  const formData = new FormData();
  formData.append("file", param.file);
  uploadFile(formData).then((res) => {
    if (res.code === 200) {
      const file = {};
      file.fileName = res.newFileName;
      file.fileType =
        res.newFileName.split(".")[res.newFileName.split(".").length - 1];
      file.url = res.url;
      file.originalFileName = res.originalFilename;
      file.fileUrl = res.fileName;
      fileList.value.push(file);
    }
  });
}

function uploadFollowRemove(index) {
  fileList.value.splice(index, 1);
}

function openFollowFile(arg) {
  const attach = arg;
  window.open(`${arg.url}`, arg.fileName);
}

function nextFollowDateDisable(date) {
  const follow = proxy.moment(followData.value.followDate);
  if (proxy.moment(date).isBefore(follow)) {
    return true;
  } else return false;
}

function loadFollow() {
  followQuery.value.companyId = form.value.id;
  listFollow(followQuery.value).then((res) => {
    form.value.followDetails = res.rows;
  });
}

function handleDelFollow(row) {
  const _ids = row.id;
  proxy.$modal
    .confirm("是否确认删除选中的数据项？")
    .then(function () {
      return delFollow(_ids);
    })
    .then(() => {
      loadFollow();
      proxy.$modal.msgSuccess("删除成功！");
    })
    .catch(() => {});
}

/** 查看按钮事件 */
function handleImageView(row) {
  // let imgUrl = [];
  // let txtUrl = [];
  // row.files.forEach((l) => {
  //   var res = l.fileUrl.split(".")[l.fileUrl.split(".").length - 1];
  //   if (
  //     res === "jpg" ||
  //     res === "png" ||
  //     res === "psd" ||
  //     res === "pdf" ||
  //     res === "gif" ||
  //     res === "bmp"
  //   ) {
  //     imgUrl.push(`${baseUrl.value}${l.fileUrl}`);
  //   } else {
  //     txtUrl.push(`${baseUrl.value}${l.fileUrl}`);
  //   }
  // });
  // if (imgUrl.length > 0) {
  //   currentFileList.value = imgUrl;
  //   showViewer.value = true;
  // }
  // if (txtUrl.length > 0) {
  //   txtUrl.forEach((l) => {
  //     downloadFile(l);
  //   });
  // }
  fileDialogRef.value.open({
    masterTableName: "biz_company_follow_detail",
    masterId: row.id,
  });
}

/** 下载事件 */
function downloadFile(url) {
  const iframe = document.createElement("iframe");
  iframe.style.display = "none"; // 防止影响页面
  iframe.style.height = 0; // 防止影响页面
  iframe.src = url;
  document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
  // 5分钟之后删除
  setTimeout(() => {
    iframe.remove();
  }, 5 * 60 * 1000);
}

function closeImages() {
  showViewer.value = false;
}

function taxTypeChange(item) {
  if (item !== "个体工商户") {
    form.value.collectionMethod = "";
  }
}

function initRegion() {
  console.log("省市区", form.value);
  cities.value = proxy.region.getCities(form.value.provinceCode);
  cities.value.unshift({ code: "", name: "全部" });
  districts.value = proxy.region.getDistricts(form.value.cityCode);
  districts.value.unshift({ code: "", name: "全部" });
  console.log("省市区", cities.value, districts.value);
}

function handleDelFile(index) {
  proxy.$modal
    .confirm("是否确认删除选中的数据项？")
    .then(function () {
      fileList.value.splice(index, 1);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功！");
    })
    .catch(() => {});
}

init();
// 暴露给父组件的方法
defineExpose({
  open,
});
</script>

<style>
.radio-scroll .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  color: rgb(64, 158, 255);
  background-color: rgba(0, 0, 0, 0);
  border-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0) rgb(64, 158, 255)
    rgba(0, 0, 0, 0);
  border-style: none none solid none;
  border-width: 0 0 3px 0;
  box-shadow: none;
}

.radio-scroll .el-radio-button__inner {
  border: none;
  background-color: rgba(0, 0, 0, 0);
  border-color: rgba(0, 0, 0, 0);
  border-style: none none solid none;
  border-width: 0 0 3px 0;
  box-shadow: none;
}

.radio-scroll .el-radio-button:first-child .el-radio-button__inner {
  border-left: none;
  border-radius: 0 0 0 0;
}

.radio-scroll .el-radio-button:last-child .el-radio-button__inner {
  border-radius: 0 0 0 0;
}

/* .company-list .detail-head {
  margin-bottom: 10px;
} */
</style>

<script>
var inputField = document.getElementById("inputField");
if (inputField) {
  console.log("事件监听");
  inputField.addEventListener("input", function () {});
}
</script>